/src/testdir/build/lua-master/source/lstrlib.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | ** $Id: lstrlib.c $ |
3 | | ** Standard library for string operations and pattern-matching |
4 | | ** See Copyright Notice in lua.h |
5 | | */ |
6 | | |
7 | | #define lstrlib_c |
8 | | #define LUA_LIB |
9 | | |
10 | | #include "lprefix.h" |
11 | | |
12 | | |
13 | | #include <ctype.h> |
14 | | #include <float.h> |
15 | | #include <limits.h> |
16 | | #include <locale.h> |
17 | | #include <math.h> |
18 | | #include <stddef.h> |
19 | | #include <stdio.h> |
20 | | #include <stdlib.h> |
21 | | #include <string.h> |
22 | | |
23 | | #include "lua.h" |
24 | | |
25 | | #include "lauxlib.h" |
26 | | #include "lualib.h" |
27 | | |
28 | | |
29 | | /* |
30 | | ** maximum number of captures that a pattern can do during |
31 | | ** pattern-matching. This limit is arbitrary, but must fit in |
32 | | ** an unsigned char. |
33 | | */ |
34 | | #if !defined(LUA_MAXCAPTURES) |
35 | 0 | #define LUA_MAXCAPTURES 32 |
36 | | #endif |
37 | | |
38 | | |
39 | | /* macro to 'unsign' a character */ |
40 | 3.66M | #define uchar(c) ((unsigned char)(c)) |
41 | | |
42 | | |
43 | | /* |
44 | | ** Some sizes are better limited to fit in 'int', but must also fit in |
45 | | ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) |
46 | | */ |
47 | 0 | #define MAX_SIZET ((size_t)(~(size_t)0)) |
48 | | |
49 | | #define MAXSIZE \ |
50 | 45.6k | (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) |
51 | | |
52 | | |
53 | | |
54 | | |
55 | 0 | static int str_len (lua_State *L) { |
56 | 0 | size_t l; |
57 | 0 | luaL_checklstring(L, 1, &l); |
58 | 0 | lua_pushinteger(L, (lua_Integer)l); |
59 | 0 | return 1; |
60 | 0 | } |
61 | | |
62 | | |
63 | | /* |
64 | | ** translate a relative initial string position |
65 | | ** (negative means back from end): clip result to [1, inf). |
66 | | ** The length of any string in Lua must fit in a lua_Integer, |
67 | | ** so there are no overflows in the casts. |
68 | | ** The inverted comparison avoids a possible overflow |
69 | | ** computing '-pos'. |
70 | | */ |
71 | 4.85k | static size_t posrelatI (lua_Integer pos, size_t len) { |
72 | 4.85k | if (pos > 0) |
73 | 2.49k | return (size_t)pos; |
74 | 2.36k | else if (pos == 0) |
75 | 932 | return 1; |
76 | 1.42k | else if (pos < -(lua_Integer)len) /* inverted comparison */ |
77 | 1.04k | return 1; /* clip to 1 */ |
78 | 381 | else return len + (size_t)pos + 1; |
79 | 4.85k | } |
80 | | |
81 | | |
82 | | /* |
83 | | ** Gets an optional ending string position from argument 'arg', |
84 | | ** with default value 'def'. |
85 | | ** Negative means back from end: clip result to [0, len] |
86 | | */ |
87 | | static size_t getendpos (lua_State *L, int arg, lua_Integer def, |
88 | 2.22k | size_t len) { |
89 | 2.22k | lua_Integer pos = luaL_optinteger(L, arg, def); |
90 | 2.22k | if (pos > (lua_Integer)len) |
91 | 351 | return len; |
92 | 1.87k | else if (pos >= 0) |
93 | 1.12k | return (size_t)pos; |
94 | 748 | else if (pos < -(lua_Integer)len) |
95 | 678 | return 0; |
96 | 70 | else return len + (size_t)pos + 1; |
97 | 2.22k | } |
98 | | |
99 | | |
100 | 723 | static int str_sub (lua_State *L) { |
101 | 723 | size_t l; |
102 | 723 | const char *s = luaL_checklstring(L, 1, &l); |
103 | 723 | size_t start = posrelatI(luaL_checkinteger(L, 2), l); |
104 | 723 | size_t end = getendpos(L, 3, -1, l); |
105 | 723 | if (start <= end) |
106 | 39 | lua_pushlstring(L, s + start - 1, (end - start) + 1); |
107 | 684 | else lua_pushliteral(L, ""); |
108 | 723 | return 1; |
109 | 723 | } |
110 | | |
111 | | |
112 | 0 | static int str_reverse (lua_State *L) { |
113 | 0 | size_t l, i; |
114 | 0 | luaL_Buffer b; |
115 | 0 | const char *s = luaL_checklstring(L, 1, &l); |
116 | 0 | char *p = luaL_buffinitsize(L, &b, l); |
117 | 0 | for (i = 0; i < l; i++) |
118 | 0 | p[i] = s[l - i - 1]; |
119 | 0 | luaL_pushresultsize(&b, l); |
120 | 0 | return 1; |
121 | 0 | } |
122 | | |
123 | | |
124 | 0 | static int str_lower (lua_State *L) { |
125 | 0 | size_t l; |
126 | 0 | size_t i; |
127 | 0 | luaL_Buffer b; |
128 | 0 | const char *s = luaL_checklstring(L, 1, &l); |
129 | 0 | char *p = luaL_buffinitsize(L, &b, l); |
130 | 0 | for (i=0; i<l; i++) |
131 | 0 | p[i] = tolower(uchar(s[i])); |
132 | 0 | luaL_pushresultsize(&b, l); |
133 | 0 | return 1; |
134 | 0 | } |
135 | | |
136 | | |
137 | 132 | static int str_upper (lua_State *L) { |
138 | 132 | size_t l; |
139 | 132 | size_t i; |
140 | 132 | luaL_Buffer b; |
141 | 132 | const char *s = luaL_checklstring(L, 1, &l); |
142 | 132 | char *p = luaL_buffinitsize(L, &b, l); |
143 | 792 | for (i=0; i<l; i++) |
144 | 660 | p[i] = toupper(uchar(s[i])); |
145 | 132 | luaL_pushresultsize(&b, l); |
146 | 132 | return 1; |
147 | 132 | } |
148 | | |
149 | | |
150 | 19.1k | static int str_rep (lua_State *L) { |
151 | 19.1k | size_t l, lsep; |
152 | 19.1k | const char *s = luaL_checklstring(L, 1, &l); |
153 | 19.1k | lua_Integer n = luaL_checkinteger(L, 2); |
154 | 19.1k | const char *sep = luaL_optlstring(L, 3, "", &lsep); |
155 | 19.1k | if (n <= 0) |
156 | 2.93k | lua_pushliteral(L, ""); |
157 | 16.1k | else if (l_unlikely(l + lsep < l || l + lsep > MAXSIZE / n)) |
158 | 6 | return luaL_error(L, "resulting string too large"); |
159 | 16.1k | else { |
160 | 16.1k | size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; |
161 | 16.1k | luaL_Buffer b; |
162 | 16.1k | char *p = luaL_buffinitsize(L, &b, totallen); |
163 | 85.2M | while (n-- > 1) { /* first n-1 copies (followed by separator) */ |
164 | 85.2M | memcpy(p, s, l * sizeof(char)); p += l; |
165 | 85.2M | if (lsep > 0) { /* empty 'memcpy' is not that cheap */ |
166 | 82.1M | memcpy(p, sep, lsep * sizeof(char)); |
167 | 82.1M | p += lsep; |
168 | 82.1M | } |
169 | 85.2M | } |
170 | 16.1k | memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ |
171 | 16.1k | luaL_pushresultsize(&b, totallen); |
172 | 16.1k | } |
173 | 19.0k | return 1; |
174 | 19.1k | } |
175 | | |
176 | | |
177 | 1.50k | static int str_byte (lua_State *L) { |
178 | 1.50k | size_t l; |
179 | 1.50k | const char *s = luaL_checklstring(L, 1, &l); |
180 | 1.50k | lua_Integer pi = luaL_optinteger(L, 2, 1); |
181 | 1.50k | size_t posi = posrelatI(pi, l); |
182 | 1.50k | size_t pose = getendpos(L, 3, pi, l); |
183 | 1.50k | int n, i; |
184 | 1.50k | if (posi > pose) return 0; /* empty interval; return no values */ |
185 | 962 | if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */ |
186 | 0 | return luaL_error(L, "string slice too long"); |
187 | 962 | n = (int)(pose - posi) + 1; |
188 | 962 | luaL_checkstack(L, n, "string slice too long"); |
189 | 1.60M | for (i=0; i<n; i++) |
190 | 1.60M | lua_pushinteger(L, uchar(s[posi+i-1])); |
191 | 962 | return n; |
192 | 962 | } |
193 | | |
194 | | |
195 | 431 | static int str_char (lua_State *L) { |
196 | 431 | int n = lua_gettop(L); /* number of arguments */ |
197 | 431 | int i; |
198 | 431 | luaL_Buffer b; |
199 | 431 | char *p = luaL_buffinitsize(L, &b, n); |
200 | 971 | for (i=1; i<=n; i++) { |
201 | 540 | lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i); |
202 | 540 | luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range"); |
203 | 540 | p[i - 1] = uchar(c); |
204 | 540 | } |
205 | 431 | luaL_pushresultsize(&b, n); |
206 | 431 | return 1; |
207 | 431 | } |
208 | | |
209 | | |
210 | | /* |
211 | | ** Buffer to store the result of 'string.dump'. It must be initialized |
212 | | ** after the call to 'lua_dump', to ensure that the function is on the |
213 | | ** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might |
214 | | ** push stuff.) |
215 | | */ |
216 | | struct str_Writer { |
217 | | int init; /* true iff buffer has been initialized */ |
218 | | luaL_Buffer B; |
219 | | }; |
220 | | |
221 | | |
222 | 244k | static int writer (lua_State *L, const void *b, size_t size, void *ud) { |
223 | 244k | struct str_Writer *state = (struct str_Writer *)ud; |
224 | 244k | if (!state->init) { |
225 | 1.70k | state->init = 1; |
226 | 1.70k | luaL_buffinit(L, &state->B); |
227 | 1.70k | } |
228 | 244k | luaL_addlstring(&state->B, (const char *)b, size); |
229 | 244k | return 0; |
230 | 244k | } |
231 | | |
232 | | |
233 | 1.70k | static int str_dump (lua_State *L) { |
234 | 1.70k | struct str_Writer state; |
235 | 1.70k | int strip = lua_toboolean(L, 2); |
236 | 1.70k | luaL_checktype(L, 1, LUA_TFUNCTION); |
237 | 1.70k | lua_settop(L, 1); /* ensure function is on the top of the stack */ |
238 | 1.70k | state.init = 0; |
239 | 1.70k | if (l_unlikely(lua_dump(L, writer, &state, strip) != 0)) |
240 | 0 | return luaL_error(L, "unable to dump given function"); |
241 | 1.70k | luaL_pushresult(&state.B); |
242 | 1.70k | return 1; |
243 | 1.70k | } |
244 | | |
245 | | |
246 | | |
247 | | /* |
248 | | ** {====================================================== |
249 | | ** METAMETHODS |
250 | | ** ======================================================= |
251 | | */ |
252 | | |
253 | | #if defined(LUA_NOCVTS2N) /* { */ |
254 | | |
255 | | /* no coercion from strings to numbers */ |
256 | | |
257 | | static const luaL_Reg stringmetamethods[] = { |
258 | | {"__index", NULL}, /* placeholder */ |
259 | | {NULL, NULL} |
260 | | }; |
261 | | |
262 | | #else /* }{ */ |
263 | | |
264 | 31.4k | static int tonum (lua_State *L, int arg) { |
265 | 31.4k | if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */ |
266 | 11.2k | lua_pushvalue(L, arg); |
267 | 11.2k | return 1; |
268 | 11.2k | } |
269 | 20.2k | else { /* check whether it is a numerical string */ |
270 | 20.2k | size_t len; |
271 | 20.2k | const char *s = lua_tolstring(L, arg, &len); |
272 | 20.2k | return (s != NULL && lua_stringtonumber(L, s) == len + 1); |
273 | 20.2k | } |
274 | 31.4k | } |
275 | | |
276 | | |
277 | 143 | static void trymt (lua_State *L, const char *mtname) { |
278 | 143 | lua_settop(L, 2); /* back to the original arguments */ |
279 | 143 | if (l_unlikely(lua_type(L, 2) == LUA_TSTRING || |
280 | 143 | !luaL_getmetafield(L, 2, mtname))) |
281 | 143 | luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2, |
282 | 143 | luaL_typename(L, -2), luaL_typename(L, -1)); |
283 | 143 | lua_insert(L, -3); /* put metamethod before arguments */ |
284 | 143 | lua_call(L, 2, 1); /* call metamethod */ |
285 | 143 | } |
286 | | |
287 | | |
288 | 15.7k | static int arith (lua_State *L, int op, const char *mtname) { |
289 | 15.7k | if (tonum(L, 1) && tonum(L, 2)) |
290 | 15.6k | lua_arith(L, op); /* result will be on the top */ |
291 | 143 | else |
292 | 143 | trymt(L, mtname); |
293 | 15.7k | return 1; |
294 | 15.7k | } |
295 | | |
296 | | |
297 | 1.50k | static int arith_add (lua_State *L) { |
298 | 1.50k | return arith(L, LUA_OPADD, "__add"); |
299 | 1.50k | } |
300 | | |
301 | 3.91k | static int arith_sub (lua_State *L) { |
302 | 3.91k | return arith(L, LUA_OPSUB, "__sub"); |
303 | 3.91k | } |
304 | | |
305 | 5.64k | static int arith_mul (lua_State *L) { |
306 | 5.64k | return arith(L, LUA_OPMUL, "__mul"); |
307 | 5.64k | } |
308 | | |
309 | 2.05k | static int arith_mod (lua_State *L) { |
310 | 2.05k | return arith(L, LUA_OPMOD, "__mod"); |
311 | 2.05k | } |
312 | | |
313 | 731 | static int arith_pow (lua_State *L) { |
314 | 731 | return arith(L, LUA_OPPOW, "__pow"); |
315 | 731 | } |
316 | | |
317 | 691 | static int arith_div (lua_State *L) { |
318 | 691 | return arith(L, LUA_OPDIV, "__div"); |
319 | 691 | } |
320 | | |
321 | 312 | static int arith_idiv (lua_State *L) { |
322 | 312 | return arith(L, LUA_OPIDIV, "__idiv"); |
323 | 312 | } |
324 | | |
325 | 933 | static int arith_unm (lua_State *L) { |
326 | 933 | return arith(L, LUA_OPUNM, "__unm"); |
327 | 933 | } |
328 | | |
329 | | |
330 | | static const luaL_Reg stringmetamethods[] = { |
331 | | {"__add", arith_add}, |
332 | | {"__sub", arith_sub}, |
333 | | {"__mul", arith_mul}, |
334 | | {"__mod", arith_mod}, |
335 | | {"__pow", arith_pow}, |
336 | | {"__div", arith_div}, |
337 | | {"__idiv", arith_idiv}, |
338 | | {"__unm", arith_unm}, |
339 | | {"__index", NULL}, /* placeholder */ |
340 | | {NULL, NULL} |
341 | | }; |
342 | | |
343 | | #endif /* } */ |
344 | | |
345 | | /* }====================================================== */ |
346 | | |
347 | | /* |
348 | | ** {====================================================== |
349 | | ** PATTERN MATCHING |
350 | | ** ======================================================= |
351 | | */ |
352 | | |
353 | | |
354 | 0 | #define CAP_UNFINISHED (-1) |
355 | 90.9k | #define CAP_POSITION (-2) |
356 | | |
357 | | |
358 | | typedef struct MatchState { |
359 | | const char *src_init; /* init of source string */ |
360 | | const char *src_end; /* end ('\0') of source string */ |
361 | | const char *p_end; /* end ('\0') of pattern */ |
362 | | lua_State *L; |
363 | | int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ |
364 | | unsigned char level; /* total number of captures (finished or unfinished) */ |
365 | | struct { |
366 | | const char *init; |
367 | | ptrdiff_t len; |
368 | | } capture[LUA_MAXCAPTURES]; |
369 | | } MatchState; |
370 | | |
371 | | |
372 | | /* recursive function */ |
373 | | static const char *match (MatchState *ms, const char *s, const char *p); |
374 | | |
375 | | |
376 | | /* maximum recursion depth for 'match' */ |
377 | | #if !defined(MAXCCALLS) |
378 | 2.08k | #define MAXCCALLS 200 |
379 | | #endif |
380 | | |
381 | | |
382 | 7.46M | #define L_ESC '%' |
383 | 2.01k | #define SPECIALS "^$*+?.([%-" |
384 | | |
385 | | |
386 | 0 | static int check_capture (MatchState *ms, int l) { |
387 | 0 | l -= '1'; |
388 | 0 | if (l_unlikely(l < 0 || l >= ms->level || |
389 | 0 | ms->capture[l].len == CAP_UNFINISHED)) |
390 | 0 | return luaL_error(ms->L, "invalid capture index %%%d", l + 1); |
391 | 0 | return l; |
392 | 0 | } |
393 | | |
394 | | |
395 | 0 | static int capture_to_close (MatchState *ms) { |
396 | 0 | int level = ms->level; |
397 | 0 | for (level--; level>=0; level--) |
398 | 0 | if (ms->capture[level].len == CAP_UNFINISHED) return level; |
399 | 0 | return luaL_error(ms->L, "invalid pattern capture"); |
400 | 0 | } |
401 | | |
402 | | |
403 | 1.02M | static const char *classend (MatchState *ms, const char *p) { |
404 | 1.02M | switch (*p++) { |
405 | 0 | case L_ESC: { |
406 | 0 | if (l_unlikely(p == ms->p_end)) |
407 | 0 | luaL_error(ms->L, "malformed pattern (ends with '%%')"); |
408 | 0 | return p+1; |
409 | 0 | } |
410 | 0 | case '[': { |
411 | 0 | if (*p == '^') p++; |
412 | 0 | do { /* look for a ']' */ |
413 | 0 | if (l_unlikely(p == ms->p_end)) |
414 | 0 | luaL_error(ms->L, "malformed pattern (missing ']')"); |
415 | 0 | if (*(p++) == L_ESC && p < ms->p_end) |
416 | 0 | p++; /* skip escapes (e.g. '%]') */ |
417 | 0 | } while (*p != ']'); |
418 | 0 | return p+1; |
419 | 0 | } |
420 | 1.02M | default: { |
421 | 1.02M | return p; |
422 | 0 | } |
423 | 1.02M | } |
424 | 1.02M | } |
425 | | |
426 | | |
427 | 0 | static int match_class (int c, int cl) { |
428 | 0 | int res; |
429 | 0 | switch (tolower(cl)) { |
430 | 0 | case 'a' : res = isalpha(c); break; |
431 | 0 | case 'c' : res = iscntrl(c); break; |
432 | 0 | case 'd' : res = isdigit(c); break; |
433 | 0 | case 'g' : res = isgraph(c); break; |
434 | 0 | case 'l' : res = islower(c); break; |
435 | 0 | case 'p' : res = ispunct(c); break; |
436 | 0 | case 's' : res = isspace(c); break; |
437 | 0 | case 'u' : res = isupper(c); break; |
438 | 0 | case 'w' : res = isalnum(c); break; |
439 | 0 | case 'x' : res = isxdigit(c); break; |
440 | 0 | case 'z' : res = (c == 0); break; /* deprecated option */ |
441 | 0 | default: return (cl == c); |
442 | 0 | } |
443 | 0 | return (islower(cl) ? res : !res); |
444 | 0 | } |
445 | | |
446 | | |
447 | 0 | static int matchbracketclass (int c, const char *p, const char *ec) { |
448 | 0 | int sig = 1; |
449 | 0 | if (*(p+1) == '^') { |
450 | 0 | sig = 0; |
451 | 0 | p++; /* skip the '^' */ |
452 | 0 | } |
453 | 0 | while (++p < ec) { |
454 | 0 | if (*p == L_ESC) { |
455 | 0 | p++; |
456 | 0 | if (match_class(c, uchar(*p))) |
457 | 0 | return sig; |
458 | 0 | } |
459 | 0 | else if ((*(p+1) == '-') && (p+2 < ec)) { |
460 | 0 | p+=2; |
461 | 0 | if (uchar(*(p-2)) <= c && c <= uchar(*p)) |
462 | 0 | return sig; |
463 | 0 | } |
464 | 0 | else if (uchar(*p) == c) return sig; |
465 | 0 | } |
466 | 0 | return !sig; |
467 | 0 | } |
468 | | |
469 | | |
470 | | static int singlematch (MatchState *ms, const char *s, const char *p, |
471 | 1.02M | const char *ep) { |
472 | 1.02M | if (s >= ms->src_end) |
473 | 1.51k | return 0; |
474 | 1.02M | else { |
475 | 1.02M | int c = uchar(*s); |
476 | 1.02M | switch (*p) { |
477 | 265 | case '.': return 1; /* matches any char */ |
478 | 0 | case L_ESC: return match_class(c, uchar(*(p+1))); |
479 | 0 | case '[': return matchbracketclass(c, p, ep-1); |
480 | 1.02M | default: return (uchar(*p) == c); |
481 | 1.02M | } |
482 | 1.02M | } |
483 | 1.02M | } |
484 | | |
485 | | |
486 | | static const char *matchbalance (MatchState *ms, const char *s, |
487 | 0 | const char *p) { |
488 | 0 | if (l_unlikely(p >= ms->p_end - 1)) |
489 | 0 | luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); |
490 | 0 | if (*s != *p) return NULL; |
491 | 0 | else { |
492 | 0 | int b = *p; |
493 | 0 | int e = *(p+1); |
494 | 0 | int cont = 1; |
495 | 0 | while (++s < ms->src_end) { |
496 | 0 | if (*s == e) { |
497 | 0 | if (--cont == 0) return s+1; |
498 | 0 | } |
499 | 0 | else if (*s == b) cont++; |
500 | 0 | } |
501 | 0 | } |
502 | 0 | return NULL; /* string ends out of balance */ |
503 | 0 | } |
504 | | |
505 | | |
506 | | static const char *max_expand (MatchState *ms, const char *s, |
507 | 0 | const char *p, const char *ep) { |
508 | 0 | ptrdiff_t i = 0; /* counts maximum expand for item */ |
509 | 0 | while (singlematch(ms, s + i, p, ep)) |
510 | 0 | i++; |
511 | | /* keeps trying to match with the maximum repetitions */ |
512 | 0 | while (i>=0) { |
513 | 0 | const char *res = match(ms, (s+i), ep+1); |
514 | 0 | if (res) return res; |
515 | 0 | i--; /* else didn't match; reduce 1 repetition to try again */ |
516 | 0 | } |
517 | 0 | return NULL; |
518 | 0 | } |
519 | | |
520 | | |
521 | | static const char *min_expand (MatchState *ms, const char *s, |
522 | 0 | const char *p, const char *ep) { |
523 | 0 | for (;;) { |
524 | 0 | const char *res = match(ms, s, ep+1); |
525 | 0 | if (res != NULL) |
526 | 0 | return res; |
527 | 0 | else if (singlematch(ms, s, p, ep)) |
528 | 0 | s++; /* try with one more repetition */ |
529 | 0 | else return NULL; |
530 | 0 | } |
531 | 0 | } |
532 | | |
533 | | |
534 | | static const char *start_capture (MatchState *ms, const char *s, |
535 | 0 | const char *p, int what) { |
536 | 0 | const char *res; |
537 | 0 | int level = ms->level; |
538 | 0 | if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); |
539 | 0 | ms->capture[level].init = s; |
540 | 0 | ms->capture[level].len = what; |
541 | 0 | ms->level = level+1; |
542 | 0 | if ((res=match(ms, s, p)) == NULL) /* match failed? */ |
543 | 0 | ms->level--; /* undo capture */ |
544 | 0 | return res; |
545 | 0 | } |
546 | | |
547 | | |
548 | | static const char *end_capture (MatchState *ms, const char *s, |
549 | 0 | const char *p) { |
550 | 0 | int l = capture_to_close(ms); |
551 | 0 | const char *res; |
552 | 0 | ms->capture[l].len = s - ms->capture[l].init; /* close capture */ |
553 | 0 | if ((res = match(ms, s, p)) == NULL) /* match failed? */ |
554 | 0 | ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ |
555 | 0 | return res; |
556 | 0 | } |
557 | | |
558 | | |
559 | 0 | static const char *match_capture (MatchState *ms, const char *s, int l) { |
560 | 0 | size_t len; |
561 | 0 | l = check_capture(ms, l); |
562 | 0 | len = ms->capture[l].len; |
563 | 0 | if ((size_t)(ms->src_end-s) >= len && |
564 | 0 | memcmp(ms->capture[l].init, s, len) == 0) |
565 | 0 | return s+len; |
566 | 0 | else return NULL; |
567 | 0 | } |
568 | | |
569 | | |
570 | 755k | static const char *match (MatchState *ms, const char *s, const char *p) { |
571 | 755k | if (l_unlikely(ms->matchdepth-- == 0)) |
572 | 0 | luaL_error(ms->L, "pattern too complex"); |
573 | 1.12M | init: /* using goto to optimize tail recursion */ |
574 | 1.12M | if (p != ms->p_end) { /* end of pattern? */ |
575 | 1.02M | switch (*p) { |
576 | 0 | case '(': { /* start capture */ |
577 | 0 | if (*(p + 1) == ')') /* position capture? */ |
578 | 0 | s = start_capture(ms, s, p + 2, CAP_POSITION); |
579 | 0 | else |
580 | 0 | s = start_capture(ms, s, p + 1, CAP_UNFINISHED); |
581 | 0 | break; |
582 | 0 | } |
583 | 0 | case ')': { /* end capture */ |
584 | 0 | s = end_capture(ms, s, p + 1); |
585 | 0 | break; |
586 | 0 | } |
587 | 0 | case '$': { |
588 | 0 | if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ |
589 | 0 | goto dflt; /* no; go to default */ |
590 | 0 | s = (s == ms->src_end) ? s : NULL; /* check end of string */ |
591 | 0 | break; |
592 | 0 | } |
593 | 0 | case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ |
594 | 0 | switch (*(p + 1)) { |
595 | 0 | case 'b': { /* balanced string? */ |
596 | 0 | s = matchbalance(ms, s, p + 2); |
597 | 0 | if (s != NULL) { |
598 | 0 | p += 4; goto init; /* return match(ms, s, p + 4); */ |
599 | 0 | } /* else fail (s == NULL) */ |
600 | 0 | break; |
601 | 0 | } |
602 | 0 | case 'f': { /* frontier? */ |
603 | 0 | const char *ep; char previous; |
604 | 0 | p += 2; |
605 | 0 | if (l_unlikely(*p != '[')) |
606 | 0 | luaL_error(ms->L, "missing '[' after '%%f' in pattern"); |
607 | 0 | ep = classend(ms, p); /* points to what is next */ |
608 | 0 | previous = (s == ms->src_init) ? '\0' : *(s - 1); |
609 | 0 | if (!matchbracketclass(uchar(previous), p, ep - 1) && |
610 | 0 | matchbracketclass(uchar(*s), p, ep - 1)) { |
611 | 0 | p = ep; goto init; /* return match(ms, s, ep); */ |
612 | 0 | } |
613 | 0 | s = NULL; /* match failed */ |
614 | 0 | break; |
615 | 0 | } |
616 | 0 | case '0': case '1': case '2': case '3': |
617 | 0 | case '4': case '5': case '6': case '7': |
618 | 0 | case '8': case '9': { /* capture results (%0-%9)? */ |
619 | 0 | s = match_capture(ms, s, uchar(*(p + 1))); |
620 | 0 | if (s != NULL) { |
621 | 0 | p += 2; goto init; /* return match(ms, s, p + 2) */ |
622 | 0 | } |
623 | 0 | break; |
624 | 0 | } |
625 | 0 | default: goto dflt; |
626 | 0 | } |
627 | 0 | break; |
628 | 0 | } |
629 | 1.02M | default: dflt: { /* pattern class plus optional suffix */ |
630 | 1.02M | const char *ep = classend(ms, p); /* points to optional suffix */ |
631 | | /* does not match at least once? */ |
632 | 1.02M | if (!singlematch(ms, s, p, ep)) { |
633 | 663k | if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ |
634 | 0 | p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ |
635 | 0 | } |
636 | 663k | else /* '+' or no suffix */ |
637 | 663k | s = NULL; /* fail */ |
638 | 663k | } |
639 | 365k | else { /* matched once */ |
640 | 365k | switch (*ep) { /* handle optional suffix */ |
641 | 0 | case '?': { /* optional */ |
642 | 0 | const char *res; |
643 | 0 | if ((res = match(ms, s + 1, ep + 1)) != NULL) |
644 | 0 | s = res; |
645 | 0 | else { |
646 | 0 | p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ |
647 | 0 | } |
648 | 0 | break; |
649 | 0 | } |
650 | 0 | case '+': /* 1 or more repetitions */ |
651 | 0 | s++; /* 1 match already done */ |
652 | | /* FALLTHROUGH */ |
653 | 0 | case '*': /* 0 or more repetitions */ |
654 | 0 | s = max_expand(ms, s, p, ep); |
655 | 0 | break; |
656 | 0 | case '-': /* 0 or more repetitions (minimum) */ |
657 | 0 | s = min_expand(ms, s, p, ep); |
658 | 0 | break; |
659 | 365k | default: /* no suffix */ |
660 | 365k | s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ |
661 | 365k | } |
662 | 365k | } |
663 | 663k | break; |
664 | 1.02M | } |
665 | 1.02M | } |
666 | 1.02M | } |
667 | 755k | ms->matchdepth++; |
668 | 755k | return s; |
669 | 1.12M | } |
670 | | |
671 | | |
672 | | |
673 | | static const char *lmemfind (const char *s1, size_t l1, |
674 | 1.82k | const char *s2, size_t l2) { |
675 | 1.82k | if (l2 == 0) return s1; /* empty strings are everywhere */ |
676 | 1.78k | else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ |
677 | 1.69k | else { |
678 | 1.69k | const char *init; /* to search for a '*s2' inside 's1' */ |
679 | 1.69k | l2--; /* 1st char will be checked by 'memchr' */ |
680 | 1.69k | l1 = l1-l2; /* 's2' cannot be found after that */ |
681 | 1.79k | while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { |
682 | 1.07k | init++; /* 1st char is already checked */ |
683 | 1.07k | if (memcmp(init, s2+1, l2) == 0) |
684 | 967 | return init-1; |
685 | 107 | else { /* correct 'l1' and 's1' to try again */ |
686 | 107 | l1 -= init-s1; |
687 | 107 | s1 = init; |
688 | 107 | } |
689 | 1.07k | } |
690 | 725 | return NULL; /* not found */ |
691 | 1.69k | } |
692 | 1.82k | } |
693 | | |
694 | | |
695 | | /* |
696 | | ** get information about the i-th capture. If there are no captures |
697 | | ** and 'i==0', return information about the whole match, which |
698 | | ** is the range 's'..'e'. If the capture is a string, return |
699 | | ** its length and put its address in '*cap'. If it is an integer |
700 | | ** (a position), push it on the stack and return CAP_POSITION. |
701 | | */ |
702 | | static size_t get_onecapture (MatchState *ms, int i, const char *s, |
703 | 90.9k | const char *e, const char **cap) { |
704 | 90.9k | if (i >= ms->level) { |
705 | 90.9k | if (l_unlikely(i != 0)) |
706 | 0 | luaL_error(ms->L, "invalid capture index %%%d", i + 1); |
707 | 90.9k | *cap = s; |
708 | 90.9k | return e - s; |
709 | 90.9k | } |
710 | 0 | else { |
711 | 0 | ptrdiff_t capl = ms->capture[i].len; |
712 | 0 | *cap = ms->capture[i].init; |
713 | 0 | if (l_unlikely(capl == CAP_UNFINISHED)) |
714 | 0 | luaL_error(ms->L, "unfinished capture"); |
715 | 0 | else if (capl == CAP_POSITION) |
716 | 0 | lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); |
717 | 0 | return capl; |
718 | 0 | } |
719 | 90.9k | } |
720 | | |
721 | | |
722 | | /* |
723 | | ** Push the i-th capture on the stack. |
724 | | */ |
725 | | static void push_onecapture (MatchState *ms, int i, const char *s, |
726 | 90.9k | const char *e) { |
727 | 90.9k | const char *cap; |
728 | 90.9k | ptrdiff_t l = get_onecapture(ms, i, s, e, &cap); |
729 | 90.9k | if (l != CAP_POSITION) |
730 | 90.9k | lua_pushlstring(ms->L, cap, l); |
731 | | /* else position was already pushed */ |
732 | 90.9k | } |
733 | | |
734 | | |
735 | 1.22k | static int push_captures (MatchState *ms, const char *s, const char *e) { |
736 | 1.22k | int i; |
737 | 1.22k | int nlevels = (ms->level == 0 && s) ? 1 : ms->level; |
738 | 1.22k | luaL_checkstack(ms->L, nlevels, "too many captures"); |
739 | 2.19k | for (i = 0; i < nlevels; i++) |
740 | 966 | push_onecapture(ms, i, s, e); |
741 | 1.22k | return nlevels; /* number of strings pushed */ |
742 | 1.22k | } |
743 | | |
744 | | |
745 | | /* check whether pattern has no special characters */ |
746 | 2.01k | static int nospecials (const char *p, size_t l) { |
747 | 2.01k | size_t upto = 0; |
748 | 2.01k | do { |
749 | 2.01k | if (strpbrk(p + upto, SPECIALS)) |
750 | 725 | return 0; /* pattern has a special character */ |
751 | 1.29k | upto += strlen(p + upto) + 1; /* may have more after \0 */ |
752 | 1.29k | } while (upto <= l); |
753 | 1.29k | return 1; /* no special chars found */ |
754 | 2.01k | } |
755 | | |
756 | | |
757 | | static void prepstate (MatchState *ms, lua_State *L, |
758 | 2.08k | const char *s, size_t ls, const char *p, size_t lp) { |
759 | 2.08k | ms->L = L; |
760 | 2.08k | ms->matchdepth = MAXCCALLS; |
761 | 2.08k | ms->src_init = s; |
762 | 2.08k | ms->src_end = s + ls; |
763 | 2.08k | ms->p_end = p + lp; |
764 | 2.08k | } |
765 | | |
766 | | |
767 | 755k | static void reprepstate (MatchState *ms) { |
768 | 755k | ms->level = 0; |
769 | 755k | lua_assert(ms->matchdepth == MAXCCALLS); |
770 | 755k | } |
771 | | |
772 | | |
773 | 2.62k | static int str_find_aux (lua_State *L, int find) { |
774 | 2.62k | size_t ls, lp; |
775 | 2.62k | const char *s = luaL_checklstring(L, 1, &ls); |
776 | 2.62k | const char *p = luaL_checklstring(L, 2, &lp); |
777 | 2.62k | size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; |
778 | 2.62k | if (init > ls) { /* start after string's end? */ |
779 | 81 | luaL_pushfail(L); /* cannot find anything */ |
780 | 81 | return 1; |
781 | 81 | } |
782 | | /* explicit request or no special characters? */ |
783 | 2.54k | if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { |
784 | | /* do a plain search */ |
785 | 1.82k | const char *s2 = lmemfind(s + init, ls - init, p, lp); |
786 | 1.82k | if (s2) { |
787 | 1.00k | lua_pushinteger(L, (s2 - s) + 1); |
788 | 1.00k | lua_pushinteger(L, (s2 - s) + lp); |
789 | 1.00k | return 2; |
790 | 1.00k | } |
791 | 1.82k | } |
792 | 725 | else { |
793 | 725 | MatchState ms; |
794 | 725 | const char *s1 = s + init; |
795 | 725 | int anchor = (*p == '^'); |
796 | 725 | if (anchor) { |
797 | 0 | p++; lp--; /* skip anchor character */ |
798 | 0 | } |
799 | 725 | prepstate(&ms, L, s, ls, p, lp); |
800 | 2.86k | do { |
801 | 2.86k | const char *res; |
802 | 2.86k | reprepstate(&ms); |
803 | 2.86k | if ((res=match(&ms, s1, p)) != NULL) { |
804 | 263 | if (find) { |
805 | 263 | lua_pushinteger(L, (s1 - s) + 1); /* start */ |
806 | 263 | lua_pushinteger(L, res - s); /* end */ |
807 | 263 | return push_captures(&ms, NULL, 0) + 2; |
808 | 263 | } |
809 | 0 | else |
810 | 0 | return push_captures(&ms, s1, res); |
811 | 263 | } |
812 | 2.86k | } while (s1++ < ms.src_end && !anchor); |
813 | 725 | } |
814 | 1.28k | luaL_pushfail(L); /* not found */ |
815 | 1.28k | return 1; |
816 | 2.54k | } |
817 | | |
818 | | |
819 | 2.62k | static int str_find (lua_State *L) { |
820 | 2.62k | return str_find_aux(L, 1); |
821 | 2.62k | } |
822 | | |
823 | | |
824 | 0 | static int str_match (lua_State *L) { |
825 | 0 | return str_find_aux(L, 0); |
826 | 0 | } |
827 | | |
828 | | |
829 | | /* state for 'gmatch' */ |
830 | | typedef struct GMatchState { |
831 | | const char *src; /* current position */ |
832 | | const char *p; /* pattern */ |
833 | | const char *lastmatch; /* end of last match */ |
834 | | MatchState ms; /* match state */ |
835 | | } GMatchState; |
836 | | |
837 | | |
838 | 0 | static int gmatch_aux (lua_State *L) { |
839 | 0 | GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3)); |
840 | 0 | const char *src; |
841 | 0 | gm->ms.L = L; |
842 | 0 | for (src = gm->src; src <= gm->ms.src_end; src++) { |
843 | 0 | const char *e; |
844 | 0 | reprepstate(&gm->ms); |
845 | 0 | if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) { |
846 | 0 | gm->src = gm->lastmatch = e; |
847 | 0 | return push_captures(&gm->ms, src, e); |
848 | 0 | } |
849 | 0 | } |
850 | 0 | return 0; /* not found */ |
851 | 0 | } |
852 | | |
853 | | |
854 | 0 | static int gmatch (lua_State *L) { |
855 | 0 | size_t ls, lp; |
856 | 0 | const char *s = luaL_checklstring(L, 1, &ls); |
857 | 0 | const char *p = luaL_checklstring(L, 2, &lp); |
858 | 0 | size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1; |
859 | 0 | GMatchState *gm; |
860 | 0 | lua_settop(L, 2); /* keep strings on closure to avoid being collected */ |
861 | 0 | gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0); |
862 | 0 | if (init > ls) /* start after string's end? */ |
863 | 0 | init = ls + 1; /* avoid overflows in 's + init' */ |
864 | 0 | prepstate(&gm->ms, L, s, ls, p, lp); |
865 | 0 | gm->src = s + init; gm->p = p; gm->lastmatch = NULL; |
866 | 0 | lua_pushcclosure(L, gmatch_aux, 3); |
867 | 0 | return 1; |
868 | 0 | } |
869 | | |
870 | | |
871 | | static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, |
872 | 494 | const char *e) { |
873 | 494 | size_t l; |
874 | 494 | lua_State *L = ms->L; |
875 | 494 | const char *news = lua_tolstring(L, 3, &l); |
876 | 494 | const char *p; |
877 | 494 | while ((p = (char *)memchr(news, L_ESC, l)) != NULL) { |
878 | 0 | luaL_addlstring(b, news, p - news); |
879 | 0 | p++; /* skip ESC */ |
880 | 0 | if (*p == L_ESC) /* '%%' */ |
881 | 0 | luaL_addchar(b, *p); |
882 | 0 | else if (*p == '0') /* '%0' */ |
883 | 0 | luaL_addlstring(b, s, e - s); |
884 | 0 | else if (isdigit(uchar(*p))) { /* '%n' */ |
885 | 0 | const char *cap; |
886 | 0 | ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap); |
887 | 0 | if (resl == CAP_POSITION) |
888 | 0 | luaL_addvalue(b); /* add position to accumulated result */ |
889 | 0 | else |
890 | 0 | luaL_addlstring(b, cap, resl); |
891 | 0 | } |
892 | 0 | else |
893 | 0 | luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); |
894 | 0 | l -= p + 1 - news; |
895 | 0 | news = p + 1; |
896 | 0 | } |
897 | 494 | luaL_addlstring(b, news, l); |
898 | 494 | } |
899 | | |
900 | | |
901 | | /* |
902 | | ** Add the replacement value to the string buffer 'b'. |
903 | | ** Return true if the original string was changed. (Function calls and |
904 | | ** table indexing resulting in nil or false do not change the subject.) |
905 | | */ |
906 | | static int add_value (MatchState *ms, luaL_Buffer *b, const char *s, |
907 | 91.4k | const char *e, int tr) { |
908 | 91.4k | lua_State *L = ms->L; |
909 | 91.4k | switch (tr) { |
910 | 966 | case LUA_TFUNCTION: { /* call the function */ |
911 | 966 | int n; |
912 | 966 | lua_pushvalue(L, 3); /* push the function */ |
913 | 966 | n = push_captures(ms, s, e); /* all captures as arguments */ |
914 | 966 | lua_call(L, n, 1); /* call it */ |
915 | 966 | break; |
916 | 0 | } |
917 | 90.0k | case LUA_TTABLE: { /* index the table */ |
918 | 90.0k | push_onecapture(ms, 0, s, e); /* first capture is the index */ |
919 | 90.0k | lua_gettable(L, 3); |
920 | 90.0k | break; |
921 | 0 | } |
922 | 494 | default: { /* LUA_TNUMBER or LUA_TSTRING */ |
923 | 494 | add_s(ms, b, s, e); /* add value to the buffer */ |
924 | 494 | return 1; /* something changed */ |
925 | 0 | } |
926 | 91.4k | } |
927 | 90.9k | if (!lua_toboolean(L, -1)) { /* nil or false? */ |
928 | 90.9k | lua_pop(L, 1); /* remove value */ |
929 | 90.9k | luaL_addlstring(b, s, e - s); /* keep original text */ |
930 | 90.9k | return 0; /* no changes */ |
931 | 90.9k | } |
932 | 72 | else if (l_unlikely(!lua_isstring(L, -1))) |
933 | 0 | return luaL_error(L, "invalid replacement value (a %s)", |
934 | 0 | luaL_typename(L, -1)); |
935 | 72 | else { |
936 | 72 | luaL_addvalue(b); /* add result to accumulator */ |
937 | 72 | return 1; /* something changed */ |
938 | 72 | } |
939 | 90.9k | } |
940 | | |
941 | | |
942 | 1.35k | static int str_gsub (lua_State *L) { |
943 | 1.35k | size_t srcl, lp; |
944 | 1.35k | const char *src = luaL_checklstring(L, 1, &srcl); /* subject */ |
945 | 1.35k | const char *p = luaL_checklstring(L, 2, &lp); /* pattern */ |
946 | 1.35k | const char *lastmatch = NULL; /* end of last match */ |
947 | 1.35k | int tr = lua_type(L, 3); /* replacement type */ |
948 | 1.35k | lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */ |
949 | 1.35k | int anchor = (*p == '^'); |
950 | 1.35k | lua_Integer n = 0; /* replacement count */ |
951 | 1.35k | int changed = 0; /* change flag */ |
952 | 1.35k | MatchState ms; |
953 | 1.35k | luaL_Buffer b; |
954 | 1.35k | luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || |
955 | 1.35k | tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, |
956 | 1.35k | "string/function/table"); |
957 | 1.35k | luaL_buffinit(L, &b); |
958 | 1.35k | if (anchor) { |
959 | 0 | p++; lp--; /* skip anchor character */ |
960 | 0 | } |
961 | 1.35k | prepstate(&ms, L, src, srcl, p, lp); |
962 | 753k | while (n < max_s) { |
963 | 752k | const char *e; |
964 | 752k | reprepstate(&ms); /* (re)prepare state for new match */ |
965 | 752k | if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */ |
966 | 91.4k | n++; |
967 | 91.4k | changed = add_value(&ms, &b, src, e, tr) | changed; |
968 | 91.4k | src = lastmatch = e; |
969 | 91.4k | } |
970 | 661k | else if (src < ms.src_end) /* otherwise, skip one character */ |
971 | 660k | luaL_addchar(&b, *src++); |
972 | 1.05k | else break; /* end of subject */ |
973 | 751k | if (anchor) break; |
974 | 751k | } |
975 | 1.35k | if (!changed) /* no changes? */ |
976 | 840 | lua_pushvalue(L, 1); /* return original string */ |
977 | 518 | else { /* something changed */ |
978 | 518 | luaL_addlstring(&b, src, ms.src_end-src); |
979 | 518 | luaL_pushresult(&b); /* create and return new string */ |
980 | 518 | } |
981 | 1.35k | lua_pushinteger(L, n); /* number of substitutions */ |
982 | 1.35k | return 2; |
983 | 1.35k | } |
984 | | |
985 | | /* }====================================================== */ |
986 | | |
987 | | |
988 | | |
989 | | /* |
990 | | ** {====================================================== |
991 | | ** STRING FORMAT |
992 | | ** ======================================================= |
993 | | */ |
994 | | |
995 | | #if !defined(lua_number2strx) /* { */ |
996 | | |
997 | | /* |
998 | | ** Hexadecimal floating-point formatter |
999 | | */ |
1000 | | |
1001 | | #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) |
1002 | | |
1003 | | |
1004 | | /* |
1005 | | ** Number of bits that goes into the first digit. It can be any value |
1006 | | ** between 1 and 4; the following definition tries to align the number |
1007 | | ** to nibble boundaries by making what is left after that first digit a |
1008 | | ** multiple of 4. |
1009 | | */ |
1010 | | #define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1) |
1011 | | |
1012 | | |
1013 | | /* |
1014 | | ** Add integer part of 'x' to buffer and return new 'x' |
1015 | | */ |
1016 | | static lua_Number adddigit (char *buff, int n, lua_Number x) { |
1017 | | lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ |
1018 | | int d = (int)dd; |
1019 | | buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ |
1020 | | return x - dd; /* return what is left */ |
1021 | | } |
1022 | | |
1023 | | |
1024 | | static int num2straux (char *buff, int sz, lua_Number x) { |
1025 | | /* if 'inf' or 'NaN', format it like '%g' */ |
1026 | | if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL) |
1027 | | return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x); |
1028 | | else if (x == 0) { /* can be -0... */ |
1029 | | /* create "0" or "-0" followed by exponent */ |
1030 | | return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x); |
1031 | | } |
1032 | | else { |
1033 | | int e; |
1034 | | lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ |
1035 | | int n = 0; /* character count */ |
1036 | | if (m < 0) { /* is number negative? */ |
1037 | | buff[n++] = '-'; /* add sign */ |
1038 | | m = -m; /* make it positive */ |
1039 | | } |
1040 | | buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ |
1041 | | m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ |
1042 | | e -= L_NBFD; /* this digit goes before the radix point */ |
1043 | | if (m > 0) { /* more digits? */ |
1044 | | buff[n++] = lua_getlocaledecpoint(); /* add radix point */ |
1045 | | do { /* add as many digits as needed */ |
1046 | | m = adddigit(buff, n++, m * 16); |
1047 | | } while (m > 0); |
1048 | | } |
1049 | | n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */ |
1050 | | lua_assert(n < sz); |
1051 | | return n; |
1052 | | } |
1053 | | } |
1054 | | |
1055 | | |
1056 | | static int lua_number2strx (lua_State *L, char *buff, int sz, |
1057 | | const char *fmt, lua_Number x) { |
1058 | | int n = num2straux(buff, sz, x); |
1059 | | if (fmt[SIZELENMOD] == 'A') { |
1060 | | int i; |
1061 | | for (i = 0; i < n; i++) |
1062 | | buff[i] = toupper(uchar(buff[i])); |
1063 | | } |
1064 | | else if (l_unlikely(fmt[SIZELENMOD] != 'a')) |
1065 | | return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); |
1066 | | return n; |
1067 | | } |
1068 | | |
1069 | | #endif /* } */ |
1070 | | |
1071 | | |
1072 | | /* |
1073 | | ** Maximum size for items formatted with '%f'. This size is produced |
1074 | | ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.', |
1075 | | ** and '\0') + number of decimal digits to represent maxfloat (which |
1076 | | ** is maximum exponent + 1). (99+3+1, adding some extra, 110) |
1077 | | */ |
1078 | 0 | #define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP)) |
1079 | | |
1080 | | |
1081 | | /* |
1082 | | ** All formats except '%f' do not need that large limit. The other |
1083 | | ** float formats use exponents, so that they fit in the 99 limit for |
1084 | | ** significant digits; 's' for large strings and 'q' add items directly |
1085 | | ** to the buffer; all integer formats also fit in the 99 limit. The |
1086 | | ** worst case are floats: they may need 99 significant digits, plus |
1087 | | ** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120. |
1088 | | */ |
1089 | 0 | #define MAX_ITEM 120 |
1090 | | |
1091 | | |
1092 | | /* valid flags in a format specification */ |
1093 | | #if !defined(L_FMTFLAGSF) |
1094 | | |
1095 | | /* valid flags for a, A, e, E, f, F, g, and G conversions */ |
1096 | 0 | #define L_FMTFLAGSF "-+#0 " |
1097 | | |
1098 | | /* valid flags for o, x, and X conversions */ |
1099 | 0 | #define L_FMTFLAGSX "-#0" |
1100 | | |
1101 | | /* valid flags for d and i conversions */ |
1102 | 0 | #define L_FMTFLAGSI "-+0 " |
1103 | | |
1104 | | /* valid flags for u conversions */ |
1105 | 0 | #define L_FMTFLAGSU "-0" |
1106 | | |
1107 | | /* valid flags for c, p, and s conversions */ |
1108 | 0 | #define L_FMTFLAGSC "-" |
1109 | | |
1110 | | #endif |
1111 | | |
1112 | | |
1113 | | /* |
1114 | | ** Maximum size of each format specification (such as "%-099.99d"): |
1115 | | ** Initial '%', flags (up to 5), width (2), period, precision (2), |
1116 | | ** length modifier (8), conversion specifier, and final '\0', plus some |
1117 | | ** extra. |
1118 | | */ |
1119 | 0 | #define MAX_FORMAT 32 |
1120 | | |
1121 | | |
1122 | 0 | static void addquoted (luaL_Buffer *b, const char *s, size_t len) { |
1123 | 0 | luaL_addchar(b, '"'); |
1124 | 0 | while (len--) { |
1125 | 0 | if (*s == '"' || *s == '\\' || *s == '\n') { |
1126 | 0 | luaL_addchar(b, '\\'); |
1127 | 0 | luaL_addchar(b, *s); |
1128 | 0 | } |
1129 | 0 | else if (iscntrl(uchar(*s))) { |
1130 | 0 | char buff[10]; |
1131 | 0 | if (!isdigit(uchar(*(s+1)))) |
1132 | 0 | l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s)); |
1133 | 0 | else |
1134 | 0 | l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s)); |
1135 | 0 | luaL_addstring(b, buff); |
1136 | 0 | } |
1137 | 0 | else |
1138 | 0 | luaL_addchar(b, *s); |
1139 | 0 | s++; |
1140 | 0 | } |
1141 | 0 | luaL_addchar(b, '"'); |
1142 | 0 | } |
1143 | | |
1144 | | |
1145 | | /* |
1146 | | ** Serialize a floating-point number in such a way that it can be |
1147 | | ** scanned back by Lua. Use hexadecimal format for "common" numbers |
1148 | | ** (to preserve precision); inf, -inf, and NaN are handled separately. |
1149 | | ** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.) |
1150 | | */ |
1151 | 0 | static int quotefloat (lua_State *L, char *buff, lua_Number n) { |
1152 | 0 | const char *s; /* for the fixed representations */ |
1153 | 0 | if (n == (lua_Number)HUGE_VAL) /* inf? */ |
1154 | 0 | s = "1e9999"; |
1155 | 0 | else if (n == -(lua_Number)HUGE_VAL) /* -inf? */ |
1156 | 0 | s = "-1e9999"; |
1157 | 0 | else if (n != n) /* NaN? */ |
1158 | 0 | s = "(0/0)"; |
1159 | 0 | else { /* format number as hexadecimal */ |
1160 | 0 | int nb = lua_number2strx(L, buff, MAX_ITEM, |
1161 | 0 | "%" LUA_NUMBER_FRMLEN "a", n); |
1162 | | /* ensures that 'buff' string uses a dot as the radix character */ |
1163 | 0 | if (memchr(buff, '.', nb) == NULL) { /* no dot? */ |
1164 | 0 | char point = lua_getlocaledecpoint(); /* try locale point */ |
1165 | 0 | char *ppoint = (char *)memchr(buff, point, nb); |
1166 | 0 | if (ppoint) *ppoint = '.'; /* change it to a dot */ |
1167 | 0 | } |
1168 | 0 | return nb; |
1169 | 0 | } |
1170 | | /* for the fixed representations */ |
1171 | 0 | return l_sprintf(buff, MAX_ITEM, "%s", s); |
1172 | 0 | } |
1173 | | |
1174 | | |
1175 | 0 | static void addliteral (lua_State *L, luaL_Buffer *b, int arg) { |
1176 | 0 | switch (lua_type(L, arg)) { |
1177 | 0 | case LUA_TSTRING: { |
1178 | 0 | size_t len; |
1179 | 0 | const char *s = lua_tolstring(L, arg, &len); |
1180 | 0 | addquoted(b, s, len); |
1181 | 0 | break; |
1182 | 0 | } |
1183 | 0 | case LUA_TNUMBER: { |
1184 | 0 | char *buff = luaL_prepbuffsize(b, MAX_ITEM); |
1185 | 0 | int nb; |
1186 | 0 | if (!lua_isinteger(L, arg)) /* float? */ |
1187 | 0 | nb = quotefloat(L, buff, lua_tonumber(L, arg)); |
1188 | 0 | else { /* integers */ |
1189 | 0 | lua_Integer n = lua_tointeger(L, arg); |
1190 | 0 | const char *format = (n == LUA_MININTEGER) /* corner case? */ |
1191 | 0 | ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */ |
1192 | 0 | : LUA_INTEGER_FMT; /* else use default format */ |
1193 | 0 | nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n); |
1194 | 0 | } |
1195 | 0 | luaL_addsize(b, nb); |
1196 | 0 | break; |
1197 | 0 | } |
1198 | 0 | case LUA_TNIL: case LUA_TBOOLEAN: { |
1199 | 0 | luaL_tolstring(L, arg, NULL); |
1200 | 0 | luaL_addvalue(b); |
1201 | 0 | break; |
1202 | 0 | } |
1203 | 0 | default: { |
1204 | 0 | luaL_argerror(L, arg, "value has no literal form"); |
1205 | 0 | } |
1206 | 0 | } |
1207 | 0 | } |
1208 | | |
1209 | | |
1210 | 0 | static const char *get2digits (const char *s) { |
1211 | 0 | if (isdigit(uchar(*s))) { |
1212 | 0 | s++; |
1213 | 0 | if (isdigit(uchar(*s))) s++; /* (2 digits at most) */ |
1214 | 0 | } |
1215 | 0 | return s; |
1216 | 0 | } |
1217 | | |
1218 | | |
1219 | | /* |
1220 | | ** Check whether a conversion specification is valid. When called, |
1221 | | ** first character in 'form' must be '%' and last character must |
1222 | | ** be a valid conversion specifier. 'flags' are the accepted flags; |
1223 | | ** 'precision' signals whether to accept a precision. |
1224 | | */ |
1225 | | static void checkformat (lua_State *L, const char *form, const char *flags, |
1226 | 0 | int precision) { |
1227 | 0 | const char *spec = form + 1; /* skip '%' */ |
1228 | 0 | spec += strspn(spec, flags); /* skip flags */ |
1229 | 0 | if (*spec != '0') { /* a width cannot start with '0' */ |
1230 | 0 | spec = get2digits(spec); /* skip width */ |
1231 | 0 | if (*spec == '.' && precision) { |
1232 | 0 | spec++; |
1233 | 0 | spec = get2digits(spec); /* skip precision */ |
1234 | 0 | } |
1235 | 0 | } |
1236 | 0 | if (!isalpha(uchar(*spec))) /* did not go to the end? */ |
1237 | 0 | luaL_error(L, "invalid conversion specification: '%s'", form); |
1238 | 0 | } |
1239 | | |
1240 | | |
1241 | | /* |
1242 | | ** Get a conversion specification and copy it to 'form'. |
1243 | | ** Return the address of its last character. |
1244 | | */ |
1245 | | static const char *getformat (lua_State *L, const char *strfrmt, |
1246 | 0 | char *form) { |
1247 | | /* spans flags, width, and precision ('0' is included as a flag) */ |
1248 | 0 | size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789."); |
1249 | 0 | len++; /* adds following character (should be the specifier) */ |
1250 | | /* still needs space for '%', '\0', plus a length modifier */ |
1251 | 0 | if (len >= MAX_FORMAT - 10) |
1252 | 0 | luaL_error(L, "invalid format (too long)"); |
1253 | 0 | *(form++) = '%'; |
1254 | 0 | memcpy(form, strfrmt, len * sizeof(char)); |
1255 | 0 | *(form + len) = '\0'; |
1256 | 0 | return strfrmt + len - 1; |
1257 | 0 | } |
1258 | | |
1259 | | |
1260 | | /* |
1261 | | ** add length modifier into formats |
1262 | | */ |
1263 | 0 | static void addlenmod (char *form, const char *lenmod) { |
1264 | 0 | size_t l = strlen(form); |
1265 | 0 | size_t lm = strlen(lenmod); |
1266 | 0 | char spec = form[l - 1]; |
1267 | 0 | strcpy(form + l - 1, lenmod); |
1268 | 0 | form[l + lm - 1] = spec; |
1269 | 0 | form[l + lm] = '\0'; |
1270 | 0 | } |
1271 | | |
1272 | | |
1273 | 213 | static int str_format (lua_State *L) { |
1274 | 213 | int top = lua_gettop(L); |
1275 | 213 | int arg = 1; |
1276 | 213 | size_t sfl; |
1277 | 213 | const char *strfrmt = luaL_checklstring(L, arg, &sfl); |
1278 | 213 | const char *strfrmt_end = strfrmt+sfl; |
1279 | 213 | const char *flags; |
1280 | 213 | luaL_Buffer b; |
1281 | 213 | luaL_buffinit(L, &b); |
1282 | 7.46M | while (strfrmt < strfrmt_end) { |
1283 | 7.46M | if (*strfrmt != L_ESC) |
1284 | 7.46M | luaL_addchar(&b, *strfrmt++); |
1285 | 0 | else if (*++strfrmt == L_ESC) |
1286 | 0 | luaL_addchar(&b, *strfrmt++); /* %% */ |
1287 | 0 | else { /* format item */ |
1288 | 0 | char form[MAX_FORMAT]; /* to store the format ('%...') */ |
1289 | 0 | int maxitem = MAX_ITEM; /* maximum length for the result */ |
1290 | 0 | char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */ |
1291 | 0 | int nb = 0; /* number of bytes in result */ |
1292 | 0 | if (++arg > top) |
1293 | 0 | return luaL_argerror(L, arg, "no value"); |
1294 | 0 | strfrmt = getformat(L, strfrmt, form); |
1295 | 0 | switch (*strfrmt++) { |
1296 | 0 | case 'c': { |
1297 | 0 | checkformat(L, form, L_FMTFLAGSC, 0); |
1298 | 0 | nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg)); |
1299 | 0 | break; |
1300 | 0 | } |
1301 | 0 | case 'd': case 'i': |
1302 | 0 | flags = L_FMTFLAGSI; |
1303 | 0 | goto intcase; |
1304 | 0 | case 'u': |
1305 | 0 | flags = L_FMTFLAGSU; |
1306 | 0 | goto intcase; |
1307 | 0 | case 'o': case 'x': case 'X': |
1308 | 0 | flags = L_FMTFLAGSX; |
1309 | 0 | intcase: { |
1310 | 0 | lua_Integer n = luaL_checkinteger(L, arg); |
1311 | 0 | checkformat(L, form, flags, 1); |
1312 | 0 | addlenmod(form, LUA_INTEGER_FRMLEN); |
1313 | 0 | nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n); |
1314 | 0 | break; |
1315 | 0 | } |
1316 | 0 | case 'a': case 'A': |
1317 | 0 | checkformat(L, form, L_FMTFLAGSF, 1); |
1318 | 0 | addlenmod(form, LUA_NUMBER_FRMLEN); |
1319 | 0 | nb = lua_number2strx(L, buff, maxitem, form, |
1320 | 0 | luaL_checknumber(L, arg)); |
1321 | 0 | break; |
1322 | 0 | case 'f': |
1323 | 0 | maxitem = MAX_ITEMF; /* extra space for '%f' */ |
1324 | 0 | buff = luaL_prepbuffsize(&b, maxitem); |
1325 | | /* FALLTHROUGH */ |
1326 | 0 | case 'e': case 'E': case 'g': case 'G': { |
1327 | 0 | lua_Number n = luaL_checknumber(L, arg); |
1328 | 0 | checkformat(L, form, L_FMTFLAGSF, 1); |
1329 | 0 | addlenmod(form, LUA_NUMBER_FRMLEN); |
1330 | 0 | nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n); |
1331 | 0 | break; |
1332 | 0 | } |
1333 | 0 | case 'p': { |
1334 | 0 | const void *p = lua_topointer(L, arg); |
1335 | 0 | checkformat(L, form, L_FMTFLAGSC, 0); |
1336 | 0 | if (p == NULL) { /* avoid calling 'printf' with argument NULL */ |
1337 | 0 | p = "(null)"; /* result */ |
1338 | 0 | form[strlen(form) - 1] = 's'; /* format it as a string */ |
1339 | 0 | } |
1340 | 0 | nb = l_sprintf(buff, maxitem, form, p); |
1341 | 0 | break; |
1342 | 0 | } |
1343 | 0 | case 'q': { |
1344 | 0 | if (form[2] != '\0') /* modifiers? */ |
1345 | 0 | return luaL_error(L, "specifier '%%q' cannot have modifiers"); |
1346 | 0 | addliteral(L, &b, arg); |
1347 | 0 | break; |
1348 | 0 | } |
1349 | 0 | case 's': { |
1350 | 0 | size_t l; |
1351 | 0 | const char *s = luaL_tolstring(L, arg, &l); |
1352 | 0 | if (form[2] == '\0') /* no modifiers? */ |
1353 | 0 | luaL_addvalue(&b); /* keep entire string */ |
1354 | 0 | else { |
1355 | 0 | luaL_argcheck(L, l == strlen(s), arg, "string contains zeros"); |
1356 | 0 | checkformat(L, form, L_FMTFLAGSC, 1); |
1357 | 0 | if (strchr(form, '.') == NULL && l >= 100) { |
1358 | | /* no precision and string is too long to be formatted */ |
1359 | 0 | luaL_addvalue(&b); /* keep entire string */ |
1360 | 0 | } |
1361 | 0 | else { /* format the string into 'buff' */ |
1362 | 0 | nb = l_sprintf(buff, maxitem, form, s); |
1363 | 0 | lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ |
1364 | 0 | } |
1365 | 0 | } |
1366 | 0 | break; |
1367 | 0 | } |
1368 | 0 | default: { /* also treat cases 'pnLlh' */ |
1369 | 0 | return luaL_error(L, "invalid conversion '%s' to 'format'", form); |
1370 | 0 | } |
1371 | 0 | } |
1372 | 0 | lua_assert(nb < maxitem); |
1373 | 0 | luaL_addsize(&b, nb); |
1374 | 0 | } |
1375 | 7.46M | } |
1376 | 213 | luaL_pushresult(&b); |
1377 | 213 | return 1; |
1378 | 213 | } |
1379 | | |
1380 | | /* }====================================================== */ |
1381 | | |
1382 | | |
1383 | | /* |
1384 | | ** {====================================================== |
1385 | | ** PACK/UNPACK |
1386 | | ** ======================================================= |
1387 | | */ |
1388 | | |
1389 | | |
1390 | | /* value used for padding */ |
1391 | | #if !defined(LUAL_PACKPADBYTE) |
1392 | | #define LUAL_PACKPADBYTE 0x00 |
1393 | | #endif |
1394 | | |
1395 | | /* maximum size for the binary representation of an integer */ |
1396 | 0 | #define MAXINTSIZE 16 |
1397 | | |
1398 | | /* number of bits in a character */ |
1399 | 45.9k | #define NB CHAR_BIT |
1400 | | |
1401 | | /* mask for one character (NB 1's) */ |
1402 | 28.4k | #define MC ((1 << NB) - 1) |
1403 | | |
1404 | | /* size of a lua_Integer */ |
1405 | 807 | #define SZINT ((int)sizeof(lua_Integer)) |
1406 | | |
1407 | | |
1408 | | /* dummy union to get native endianness */ |
1409 | | static const union { |
1410 | | int dummy; |
1411 | | char little; /* true iff machine is little endian */ |
1412 | | } nativeendian = {1}; |
1413 | | |
1414 | | |
1415 | | /* |
1416 | | ** information to pack/unpack stuff |
1417 | | */ |
1418 | | typedef struct Header { |
1419 | | lua_State *L; |
1420 | | int islittle; |
1421 | | int maxalign; |
1422 | | } Header; |
1423 | | |
1424 | | |
1425 | | /* |
1426 | | ** options for pack/unpack |
1427 | | */ |
1428 | | typedef enum KOption { |
1429 | | Kint, /* signed integers */ |
1430 | | Kuint, /* unsigned integers */ |
1431 | | Kfloat, /* single-precision floating-point numbers */ |
1432 | | Knumber, /* Lua "native" floating-point numbers */ |
1433 | | Kdouble, /* double-precision floating-point numbers */ |
1434 | | Kchar, /* fixed-length strings */ |
1435 | | Kstring, /* strings with prefixed length */ |
1436 | | Kzstr, /* zero-terminated strings */ |
1437 | | Kpadding, /* padding */ |
1438 | | Kpaddalign, /* padding for alignment */ |
1439 | | Knop /* no-op (configuration or spaces) */ |
1440 | | } KOption; |
1441 | | |
1442 | | |
1443 | | /* |
1444 | | ** Read an integer numeral from string 'fmt' or return 'df' if |
1445 | | ** there is no numeral |
1446 | | */ |
1447 | 141k | static int digit (int c) { return '0' <= c && c <= '9'; } |
1448 | | |
1449 | 65.7k | static int getnum (const char **fmt, int df) { |
1450 | 65.7k | if (!digit(**fmt)) /* no number? */ |
1451 | 35.5k | return df; /* return default value */ |
1452 | 30.2k | else { |
1453 | 30.2k | int a = 0; |
1454 | 75.9k | do { |
1455 | 75.9k | a = a*10 + (*((*fmt)++) - '0'); |
1456 | 75.9k | } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); |
1457 | 30.2k | return a; |
1458 | 30.2k | } |
1459 | 65.7k | } |
1460 | | |
1461 | | |
1462 | | /* |
1463 | | ** Read an integer numeral and raises an error if it is larger |
1464 | | ** than the maximum size for integers. |
1465 | | */ |
1466 | 45.7k | static int getnumlimit (Header *h, const char **fmt, int df) { |
1467 | 45.7k | int sz = getnum(fmt, df); |
1468 | 45.7k | if (l_unlikely(sz > MAXINTSIZE || sz <= 0)) |
1469 | 0 | return luaL_error(h->L, "integral size (%d) out of limits [1,%d]", |
1470 | 0 | sz, MAXINTSIZE); |
1471 | 45.7k | return sz; |
1472 | 45.7k | } |
1473 | | |
1474 | | |
1475 | | /* |
1476 | | ** Initialize Header |
1477 | | */ |
1478 | 21.4k | static void initheader (lua_State *L, Header *h) { |
1479 | 21.4k | h->L = L; |
1480 | 21.4k | h->islittle = nativeendian.little; |
1481 | 21.4k | h->maxalign = 1; |
1482 | 21.4k | } |
1483 | | |
1484 | | |
1485 | | /* |
1486 | | ** Read and classify next option. 'size' is filled with option's size. |
1487 | | */ |
1488 | 1.26M | static KOption getoption (Header *h, const char **fmt, int *size) { |
1489 | | /* dummy structure to get native alignment requirements */ |
1490 | 1.26M | struct cD { char c; union { LUAI_MAXALIGN; } u; }; |
1491 | 1.26M | int opt = *((*fmt)++); |
1492 | 1.26M | *size = 0; /* default */ |
1493 | 1.26M | switch (opt) { |
1494 | 26 | case 'b': *size = sizeof(char); return Kint; |
1495 | 61 | case 'B': *size = sizeof(char); return Kuint; |
1496 | 0 | case 'h': *size = sizeof(short); return Kint; |
1497 | 48 | case 'H': *size = sizeof(short); return Kuint; |
1498 | 252 | case 'l': *size = sizeof(long); return Kint; |
1499 | 148 | case 'L': *size = sizeof(long); return Kuint; |
1500 | 0 | case 'j': *size = sizeof(lua_Integer); return Kint; |
1501 | 144 | case 'J': *size = sizeof(lua_Integer); return Kuint; |
1502 | 0 | case 'T': *size = sizeof(size_t); return Kuint; |
1503 | 86 | case 'f': *size = sizeof(float); return Kfloat; |
1504 | 86 | case 'n': *size = sizeof(lua_Number); return Knumber; |
1505 | 142 | case 'd': *size = sizeof(double); return Kdouble; |
1506 | 92 | case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; |
1507 | 36 | case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; |
1508 | 10.2k | case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; |
1509 | 20.0k | case 'c': |
1510 | 20.0k | *size = getnum(fmt, -1); |
1511 | 20.0k | if (l_unlikely(*size == -1)) |
1512 | 0 | luaL_error(h->L, "missing size for format option 'c'"); |
1513 | 20.0k | return Kchar; |
1514 | 276 | case 'z': return Kzstr; |
1515 | 64 | case 'x': *size = 1; return Kpadding; |
1516 | 0 | case 'X': return Kpaddalign; |
1517 | 0 | case ' ': break; |
1518 | 1.19M | case '<': h->islittle = 1; break; |
1519 | 0 | case '>': h->islittle = 0; break; |
1520 | 8.84k | case '=': h->islittle = nativeendian.little; break; |
1521 | 35.3k | case '!': { |
1522 | 35.3k | const int maxalign = offsetof(struct cD, u); |
1523 | 35.3k | h->maxalign = getnumlimit(h, fmt, maxalign); |
1524 | 35.3k | break; |
1525 | 0 | } |
1526 | 2 | default: luaL_error(h->L, "invalid format option '%c'", opt); |
1527 | 1.26M | } |
1528 | 1.23M | return Knop; |
1529 | 1.26M | } |
1530 | | |
1531 | | |
1532 | | /* |
1533 | | ** Read, classify, and fill other details about the next option. |
1534 | | ** 'psize' is filled with option's size, 'notoalign' with its |
1535 | | ** alignment requirements. |
1536 | | ** Local variable 'size' gets the size to be aligned. (Kpadal option |
1537 | | ** always gets its full alignment, other options are limited by |
1538 | | ** the maximum alignment ('maxalign'). Kchar option needs no alignment |
1539 | | ** despite its size. |
1540 | | */ |
1541 | | static KOption getdetails (Header *h, size_t totalsize, |
1542 | 1.26M | const char **fmt, int *psize, int *ntoalign) { |
1543 | 1.26M | KOption opt = getoption(h, fmt, psize); |
1544 | 1.26M | int align = *psize; /* usually, alignment follows size */ |
1545 | 1.26M | if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ |
1546 | 0 | if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) |
1547 | 0 | luaL_argerror(h->L, 1, "invalid next option for option 'X'"); |
1548 | 0 | } |
1549 | 1.26M | if (align <= 1 || opt == Kchar) /* need no alignment? */ |
1550 | 1.25M | *ntoalign = 0; |
1551 | 11.2k | else { |
1552 | 11.2k | if (align > h->maxalign) /* enforce maximum alignment */ |
1553 | 2.42k | align = h->maxalign; |
1554 | 11.2k | if (l_unlikely((align & (align - 1)) != 0)) /* not a power of 2? */ |
1555 | 0 | luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); |
1556 | 11.2k | *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); |
1557 | 11.2k | } |
1558 | 1.26M | return opt; |
1559 | 1.26M | } |
1560 | | |
1561 | | |
1562 | | /* |
1563 | | ** Pack integer 'n' with 'size' bytes and 'islittle' endianness. |
1564 | | ** The final 'if' handles the case when 'size' is larger than |
1565 | | ** the size of a Lua integer, correcting the extra sign-extension |
1566 | | ** bytes if necessary (by default they would be zeros). |
1567 | | */ |
1568 | | static void packint (luaL_Buffer *b, lua_Unsigned n, |
1569 | 11.0k | int islittle, int size, int neg) { |
1570 | 11.0k | char *buff = luaL_prepbuffsize(b, size); |
1571 | 11.0k | int i; |
1572 | 11.0k | buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ |
1573 | 28.4k | for (i = 1; i < size; i++) { |
1574 | 17.4k | n >>= NB; |
1575 | 17.4k | buff[islittle ? i : size - 1 - i] = (char)(n & MC); |
1576 | 17.4k | } |
1577 | 11.0k | if (neg && size > SZINT) { /* negative number need sign extension? */ |
1578 | 0 | for (i = SZINT; i < size; i++) /* correct extra bytes */ |
1579 | 0 | buff[islittle ? i : size - 1 - i] = (char)MC; |
1580 | 0 | } |
1581 | 11.0k | luaL_addsize(b, size); /* add result to buffer */ |
1582 | 11.0k | } |
1583 | | |
1584 | | |
1585 | | /* |
1586 | | ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if |
1587 | | ** given 'islittle' is different from native endianness. |
1588 | | */ |
1589 | | static void copywithendian (char *dest, const char *src, |
1590 | 313 | int size, int islittle) { |
1591 | 313 | if (islittle == nativeendian.little) |
1592 | 313 | memcpy(dest, src, size); |
1593 | 0 | else { |
1594 | 0 | dest += size - 1; |
1595 | 0 | while (size-- != 0) |
1596 | 0 | *(dest--) = *(src++); |
1597 | 0 | } |
1598 | 313 | } |
1599 | | |
1600 | | |
1601 | 21.4k | static int str_pack (lua_State *L) { |
1602 | 21.4k | luaL_Buffer b; |
1603 | 21.4k | Header h; |
1604 | 21.4k | const char *fmt = luaL_checkstring(L, 1); /* format string */ |
1605 | 21.4k | int arg = 1; /* current argument to pack */ |
1606 | 21.4k | size_t totalsize = 0; /* accumulate total size of result */ |
1607 | 21.4k | initheader(L, &h); |
1608 | 21.4k | lua_pushnil(L); /* mark to separate arguments from string buffer */ |
1609 | 21.4k | luaL_buffinit(L, &b); |
1610 | 1.29M | while (*fmt != '\0') { |
1611 | 1.26M | int size, ntoalign; |
1612 | 1.26M | KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); |
1613 | 1.26M | totalsize += ntoalign + size; |
1614 | 1.26M | while (ntoalign-- > 0) |
1615 | 0 | luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */ |
1616 | 1.26M | arg++; |
1617 | 1.26M | switch (opt) { |
1618 | 370 | case Kint: { /* signed integers */ |
1619 | 370 | lua_Integer n = luaL_checkinteger(L, arg); |
1620 | 370 | if (size < SZINT) { /* need overflow check? */ |
1621 | 118 | lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); |
1622 | 118 | luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); |
1623 | 118 | } |
1624 | 370 | packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); |
1625 | 370 | break; |
1626 | 0 | } |
1627 | 437 | case Kuint: { /* unsigned integers */ |
1628 | 437 | lua_Integer n = luaL_checkinteger(L, arg); |
1629 | 437 | if (size < SZINT) /* need overflow check? */ |
1630 | 145 | luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), |
1631 | 437 | arg, "unsigned overflow"); |
1632 | 437 | packint(&b, (lua_Unsigned)n, h.islittle, size, 0); |
1633 | 437 | break; |
1634 | 0 | } |
1635 | 86 | case Kfloat: { /* C float */ |
1636 | 86 | float f = (float)luaL_checknumber(L, arg); /* get argument */ |
1637 | 86 | char *buff = luaL_prepbuffsize(&b, sizeof(f)); |
1638 | | /* move 'f' to final result, correcting endianness if needed */ |
1639 | 86 | copywithendian(buff, (char *)&f, sizeof(f), h.islittle); |
1640 | 86 | luaL_addsize(&b, size); |
1641 | 86 | break; |
1642 | 0 | } |
1643 | 86 | case Knumber: { /* Lua float */ |
1644 | 86 | lua_Number f = luaL_checknumber(L, arg); /* get argument */ |
1645 | 86 | char *buff = luaL_prepbuffsize(&b, sizeof(f)); |
1646 | | /* move 'f' to final result, correcting endianness if needed */ |
1647 | 86 | copywithendian(buff, (char *)&f, sizeof(f), h.islittle); |
1648 | 86 | luaL_addsize(&b, size); |
1649 | 86 | break; |
1650 | 0 | } |
1651 | 142 | case Kdouble: { /* C double */ |
1652 | 142 | double f = (double)luaL_checknumber(L, arg); /* get argument */ |
1653 | 142 | char *buff = luaL_prepbuffsize(&b, sizeof(f)); |
1654 | | /* move 'f' to final result, correcting endianness if needed */ |
1655 | 142 | copywithendian(buff, (char *)&f, sizeof(f), h.islittle); |
1656 | 142 | luaL_addsize(&b, size); |
1657 | 142 | break; |
1658 | 0 | } |
1659 | 20.0k | case Kchar: { /* fixed-size string */ |
1660 | 20.0k | size_t len; |
1661 | 20.0k | const char *s = luaL_checklstring(L, arg, &len); |
1662 | 20.0k | luaL_argcheck(L, len <= (size_t)size, arg, |
1663 | 20.0k | "string longer than given size"); |
1664 | 20.0k | luaL_addlstring(&b, s, len); /* add string */ |
1665 | 1.16G | while (len++ < (size_t)size) /* pad extra space */ |
1666 | 1.16G | luaL_addchar(&b, LUAL_PACKPADBYTE); |
1667 | 20.0k | break; |
1668 | 0 | } |
1669 | 10.2k | case Kstring: { /* strings with length count */ |
1670 | 10.2k | size_t len; |
1671 | 10.2k | const char *s = luaL_checklstring(L, arg, &len); |
1672 | 10.2k | luaL_argcheck(L, size >= (int)sizeof(size_t) || |
1673 | 10.2k | len < ((size_t)1 << (size * NB)), |
1674 | 10.2k | arg, "string length does not fit in given size"); |
1675 | 10.2k | packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ |
1676 | 10.2k | luaL_addlstring(&b, s, len); |
1677 | 10.2k | totalsize += len; |
1678 | 10.2k | break; |
1679 | 0 | } |
1680 | 276 | case Kzstr: { /* zero-terminated string */ |
1681 | 276 | size_t len; |
1682 | 276 | const char *s = luaL_checklstring(L, arg, &len); |
1683 | 276 | luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); |
1684 | 276 | luaL_addlstring(&b, s, len); |
1685 | 276 | luaL_addchar(&b, '\0'); /* add zero at the end */ |
1686 | 276 | totalsize += len + 1; |
1687 | 276 | break; |
1688 | 0 | } |
1689 | 64 | case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */ |
1690 | 1.23M | case Kpaddalign: case Knop: |
1691 | 1.23M | arg--; /* undo increment */ |
1692 | 1.23M | break; |
1693 | 1.26M | } |
1694 | 1.26M | } |
1695 | 21.4k | luaL_pushresult(&b); |
1696 | 21.4k | return 1; |
1697 | 21.4k | } |
1698 | | |
1699 | | |
1700 | 0 | static int str_packsize (lua_State *L) { |
1701 | 0 | Header h; |
1702 | 0 | const char *fmt = luaL_checkstring(L, 1); /* format string */ |
1703 | 0 | size_t totalsize = 0; /* accumulate total size of result */ |
1704 | 0 | initheader(L, &h); |
1705 | 0 | while (*fmt != '\0') { |
1706 | 0 | int size, ntoalign; |
1707 | 0 | KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); |
1708 | 0 | luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1, |
1709 | 0 | "variable-length format"); |
1710 | 0 | size += ntoalign; /* total space used by option */ |
1711 | 0 | luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, |
1712 | 0 | "format result too large"); |
1713 | 0 | totalsize += size; |
1714 | 0 | } |
1715 | 0 | lua_pushinteger(L, (lua_Integer)totalsize); |
1716 | 0 | return 1; |
1717 | 0 | } |
1718 | | |
1719 | | |
1720 | | /* |
1721 | | ** Unpack an integer with 'size' bytes and 'islittle' endianness. |
1722 | | ** If size is smaller than the size of a Lua integer and integer |
1723 | | ** is signed, must do sign extension (propagating the sign to the |
1724 | | ** higher bits); if size is larger than the size of a Lua integer, |
1725 | | ** it must check the unread bytes to see whether they do not cause an |
1726 | | ** overflow. |
1727 | | */ |
1728 | | static lua_Integer unpackint (lua_State *L, const char *str, |
1729 | 0 | int islittle, int size, int issigned) { |
1730 | 0 | lua_Unsigned res = 0; |
1731 | 0 | int i; |
1732 | 0 | int limit = (size <= SZINT) ? size : SZINT; |
1733 | 0 | for (i = limit - 1; i >= 0; i--) { |
1734 | 0 | res <<= NB; |
1735 | 0 | res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; |
1736 | 0 | } |
1737 | 0 | if (size < SZINT) { /* real size smaller than lua_Integer? */ |
1738 | 0 | if (issigned) { /* needs sign extension? */ |
1739 | 0 | lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); |
1740 | 0 | res = ((res ^ mask) - mask); /* do sign extension */ |
1741 | 0 | } |
1742 | 0 | } |
1743 | 0 | else if (size > SZINT) { /* must check unread bytes */ |
1744 | 0 | int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; |
1745 | 0 | for (i = limit; i < size; i++) { |
1746 | 0 | if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask)) |
1747 | 0 | luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); |
1748 | 0 | } |
1749 | 0 | } |
1750 | 0 | return (lua_Integer)res; |
1751 | 0 | } |
1752 | | |
1753 | | |
1754 | 0 | static int str_unpack (lua_State *L) { |
1755 | 0 | Header h; |
1756 | 0 | const char *fmt = luaL_checkstring(L, 1); |
1757 | 0 | size_t ld; |
1758 | 0 | const char *data = luaL_checklstring(L, 2, &ld); |
1759 | 0 | size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1; |
1760 | 0 | int n = 0; /* number of results */ |
1761 | 0 | luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); |
1762 | 0 | initheader(L, &h); |
1763 | 0 | while (*fmt != '\0') { |
1764 | 0 | int size, ntoalign; |
1765 | 0 | KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); |
1766 | 0 | luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2, |
1767 | 0 | "data string too short"); |
1768 | 0 | pos += ntoalign; /* skip alignment */ |
1769 | | /* stack space for item + next position */ |
1770 | 0 | luaL_checkstack(L, 2, "too many results"); |
1771 | 0 | n++; |
1772 | 0 | switch (opt) { |
1773 | 0 | case Kint: |
1774 | 0 | case Kuint: { |
1775 | 0 | lua_Integer res = unpackint(L, data + pos, h.islittle, size, |
1776 | 0 | (opt == Kint)); |
1777 | 0 | lua_pushinteger(L, res); |
1778 | 0 | break; |
1779 | 0 | } |
1780 | 0 | case Kfloat: { |
1781 | 0 | float f; |
1782 | 0 | copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); |
1783 | 0 | lua_pushnumber(L, (lua_Number)f); |
1784 | 0 | break; |
1785 | 0 | } |
1786 | 0 | case Knumber: { |
1787 | 0 | lua_Number f; |
1788 | 0 | copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); |
1789 | 0 | lua_pushnumber(L, f); |
1790 | 0 | break; |
1791 | 0 | } |
1792 | 0 | case Kdouble: { |
1793 | 0 | double f; |
1794 | 0 | copywithendian((char *)&f, data + pos, sizeof(f), h.islittle); |
1795 | 0 | lua_pushnumber(L, (lua_Number)f); |
1796 | 0 | break; |
1797 | 0 | } |
1798 | 0 | case Kchar: { |
1799 | 0 | lua_pushlstring(L, data + pos, size); |
1800 | 0 | break; |
1801 | 0 | } |
1802 | 0 | case Kstring: { |
1803 | 0 | size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); |
1804 | 0 | luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short"); |
1805 | 0 | lua_pushlstring(L, data + pos + size, len); |
1806 | 0 | pos += len; /* skip string */ |
1807 | 0 | break; |
1808 | 0 | } |
1809 | 0 | case Kzstr: { |
1810 | 0 | size_t len = strlen(data + pos); |
1811 | 0 | luaL_argcheck(L, pos + len < ld, 2, |
1812 | 0 | "unfinished string for format 'z'"); |
1813 | 0 | lua_pushlstring(L, data + pos, len); |
1814 | 0 | pos += len + 1; /* skip string plus final '\0' */ |
1815 | 0 | break; |
1816 | 0 | } |
1817 | 0 | case Kpaddalign: case Kpadding: case Knop: |
1818 | 0 | n--; /* undo increment */ |
1819 | 0 | break; |
1820 | 0 | } |
1821 | 0 | pos += size; |
1822 | 0 | } |
1823 | 0 | lua_pushinteger(L, pos + 1); /* next position */ |
1824 | 0 | return n + 1; |
1825 | 0 | } |
1826 | | |
1827 | | /* }====================================================== */ |
1828 | | |
1829 | | |
1830 | | static const luaL_Reg strlib[] = { |
1831 | | {"byte", str_byte}, |
1832 | | {"char", str_char}, |
1833 | | {"dump", str_dump}, |
1834 | | {"find", str_find}, |
1835 | | {"format", str_format}, |
1836 | | {"gmatch", gmatch}, |
1837 | | {"gsub", str_gsub}, |
1838 | | {"len", str_len}, |
1839 | | {"lower", str_lower}, |
1840 | | {"match", str_match}, |
1841 | | {"rep", str_rep}, |
1842 | | {"reverse", str_reverse}, |
1843 | | {"sub", str_sub}, |
1844 | | {"upper", str_upper}, |
1845 | | {"pack", str_pack}, |
1846 | | {"packsize", str_packsize}, |
1847 | | {"unpack", str_unpack}, |
1848 | | {NULL, NULL} |
1849 | | }; |
1850 | | |
1851 | | |
1852 | 2.65k | static void createmetatable (lua_State *L) { |
1853 | | /* table to be metatable for strings */ |
1854 | 2.65k | luaL_newlibtable(L, stringmetamethods); |
1855 | 2.65k | luaL_setfuncs(L, stringmetamethods, 0); |
1856 | 2.65k | lua_pushliteral(L, ""); /* dummy string */ |
1857 | 2.65k | lua_pushvalue(L, -2); /* copy table */ |
1858 | 2.65k | lua_setmetatable(L, -2); /* set table as metatable for strings */ |
1859 | 2.65k | lua_pop(L, 1); /* pop dummy string */ |
1860 | 2.65k | lua_pushvalue(L, -2); /* get string library */ |
1861 | 2.65k | lua_setfield(L, -2, "__index"); /* metatable.__index = string */ |
1862 | 2.65k | lua_pop(L, 1); /* pop metatable */ |
1863 | 2.65k | } |
1864 | | |
1865 | | |
1866 | | /* |
1867 | | ** Open string library |
1868 | | */ |
1869 | 2.65k | LUAMOD_API int luaopen_string (lua_State *L) { |
1870 | 2.65k | luaL_newlib(L, strlib); |
1871 | 2.65k | createmetatable(L); |
1872 | 2.65k | return 1; |
1873 | 2.65k | } |
1874 | | |