]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | /* |
2 | ** $Id: lstrlib.c,v 1.229 2015/05/20 17:39:23 roberto Exp $ | |
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 <stddef.h> | |
17 | #include <stdio.h> | |
18 | #include <stdlib.h> | |
19 | #include <string.h> | |
20 | ||
21 | #include "lua.h" | |
22 | ||
23 | #include "lauxlib.h" | |
24 | #include "lualib.h" | |
25 | ||
26 | ||
27 | /* | |
28 | ** maximum number of captures that a pattern can do during | |
29 | ** pattern-matching. This limit is arbitrary. | |
30 | */ | |
31 | #if !defined(LUA_MAXCAPTURES) | |
32 | #define LUA_MAXCAPTURES 32 | |
33 | #endif | |
34 | ||
35 | ||
36 | /* macro to 'unsign' a character */ | |
37 | #define uchar(c) ((unsigned char)(c)) | |
38 | ||
39 | ||
40 | /* | |
41 | ** Some sizes are better limited to fit in 'int', but must also fit in | |
42 | ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) | |
43 | */ | |
44 | #define MAXSIZE \ | |
45 | (sizeof(size_t) < sizeof(int) ? (~(size_t)0) : (size_t)(INT_MAX)) | |
46 | ||
47 | ||
48 | ||
49 | ||
50 | static int str_len (lua_State *L) { | |
51 | size_t l; | |
52 | luaL_checklstring(L, 1, &l); | |
53 | lua_pushinteger(L, (lua_Integer)l); | |
54 | return 1; | |
55 | } | |
56 | ||
57 | ||
58 | /* translate a relative string position: negative means back from end */ | |
59 | static lua_Integer posrelat (lua_Integer pos, size_t len) { | |
60 | if (pos >= 0) return pos; | |
61 | else if (0u - (size_t)pos > len) return 0; | |
62 | else return (lua_Integer)len + pos + 1; | |
63 | } | |
64 | ||
65 | ||
66 | static int str_sub (lua_State *L) { | |
67 | size_t l; | |
68 | const char *s = luaL_checklstring(L, 1, &l); | |
69 | lua_Integer start = posrelat(luaL_checkinteger(L, 2), l); | |
70 | lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l); | |
71 | if (start < 1) start = 1; | |
72 | if (end > (lua_Integer)l) end = l; | |
73 | if (start <= end) | |
74 | lua_pushlstring(L, s + start - 1, (size_t)(end - start) + 1); | |
75 | else lua_pushliteral(L, ""); | |
76 | return 1; | |
77 | } | |
78 | ||
79 | ||
80 | static int str_reverse (lua_State *L) { | |
81 | size_t l, i; | |
82 | luaL_Buffer b; | |
83 | const char *s = luaL_checklstring(L, 1, &l); | |
84 | char *p = luaL_buffinitsize(L, &b, l); | |
85 | for (i = 0; i < l; i++) | |
86 | p[i] = s[l - i - 1]; | |
87 | luaL_pushresultsize(&b, l); | |
88 | return 1; | |
89 | } | |
90 | ||
91 | ||
92 | static int str_lower (lua_State *L) { | |
93 | size_t l; | |
94 | size_t i; | |
95 | luaL_Buffer b; | |
96 | const char *s = luaL_checklstring(L, 1, &l); | |
97 | char *p = luaL_buffinitsize(L, &b, l); | |
98 | for (i=0; i<l; i++) | |
99 | p[i] = tolower(uchar(s[i])); | |
100 | luaL_pushresultsize(&b, l); | |
101 | return 1; | |
102 | } | |
103 | ||
104 | ||
105 | static int str_upper (lua_State *L) { | |
106 | size_t l; | |
107 | size_t i; | |
108 | luaL_Buffer b; | |
109 | const char *s = luaL_checklstring(L, 1, &l); | |
110 | char *p = luaL_buffinitsize(L, &b, l); | |
111 | for (i=0; i<l; i++) | |
112 | p[i] = toupper(uchar(s[i])); | |
113 | luaL_pushresultsize(&b, l); | |
114 | return 1; | |
115 | } | |
116 | ||
117 | ||
118 | static int str_rep (lua_State *L) { | |
119 | size_t l, lsep; | |
120 | const char *s = luaL_checklstring(L, 1, &l); | |
121 | lua_Integer n = luaL_checkinteger(L, 2); | |
122 | const char *sep = luaL_optlstring(L, 3, "", &lsep); | |
123 | if (n <= 0) lua_pushliteral(L, ""); | |
124 | else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */ | |
125 | return luaL_error(L, "resulting string too large"); | |
126 | else { | |
127 | size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; | |
128 | luaL_Buffer b; | |
129 | char *p = luaL_buffinitsize(L, &b, totallen); | |
130 | while (n-- > 1) { /* first n-1 copies (followed by separator) */ | |
131 | memcpy(p, s, l * sizeof(char)); p += l; | |
132 | if (lsep > 0) { /* empty 'memcpy' is not that cheap */ | |
133 | memcpy(p, sep, lsep * sizeof(char)); | |
134 | p += lsep; | |
135 | } | |
136 | } | |
137 | memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ | |
138 | luaL_pushresultsize(&b, totallen); | |
139 | } | |
140 | return 1; | |
141 | } | |
142 | ||
143 | ||
144 | static int str_byte (lua_State *L) { | |
145 | size_t l; | |
146 | const char *s = luaL_checklstring(L, 1, &l); | |
147 | lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l); | |
148 | lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l); | |
149 | int n, i; | |
150 | if (posi < 1) posi = 1; | |
151 | if (pose > (lua_Integer)l) pose = l; | |
152 | if (posi > pose) return 0; /* empty interval; return no values */ | |
153 | if (pose - posi >= INT_MAX) /* arithmetic overflow? */ | |
154 | return luaL_error(L, "string slice too long"); | |
155 | n = (int)(pose - posi) + 1; | |
156 | luaL_checkstack(L, n, "string slice too long"); | |
157 | for (i=0; i<n; i++) | |
158 | lua_pushinteger(L, uchar(s[posi+i-1])); | |
159 | return n; | |
160 | } | |
161 | ||
162 | ||
163 | static int str_char (lua_State *L) { | |
164 | int n = lua_gettop(L); /* number of arguments */ | |
165 | int i; | |
166 | luaL_Buffer b; | |
167 | char *p = luaL_buffinitsize(L, &b, n); | |
168 | for (i=1; i<=n; i++) { | |
169 | lua_Integer c = luaL_checkinteger(L, i); | |
170 | luaL_argcheck(L, uchar(c) == c, i, "value out of range"); | |
171 | p[i - 1] = uchar(c); | |
172 | } | |
173 | luaL_pushresultsize(&b, n); | |
174 | return 1; | |
175 | } | |
176 | ||
177 | ||
178 | static int writer (lua_State *L, const void *b, size_t size, void *B) { | |
179 | (void)L; | |
180 | luaL_addlstring((luaL_Buffer *) B, (const char *)b, size); | |
181 | return 0; | |
182 | } | |
183 | ||
184 | ||
185 | static int str_dump (lua_State *L) { | |
186 | luaL_Buffer b; | |
187 | int strip = lua_toboolean(L, 2); | |
188 | luaL_checktype(L, 1, LUA_TFUNCTION); | |
189 | lua_settop(L, 1); | |
190 | luaL_buffinit(L,&b); | |
191 | if (lua_dump(L, writer, &b, strip) != 0) | |
192 | return luaL_error(L, "unable to dump given function"); | |
193 | luaL_pushresult(&b); | |
194 | return 1; | |
195 | } | |
196 | ||
197 | ||
198 | ||
199 | /* | |
200 | ** {====================================================== | |
201 | ** PATTERN MATCHING | |
202 | ** ======================================================= | |
203 | */ | |
204 | ||
205 | ||
206 | #define CAP_UNFINISHED (-1) | |
207 | #define CAP_POSITION (-2) | |
208 | ||
209 | ||
210 | typedef struct MatchState { | |
211 | int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ | |
212 | const char *src_init; /* init of source string */ | |
213 | const char *src_end; /* end ('\0') of source string */ | |
214 | const char *p_end; /* end ('\0') of pattern */ | |
215 | lua_State *L; | |
216 | int level; /* total number of captures (finished or unfinished) */ | |
217 | struct { | |
218 | const char *init; | |
219 | ptrdiff_t len; | |
220 | } capture[LUA_MAXCAPTURES]; | |
221 | } MatchState; | |
222 | ||
223 | ||
224 | /* recursive function */ | |
225 | static const char *match (MatchState *ms, const char *s, const char *p); | |
226 | ||
227 | ||
228 | /* maximum recursion depth for 'match' */ | |
229 | #if !defined(MAXCCALLS) | |
230 | #define MAXCCALLS 200 | |
231 | #endif | |
232 | ||
233 | ||
234 | #define L_ESC '%' | |
235 | #define SPECIALS "^$*+?.([%-" | |
236 | ||
237 | ||
238 | static int check_capture (MatchState *ms, int l) { | |
239 | l -= '1'; | |
240 | if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) | |
241 | return luaL_error(ms->L, "invalid capture index %%%d", l + 1); | |
242 | return l; | |
243 | } | |
244 | ||
245 | ||
246 | static int capture_to_close (MatchState *ms) { | |
247 | int level = ms->level; | |
248 | for (level--; level>=0; level--) | |
249 | if (ms->capture[level].len == CAP_UNFINISHED) return level; | |
250 | return luaL_error(ms->L, "invalid pattern capture"); | |
251 | } | |
252 | ||
253 | ||
254 | static const char *classend (MatchState *ms, const char *p) { | |
255 | switch (*p++) { | |
256 | case L_ESC: { | |
257 | if (p == ms->p_end) | |
258 | luaL_error(ms->L, "malformed pattern (ends with '%%')"); | |
259 | return p+1; | |
260 | } | |
261 | case '[': { | |
262 | if (*p == '^') p++; | |
263 | do { /* look for a ']' */ | |
264 | if (p == ms->p_end) | |
265 | luaL_error(ms->L, "malformed pattern (missing ']')"); | |
266 | if (*(p++) == L_ESC && p < ms->p_end) | |
267 | p++; /* skip escapes (e.g. '%]') */ | |
268 | } while (*p != ']'); | |
269 | return p+1; | |
270 | } | |
271 | default: { | |
272 | return p; | |
273 | } | |
274 | } | |
275 | } | |
276 | ||
277 | ||
278 | static int match_class (int c, int cl) { | |
279 | int res; | |
280 | switch (tolower(cl)) { | |
281 | case 'a' : res = isalpha(c); break; | |
282 | case 'c' : res = iscntrl(c); break; | |
283 | case 'd' : res = isdigit(c); break; | |
284 | case 'g' : res = isgraph(c); break; | |
285 | case 'l' : res = islower(c); break; | |
286 | case 'p' : res = ispunct(c); break; | |
287 | case 's' : res = isspace(c); break; | |
288 | case 'u' : res = isupper(c); break; | |
289 | case 'w' : res = isalnum(c); break; | |
290 | case 'x' : res = isxdigit(c); break; | |
291 | case 'z' : res = (c == 0); break; /* deprecated option */ | |
292 | default: return (cl == c); | |
293 | } | |
294 | return (islower(cl) ? res : !res); | |
295 | } | |
296 | ||
297 | ||
298 | static int matchbracketclass (int c, const char *p, const char *ec) { | |
299 | int sig = 1; | |
300 | if (*(p+1) == '^') { | |
301 | sig = 0; | |
302 | p++; /* skip the '^' */ | |
303 | } | |
304 | while (++p < ec) { | |
305 | if (*p == L_ESC) { | |
306 | p++; | |
307 | if (match_class(c, uchar(*p))) | |
308 | return sig; | |
309 | } | |
310 | else if ((*(p+1) == '-') && (p+2 < ec)) { | |
311 | p+=2; | |
312 | if (uchar(*(p-2)) <= c && c <= uchar(*p)) | |
313 | return sig; | |
314 | } | |
315 | else if (uchar(*p) == c) return sig; | |
316 | } | |
317 | return !sig; | |
318 | } | |
319 | ||
320 | ||
321 | static int singlematch (MatchState *ms, const char *s, const char *p, | |
322 | const char *ep) { | |
323 | if (s >= ms->src_end) | |
324 | return 0; | |
325 | else { | |
326 | int c = uchar(*s); | |
327 | switch (*p) { | |
328 | case '.': return 1; /* matches any char */ | |
329 | case L_ESC: return match_class(c, uchar(*(p+1))); | |
330 | case '[': return matchbracketclass(c, p, ep-1); | |
331 | default: return (uchar(*p) == c); | |
332 | } | |
333 | } | |
334 | } | |
335 | ||
336 | ||
337 | static const char *matchbalance (MatchState *ms, const char *s, | |
338 | const char *p) { | |
339 | if (p >= ms->p_end - 1) | |
340 | luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')"); | |
341 | if (*s != *p) return NULL; | |
342 | else { | |
343 | int b = *p; | |
344 | int e = *(p+1); | |
345 | int cont = 1; | |
346 | while (++s < ms->src_end) { | |
347 | if (*s == e) { | |
348 | if (--cont == 0) return s+1; | |
349 | } | |
350 | else if (*s == b) cont++; | |
351 | } | |
352 | } | |
353 | return NULL; /* string ends out of balance */ | |
354 | } | |
355 | ||
356 | ||
357 | static const char *max_expand (MatchState *ms, const char *s, | |
358 | const char *p, const char *ep) { | |
359 | ptrdiff_t i = 0; /* counts maximum expand for item */ | |
360 | while (singlematch(ms, s + i, p, ep)) | |
361 | i++; | |
362 | /* keeps trying to match with the maximum repetitions */ | |
363 | while (i>=0) { | |
364 | const char *res = match(ms, (s+i), ep+1); | |
365 | if (res) return res; | |
366 | i--; /* else didn't match; reduce 1 repetition to try again */ | |
367 | } | |
368 | return NULL; | |
369 | } | |
370 | ||
371 | ||
372 | static const char *min_expand (MatchState *ms, const char *s, | |
373 | const char *p, const char *ep) { | |
374 | for (;;) { | |
375 | const char *res = match(ms, s, ep+1); | |
376 | if (res != NULL) | |
377 | return res; | |
378 | else if (singlematch(ms, s, p, ep)) | |
379 | s++; /* try with one more repetition */ | |
380 | else return NULL; | |
381 | } | |
382 | } | |
383 | ||
384 | ||
385 | static const char *start_capture (MatchState *ms, const char *s, | |
386 | const char *p, int what) { | |
387 | const char *res; | |
388 | int level = ms->level; | |
389 | if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); | |
390 | ms->capture[level].init = s; | |
391 | ms->capture[level].len = what; | |
392 | ms->level = level+1; | |
393 | if ((res=match(ms, s, p)) == NULL) /* match failed? */ | |
394 | ms->level--; /* undo capture */ | |
395 | return res; | |
396 | } | |
397 | ||
398 | ||
399 | static const char *end_capture (MatchState *ms, const char *s, | |
400 | const char *p) { | |
401 | int l = capture_to_close(ms); | |
402 | const char *res; | |
403 | ms->capture[l].len = s - ms->capture[l].init; /* close capture */ | |
404 | if ((res = match(ms, s, p)) == NULL) /* match failed? */ | |
405 | ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ | |
406 | return res; | |
407 | } | |
408 | ||
409 | ||
410 | static const char *match_capture (MatchState *ms, const char *s, int l) { | |
411 | size_t len; | |
412 | l = check_capture(ms, l); | |
413 | len = ms->capture[l].len; | |
414 | if ((size_t)(ms->src_end-s) >= len && | |
415 | memcmp(ms->capture[l].init, s, len) == 0) | |
416 | return s+len; | |
417 | else return NULL; | |
418 | } | |
419 | ||
420 | ||
421 | static const char *match (MatchState *ms, const char *s, const char *p) { | |
422 | if (ms->matchdepth-- == 0) | |
423 | luaL_error(ms->L, "pattern too complex"); | |
424 | init: /* using goto's to optimize tail recursion */ | |
425 | if (p != ms->p_end) { /* end of pattern? */ | |
426 | switch (*p) { | |
427 | case '(': { /* start capture */ | |
428 | if (*(p + 1) == ')') /* position capture? */ | |
429 | s = start_capture(ms, s, p + 2, CAP_POSITION); | |
430 | else | |
431 | s = start_capture(ms, s, p + 1, CAP_UNFINISHED); | |
432 | break; | |
433 | } | |
434 | case ')': { /* end capture */ | |
435 | s = end_capture(ms, s, p + 1); | |
436 | break; | |
437 | } | |
438 | case '$': { | |
439 | if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ | |
440 | goto dflt; /* no; go to default */ | |
441 | s = (s == ms->src_end) ? s : NULL; /* check end of string */ | |
442 | break; | |
443 | } | |
444 | case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ | |
445 | switch (*(p + 1)) { | |
446 | case 'b': { /* balanced string? */ | |
447 | s = matchbalance(ms, s, p + 2); | |
448 | if (s != NULL) { | |
449 | p += 4; goto init; /* return match(ms, s, p + 4); */ | |
450 | } /* else fail (s == NULL) */ | |
451 | break; | |
452 | } | |
453 | case 'f': { /* frontier? */ | |
454 | const char *ep; char previous; | |
455 | p += 2; | |
456 | if (*p != '[') | |
457 | luaL_error(ms->L, "missing '[' after '%%f' in pattern"); | |
458 | ep = classend(ms, p); /* points to what is next */ | |
459 | previous = (s == ms->src_init) ? '\0' : *(s - 1); | |
460 | if (!matchbracketclass(uchar(previous), p, ep - 1) && | |
461 | matchbracketclass(uchar(*s), p, ep - 1)) { | |
462 | p = ep; goto init; /* return match(ms, s, ep); */ | |
463 | } | |
464 | s = NULL; /* match failed */ | |
465 | break; | |
466 | } | |
467 | case '0': case '1': case '2': case '3': | |
468 | case '4': case '5': case '6': case '7': | |
469 | case '8': case '9': { /* capture results (%0-%9)? */ | |
470 | s = match_capture(ms, s, uchar(*(p + 1))); | |
471 | if (s != NULL) { | |
472 | p += 2; goto init; /* return match(ms, s, p + 2) */ | |
473 | } | |
474 | break; | |
475 | } | |
476 | default: goto dflt; | |
477 | } | |
478 | break; | |
479 | } | |
480 | default: dflt: { /* pattern class plus optional suffix */ | |
481 | const char *ep = classend(ms, p); /* points to optional suffix */ | |
482 | /* does not match at least once? */ | |
483 | if (!singlematch(ms, s, p, ep)) { | |
484 | if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ | |
485 | p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ | |
486 | } | |
487 | else /* '+' or no suffix */ | |
488 | s = NULL; /* fail */ | |
489 | } | |
490 | else { /* matched once */ | |
491 | switch (*ep) { /* handle optional suffix */ | |
492 | case '?': { /* optional */ | |
493 | const char *res; | |
494 | if ((res = match(ms, s + 1, ep + 1)) != NULL) | |
495 | s = res; | |
496 | else { | |
497 | p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ | |
498 | } | |
499 | break; | |
500 | } | |
501 | case '+': /* 1 or more repetitions */ | |
502 | s++; /* 1 match already done */ | |
503 | /* FALLTHROUGH */ | |
504 | case '*': /* 0 or more repetitions */ | |
505 | s = max_expand(ms, s, p, ep); | |
506 | break; | |
507 | case '-': /* 0 or more repetitions (minimum) */ | |
508 | s = min_expand(ms, s, p, ep); | |
509 | break; | |
510 | default: /* no suffix */ | |
511 | s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ | |
512 | } | |
513 | } | |
514 | break; | |
515 | } | |
516 | } | |
517 | } | |
518 | ms->matchdepth++; | |
519 | return s; | |
520 | } | |
521 | ||
522 | ||
523 | ||
524 | static const char *lmemfind (const char *s1, size_t l1, | |
525 | const char *s2, size_t l2) { | |
526 | if (l2 == 0) return s1; /* empty strings are everywhere */ | |
527 | else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ | |
528 | else { | |
529 | const char *init; /* to search for a '*s2' inside 's1' */ | |
530 | l2--; /* 1st char will be checked by 'memchr' */ | |
531 | l1 = l1-l2; /* 's2' cannot be found after that */ | |
532 | while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { | |
533 | init++; /* 1st char is already checked */ | |
534 | if (memcmp(init, s2+1, l2) == 0) | |
535 | return init-1; | |
536 | else { /* correct 'l1' and 's1' to try again */ | |
537 | l1 -= init-s1; | |
538 | s1 = init; | |
539 | } | |
540 | } | |
541 | return NULL; /* not found */ | |
542 | } | |
543 | } | |
544 | ||
545 | ||
546 | static void push_onecapture (MatchState *ms, int i, const char *s, | |
547 | const char *e) { | |
548 | if (i >= ms->level) { | |
549 | if (i == 0) /* ms->level == 0, too */ | |
550 | lua_pushlstring(ms->L, s, e - s); /* add whole match */ | |
551 | else | |
552 | luaL_error(ms->L, "invalid capture index %%%d", i + 1); | |
553 | } | |
554 | else { | |
555 | ptrdiff_t l = ms->capture[i].len; | |
556 | if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); | |
557 | if (l == CAP_POSITION) | |
558 | lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1); | |
559 | else | |
560 | lua_pushlstring(ms->L, ms->capture[i].init, l); | |
561 | } | |
562 | } | |
563 | ||
564 | ||
565 | static int push_captures (MatchState *ms, const char *s, const char *e) { | |
566 | int i; | |
567 | int nlevels = (ms->level == 0 && s) ? 1 : ms->level; | |
568 | luaL_checkstack(ms->L, nlevels, "too many captures"); | |
569 | for (i = 0; i < nlevels; i++) | |
570 | push_onecapture(ms, i, s, e); | |
571 | return nlevels; /* number of strings pushed */ | |
572 | } | |
573 | ||
574 | ||
575 | /* check whether pattern has no special characters */ | |
576 | static int nospecials (const char *p, size_t l) { | |
577 | size_t upto = 0; | |
578 | do { | |
579 | if (strpbrk(p + upto, SPECIALS)) | |
580 | return 0; /* pattern has a special character */ | |
581 | upto += strlen(p + upto) + 1; /* may have more after \0 */ | |
582 | } while (upto <= l); | |
583 | return 1; /* no special chars found */ | |
584 | } | |
585 | ||
586 | ||
587 | static int str_find_aux (lua_State *L, int find) { | |
588 | size_t ls, lp; | |
589 | const char *s = luaL_checklstring(L, 1, &ls); | |
590 | const char *p = luaL_checklstring(L, 2, &lp); | |
591 | lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls); | |
592 | if (init < 1) init = 1; | |
593 | else if (init > (lua_Integer)ls + 1) { /* start after string's end? */ | |
594 | lua_pushnil(L); /* cannot find anything */ | |
595 | return 1; | |
596 | } | |
597 | /* explicit request or no special characters? */ | |
598 | if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { | |
599 | /* do a plain search */ | |
600 | const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp); | |
601 | if (s2) { | |
602 | lua_pushinteger(L, (s2 - s) + 1); | |
603 | lua_pushinteger(L, (s2 - s) + lp); | |
604 | return 2; | |
605 | } | |
606 | } | |
607 | else { | |
608 | MatchState ms; | |
609 | const char *s1 = s + init - 1; | |
610 | int anchor = (*p == '^'); | |
611 | if (anchor) { | |
612 | p++; lp--; /* skip anchor character */ | |
613 | } | |
614 | ms.L = L; | |
615 | ms.matchdepth = MAXCCALLS; | |
616 | ms.src_init = s; | |
617 | ms.src_end = s + ls; | |
618 | ms.p_end = p + lp; | |
619 | do { | |
620 | const char *res; | |
621 | ms.level = 0; | |
622 | lua_assert(ms.matchdepth == MAXCCALLS); | |
623 | if ((res=match(&ms, s1, p)) != NULL) { | |
624 | if (find) { | |
625 | lua_pushinteger(L, (s1 - s) + 1); /* start */ | |
626 | lua_pushinteger(L, res - s); /* end */ | |
627 | return push_captures(&ms, NULL, 0) + 2; | |
628 | } | |
629 | else | |
630 | return push_captures(&ms, s1, res); | |
631 | } | |
632 | } while (s1++ < ms.src_end && !anchor); | |
633 | } | |
634 | lua_pushnil(L); /* not found */ | |
635 | return 1; | |
636 | } | |
637 | ||
638 | ||
639 | static int str_find (lua_State *L) { | |
640 | return str_find_aux(L, 1); | |
641 | } | |
642 | ||
643 | ||
644 | static int str_match (lua_State *L) { | |
645 | return str_find_aux(L, 0); | |
646 | } | |
647 | ||
648 | ||
649 | static int gmatch_aux (lua_State *L) { | |
650 | MatchState ms; | |
651 | size_t ls, lp; | |
652 | const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); | |
653 | const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp); | |
654 | const char *src; | |
655 | ms.L = L; | |
656 | ms.matchdepth = MAXCCALLS; | |
657 | ms.src_init = s; | |
658 | ms.src_end = s+ls; | |
659 | ms.p_end = p + lp; | |
660 | for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); | |
661 | src <= ms.src_end; | |
662 | src++) { | |
663 | const char *e; | |
664 | ms.level = 0; | |
665 | lua_assert(ms.matchdepth == MAXCCALLS); | |
666 | if ((e = match(&ms, src, p)) != NULL) { | |
667 | lua_Integer newstart = e-s; | |
668 | if (e == src) newstart++; /* empty match? go at least one position */ | |
669 | lua_pushinteger(L, newstart); | |
670 | lua_replace(L, lua_upvalueindex(3)); | |
671 | return push_captures(&ms, src, e); | |
672 | } | |
673 | } | |
674 | return 0; /* not found */ | |
675 | } | |
676 | ||
677 | ||
678 | static int gmatch (lua_State *L) { | |
679 | luaL_checkstring(L, 1); | |
680 | luaL_checkstring(L, 2); | |
681 | lua_settop(L, 2); | |
682 | lua_pushinteger(L, 0); | |
683 | lua_pushcclosure(L, gmatch_aux, 3); | |
684 | return 1; | |
685 | } | |
686 | ||
687 | ||
688 | static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, | |
689 | const char *e) { | |
690 | size_t l, i; | |
691 | lua_State *L = ms->L; | |
692 | const char *news = lua_tolstring(L, 3, &l); | |
693 | for (i = 0; i < l; i++) { | |
694 | if (news[i] != L_ESC) | |
695 | luaL_addchar(b, news[i]); | |
696 | else { | |
697 | i++; /* skip ESC */ | |
698 | if (!isdigit(uchar(news[i]))) { | |
699 | if (news[i] != L_ESC) | |
700 | luaL_error(L, "invalid use of '%c' in replacement string", L_ESC); | |
701 | luaL_addchar(b, news[i]); | |
702 | } | |
703 | else if (news[i] == '0') | |
704 | luaL_addlstring(b, s, e - s); | |
705 | else { | |
706 | push_onecapture(ms, news[i] - '1', s, e); | |
707 | luaL_tolstring(L, -1, NULL); /* if number, convert it to string */ | |
708 | lua_remove(L, -2); /* remove original value */ | |
709 | luaL_addvalue(b); /* add capture to accumulated result */ | |
710 | } | |
711 | } | |
712 | } | |
713 | } | |
714 | ||
715 | ||
716 | static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, | |
717 | const char *e, int tr) { | |
718 | lua_State *L = ms->L; | |
719 | switch (tr) { | |
720 | case LUA_TFUNCTION: { | |
721 | int n; | |
722 | lua_pushvalue(L, 3); | |
723 | n = push_captures(ms, s, e); | |
724 | lua_call(L, n, 1); | |
725 | break; | |
726 | } | |
727 | case LUA_TTABLE: { | |
728 | push_onecapture(ms, 0, s, e); | |
729 | lua_gettable(L, 3); | |
730 | break; | |
731 | } | |
732 | default: { /* LUA_TNUMBER or LUA_TSTRING */ | |
733 | add_s(ms, b, s, e); | |
734 | return; | |
735 | } | |
736 | } | |
737 | if (!lua_toboolean(L, -1)) { /* nil or false? */ | |
738 | lua_pop(L, 1); | |
739 | lua_pushlstring(L, s, e - s); /* keep original text */ | |
740 | } | |
741 | else if (!lua_isstring(L, -1)) | |
742 | luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); | |
743 | luaL_addvalue(b); /* add result to accumulator */ | |
744 | } | |
745 | ||
746 | ||
747 | static int str_gsub (lua_State *L) { | |
748 | size_t srcl, lp; | |
749 | const char *src = luaL_checklstring(L, 1, &srcl); | |
750 | const char *p = luaL_checklstring(L, 2, &lp); | |
751 | int tr = lua_type(L, 3); | |
752 | lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); | |
753 | int anchor = (*p == '^'); | |
754 | lua_Integer n = 0; | |
755 | MatchState ms; | |
756 | luaL_Buffer b; | |
757 | luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || | |
758 | tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, | |
759 | "string/function/table expected"); | |
760 | luaL_buffinit(L, &b); | |
761 | if (anchor) { | |
762 | p++; lp--; /* skip anchor character */ | |
763 | } | |
764 | ms.L = L; | |
765 | ms.matchdepth = MAXCCALLS; | |
766 | ms.src_init = src; | |
767 | ms.src_end = src+srcl; | |
768 | ms.p_end = p + lp; | |
769 | while (n < max_s) { | |
770 | const char *e; | |
771 | ms.level = 0; | |
772 | lua_assert(ms.matchdepth == MAXCCALLS); | |
773 | e = match(&ms, src, p); | |
774 | if (e) { | |
775 | n++; | |
776 | add_value(&ms, &b, src, e, tr); | |
777 | } | |
778 | if (e && e>src) /* non empty match? */ | |
779 | src = e; /* skip it */ | |
780 | else if (src < ms.src_end) | |
781 | luaL_addchar(&b, *src++); | |
782 | else break; | |
783 | if (anchor) break; | |
784 | } | |
785 | luaL_addlstring(&b, src, ms.src_end-src); | |
786 | luaL_pushresult(&b); | |
787 | lua_pushinteger(L, n); /* number of substitutions */ | |
788 | return 2; | |
789 | } | |
790 | ||
791 | /* }====================================================== */ | |
792 | ||
793 | ||
794 | ||
795 | /* | |
796 | ** {====================================================== | |
797 | ** STRING FORMAT | |
798 | ** ======================================================= | |
799 | */ | |
800 | ||
801 | #if !defined(lua_number2strx) /* { */ | |
802 | ||
803 | /* | |
804 | ** Hexadecimal floating-point formatter | |
805 | */ | |
806 | ||
807 | #include <locale.h> | |
808 | #include <math.h> | |
809 | ||
810 | #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char)) | |
811 | ||
812 | ||
813 | /* | |
814 | ** Number of bits that goes into the first digit. It can be any value | |
815 | ** between 1 and 4; the following definition tries to align the number | |
816 | ** to nibble boundaries by making what is left after that first digit a | |
817 | ** multiple of 4. | |
818 | */ | |
819 | #define L_NBFD ((l_mathlim(MANT_DIG) - 1)%4 + 1) | |
820 | ||
821 | ||
822 | /* | |
823 | ** Add integer part of 'x' to buffer and return new 'x' | |
824 | */ | |
825 | static lua_Number adddigit (char *buff, int n, lua_Number x) { | |
826 | lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */ | |
827 | int d = (int)dd; | |
828 | buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */ | |
829 | return x - dd; /* return what is left */ | |
830 | } | |
831 | ||
832 | ||
833 | static int num2straux (char *buff, lua_Number x) { | |
834 | if (x != x || x == HUGE_VAL || x == -HUGE_VAL) /* inf or NaN? */ | |
835 | return sprintf(buff, LUA_NUMBER_FMT, x); /* equal to '%g' */ | |
836 | else if (x == 0) { /* can be -0... */ | |
837 | sprintf(buff, LUA_NUMBER_FMT, x); | |
838 | strcat(buff, "x0p+0"); /* reuses '0/-0' from 'sprintf'... */ | |
839 | return strlen(buff); | |
840 | } | |
841 | else { | |
842 | int e; | |
843 | lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */ | |
844 | int n = 0; /* character count */ | |
845 | if (m < 0) { /* is number negative? */ | |
846 | buff[n++] = '-'; /* add signal */ | |
847 | m = -m; /* make it positive */ | |
848 | } | |
849 | buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */ | |
850 | m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */ | |
851 | e -= L_NBFD; /* this digit goes before the radix point */ | |
852 | if (m > 0) { /* more digits? */ | |
853 | buff[n++] = lua_getlocaledecpoint(); /* add radix point */ | |
854 | do { /* add as many digits as needed */ | |
855 | m = adddigit(buff, n++, m * 16); | |
856 | } while (m > 0); | |
857 | } | |
858 | n += sprintf(buff + n, "p%+d", e); /* add exponent */ | |
859 | return n; | |
860 | } | |
861 | } | |
862 | ||
863 | ||
864 | static int lua_number2strx (lua_State *L, char *buff, const char *fmt, | |
865 | lua_Number x) { | |
866 | int n = num2straux(buff, x); | |
867 | if (fmt[SIZELENMOD] == 'A') { | |
868 | int i; | |
869 | for (i = 0; i < n; i++) | |
870 | buff[i] = toupper(uchar(buff[i])); | |
871 | } | |
872 | else if (fmt[SIZELENMOD] != 'a') | |
873 | luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented"); | |
874 | return n; | |
875 | } | |
876 | ||
877 | #endif /* } */ | |
878 | ||
879 | ||
880 | /* | |
881 | ** Maximum size of each formatted item. This maximum size is produced | |
882 | ** by format('%.99f', minfloat), and is equal to 99 + 2 ('-' and '.') + | |
883 | ** number of decimal digits to represent minfloat. | |
884 | */ | |
885 | #define MAX_ITEM (120 + l_mathlim(MAX_10_EXP)) | |
886 | ||
887 | ||
888 | /* valid flags in a format specification */ | |
889 | #define FLAGS "-+ #0" | |
890 | ||
891 | /* | |
892 | ** maximum size of each format specification (such as "%-099.99d") | |
893 | */ | |
894 | #define MAX_FORMAT 32 | |
895 | ||
896 | ||
897 | static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { | |
898 | size_t l; | |
899 | const char *s = luaL_checklstring(L, arg, &l); | |
900 | luaL_addchar(b, '"'); | |
901 | while (l--) { | |
902 | if (*s == '"' || *s == '\\' || *s == '\n') { | |
903 | luaL_addchar(b, '\\'); | |
904 | luaL_addchar(b, *s); | |
905 | } | |
906 | else if (*s == '\0' || iscntrl(uchar(*s))) { | |
907 | char buff[10]; | |
908 | if (!isdigit(uchar(*(s+1)))) | |
909 | sprintf(buff, "\\%d", (int)uchar(*s)); | |
910 | else | |
911 | sprintf(buff, "\\%03d", (int)uchar(*s)); | |
912 | luaL_addstring(b, buff); | |
913 | } | |
914 | else | |
915 | luaL_addchar(b, *s); | |
916 | s++; | |
917 | } | |
918 | luaL_addchar(b, '"'); | |
919 | } | |
920 | ||
921 | static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { | |
922 | const char *p = strfrmt; | |
923 | while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ | |
924 | if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) | |
925 | luaL_error(L, "invalid format (repeated flags)"); | |
926 | if (isdigit(uchar(*p))) p++; /* skip width */ | |
927 | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ | |
928 | if (*p == '.') { | |
929 | p++; | |
930 | if (isdigit(uchar(*p))) p++; /* skip precision */ | |
931 | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ | |
932 | } | |
933 | if (isdigit(uchar(*p))) | |
934 | luaL_error(L, "invalid format (width or precision too long)"); | |
935 | *(form++) = '%'; | |
936 | memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char)); | |
937 | form += (p - strfrmt) + 1; | |
938 | *form = '\0'; | |
939 | return p; | |
940 | } | |
941 | ||
942 | ||
943 | /* | |
944 | ** add length modifier into formats | |
945 | */ | |
946 | static void addlenmod (char *form, const char *lenmod) { | |
947 | size_t l = strlen(form); | |
948 | size_t lm = strlen(lenmod); | |
949 | char spec = form[l - 1]; | |
950 | strcpy(form + l - 1, lenmod); | |
951 | form[l + lm - 1] = spec; | |
952 | form[l + lm] = '\0'; | |
953 | } | |
954 | ||
955 | ||
956 | static int str_format (lua_State *L) { | |
957 | int top = lua_gettop(L); | |
958 | int arg = 1; | |
959 | size_t sfl; | |
960 | const char *strfrmt = luaL_checklstring(L, arg, &sfl); | |
961 | const char *strfrmt_end = strfrmt+sfl; | |
962 | luaL_Buffer b; | |
963 | luaL_buffinit(L, &b); | |
964 | while (strfrmt < strfrmt_end) { | |
965 | if (*strfrmt != L_ESC) | |
966 | luaL_addchar(&b, *strfrmt++); | |
967 | else if (*++strfrmt == L_ESC) | |
968 | luaL_addchar(&b, *strfrmt++); /* %% */ | |
969 | else { /* format item */ | |
970 | char form[MAX_FORMAT]; /* to store the format ('%...') */ | |
971 | char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ | |
972 | int nb = 0; /* number of bytes in added item */ | |
973 | if (++arg > top) | |
974 | luaL_argerror(L, arg, "no value"); | |
975 | strfrmt = scanformat(L, strfrmt, form); | |
976 | switch (*strfrmt++) { | |
977 | case 'c': { | |
978 | nb = sprintf(buff, form, (int)luaL_checkinteger(L, arg)); | |
979 | break; | |
980 | } | |
981 | case 'd': case 'i': | |
982 | case 'o': case 'u': case 'x': case 'X': { | |
983 | lua_Integer n = luaL_checkinteger(L, arg); | |
984 | addlenmod(form, LUA_INTEGER_FRMLEN); | |
985 | nb = sprintf(buff, form, n); | |
986 | break; | |
987 | } | |
988 | case 'a': case 'A': | |
989 | addlenmod(form, LUA_NUMBER_FRMLEN); | |
990 | nb = lua_number2strx(L, buff, form, luaL_checknumber(L, arg)); | |
991 | break; | |
992 | case 'e': case 'E': case 'f': | |
993 | case 'g': case 'G': { | |
994 | addlenmod(form, LUA_NUMBER_FRMLEN); | |
995 | nb = sprintf(buff, form, luaL_checknumber(L, arg)); | |
996 | break; | |
997 | } | |
998 | case 'q': { | |
999 | addquoted(L, &b, arg); | |
1000 | break; | |
1001 | } | |
1002 | case 's': { | |
1003 | size_t l; | |
1004 | const char *s = luaL_tolstring(L, arg, &l); | |
1005 | if (!strchr(form, '.') && l >= 100) { | |
1006 | /* no precision and string is too long to be formatted; | |
1007 | keep original string */ | |
1008 | luaL_addvalue(&b); | |
1009 | } | |
1010 | else { | |
1011 | nb = sprintf(buff, form, s); | |
1012 | lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ | |
1013 | } | |
1014 | break; | |
1015 | } | |
1016 | default: { /* also treat cases 'pnLlh' */ | |
1017 | return luaL_error(L, "invalid option '%%%c' to 'format'", | |
1018 | *(strfrmt - 1)); | |
1019 | } | |
1020 | } | |
1021 | luaL_addsize(&b, nb); | |
1022 | } | |
1023 | } | |
1024 | luaL_pushresult(&b); | |
1025 | return 1; | |
1026 | } | |
1027 | ||
1028 | /* }====================================================== */ | |
1029 | ||
1030 | ||
1031 | /* | |
1032 | ** {====================================================== | |
1033 | ** PACK/UNPACK | |
1034 | ** ======================================================= | |
1035 | */ | |
1036 | ||
1037 | ||
1038 | /* value used for padding */ | |
1039 | #if !defined(LUA_PACKPADBYTE) | |
1040 | #define LUA_PACKPADBYTE 0x00 | |
1041 | #endif | |
1042 | ||
1043 | /* maximum size for the binary representation of an integer */ | |
1044 | #define MAXINTSIZE 16 | |
1045 | ||
1046 | /* number of bits in a character */ | |
1047 | #define NB CHAR_BIT | |
1048 | ||
1049 | /* mask for one character (NB 1's) */ | |
1050 | #define MC ((1 << NB) - 1) | |
1051 | ||
1052 | /* size of a lua_Integer */ | |
1053 | #define SZINT ((int)sizeof(lua_Integer)) | |
1054 | ||
1055 | ||
1056 | /* dummy union to get native endianness */ | |
1057 | static const union { | |
1058 | int dummy; | |
1059 | char little; /* true iff machine is little endian */ | |
1060 | } nativeendian = {1}; | |
1061 | ||
1062 | ||
1063 | /* dummy structure to get native alignment requirements */ | |
1064 | struct cD { | |
1065 | char c; | |
1066 | union { double d; void *p; lua_Integer i; lua_Number n; } u; | |
1067 | }; | |
1068 | ||
1069 | #define MAXALIGN (offsetof(struct cD, u)) | |
1070 | ||
1071 | ||
1072 | /* | |
1073 | ** Union for serializing floats | |
1074 | */ | |
1075 | typedef union Ftypes { | |
1076 | float f; | |
1077 | double d; | |
1078 | lua_Number n; | |
1079 | char buff[5 * sizeof(lua_Number)]; /* enough for any float type */ | |
1080 | } Ftypes; | |
1081 | ||
1082 | ||
1083 | /* | |
1084 | ** information to pack/unpack stuff | |
1085 | */ | |
1086 | typedef struct Header { | |
1087 | lua_State *L; | |
1088 | int islittle; | |
1089 | int maxalign; | |
1090 | } Header; | |
1091 | ||
1092 | ||
1093 | /* | |
1094 | ** options for pack/unpack | |
1095 | */ | |
1096 | typedef enum KOption { | |
1097 | Kint, /* signed integers */ | |
1098 | Kuint, /* unsigned integers */ | |
1099 | Kfloat, /* floating-point numbers */ | |
1100 | Kchar, /* fixed-length strings */ | |
1101 | Kstring, /* strings with prefixed length */ | |
1102 | Kzstr, /* zero-terminated strings */ | |
1103 | Kpadding, /* padding */ | |
1104 | Kpaddalign, /* padding for alignment */ | |
1105 | Knop /* no-op (configuration or spaces) */ | |
1106 | } KOption; | |
1107 | ||
1108 | ||
1109 | /* | |
1110 | ** Read an integer numeral from string 'fmt' or return 'df' if | |
1111 | ** there is no numeral | |
1112 | */ | |
1113 | static int digit (int c) { return '0' <= c && c <= '9'; } | |
1114 | ||
1115 | static int getnum (const char **fmt, int df) { | |
1116 | if (!digit(**fmt)) /* no number? */ | |
1117 | return df; /* return default value */ | |
1118 | else { | |
1119 | int a = 0; | |
1120 | do { | |
1121 | a = a*10 + (*((*fmt)++) - '0'); | |
1122 | } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); | |
1123 | return a; | |
1124 | } | |
1125 | } | |
1126 | ||
1127 | ||
1128 | /* | |
1129 | ** Read an integer numeral and raises an error if it is larger | |
1130 | ** than the maximum size for integers. | |
1131 | */ | |
1132 | static int getnumlimit (Header *h, const char **fmt, int df) { | |
1133 | int sz = getnum(fmt, df); | |
1134 | if (sz > MAXINTSIZE || sz <= 0) | |
1135 | luaL_error(h->L, "integral size (%d) out of limits [1,%d]", | |
1136 | sz, MAXINTSIZE); | |
1137 | return sz; | |
1138 | } | |
1139 | ||
1140 | ||
1141 | /* | |
1142 | ** Initialize Header | |
1143 | */ | |
1144 | static void initheader (lua_State *L, Header *h) { | |
1145 | h->L = L; | |
1146 | h->islittle = nativeendian.little; | |
1147 | h->maxalign = 1; | |
1148 | } | |
1149 | ||
1150 | ||
1151 | /* | |
1152 | ** Read and classify next option. 'size' is filled with option's size. | |
1153 | */ | |
1154 | static KOption getoption (Header *h, const char **fmt, int *size) { | |
1155 | int opt = *((*fmt)++); | |
1156 | *size = 0; /* default */ | |
1157 | switch (opt) { | |
1158 | case 'b': *size = sizeof(char); return Kint; | |
1159 | case 'B': *size = sizeof(char); return Kuint; | |
1160 | case 'h': *size = sizeof(short); return Kint; | |
1161 | case 'H': *size = sizeof(short); return Kuint; | |
1162 | case 'l': *size = sizeof(long); return Kint; | |
1163 | case 'L': *size = sizeof(long); return Kuint; | |
1164 | case 'j': *size = sizeof(lua_Integer); return Kint; | |
1165 | case 'J': *size = sizeof(lua_Integer); return Kuint; | |
1166 | case 'T': *size = sizeof(size_t); return Kuint; | |
1167 | case 'f': *size = sizeof(float); return Kfloat; | |
1168 | case 'd': *size = sizeof(double); return Kfloat; | |
1169 | case 'n': *size = sizeof(lua_Number); return Kfloat; | |
1170 | case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; | |
1171 | case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; | |
1172 | case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; | |
1173 | case 'c': | |
1174 | *size = getnum(fmt, -1); | |
1175 | if (*size == -1) | |
1176 | luaL_error(h->L, "missing size for format option 'c'"); | |
1177 | return Kchar; | |
1178 | case 'z': return Kzstr; | |
1179 | case 'x': *size = 1; return Kpadding; | |
1180 | case 'X': return Kpaddalign; | |
1181 | case ' ': break; | |
1182 | case '<': h->islittle = 1; break; | |
1183 | case '>': h->islittle = 0; break; | |
1184 | case '=': h->islittle = nativeendian.little; break; | |
1185 | case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; | |
1186 | default: luaL_error(h->L, "invalid format option '%c'", opt); | |
1187 | } | |
1188 | return Knop; | |
1189 | } | |
1190 | ||
1191 | ||
1192 | /* | |
1193 | ** Read, classify, and fill other details about the next option. | |
1194 | ** 'psize' is filled with option's size, 'notoalign' with its | |
1195 | ** alignment requirements. | |
1196 | ** Local variable 'size' gets the size to be aligned. (Kpadal option | |
1197 | ** always gets its full alignment, other options are limited by | |
1198 | ** the maximum alignment ('maxalign'). Kchar option needs no alignment | |
1199 | ** despite its size. | |
1200 | */ | |
1201 | static KOption getdetails (Header *h, size_t totalsize, | |
1202 | const char **fmt, int *psize, int *ntoalign) { | |
1203 | KOption opt = getoption(h, fmt, psize); | |
1204 | int align = *psize; /* usually, alignment follows size */ | |
1205 | if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ | |
1206 | if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) | |
1207 | luaL_argerror(h->L, 1, "invalid next option for option 'X'"); | |
1208 | } | |
1209 | if (align <= 1 || opt == Kchar) /* need no alignment? */ | |
1210 | *ntoalign = 0; | |
1211 | else { | |
1212 | if (align > h->maxalign) /* enforce maximum alignment */ | |
1213 | align = h->maxalign; | |
1214 | if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */ | |
1215 | luaL_argerror(h->L, 1, "format asks for alignment not power of 2"); | |
1216 | *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1); | |
1217 | } | |
1218 | return opt; | |
1219 | } | |
1220 | ||
1221 | ||
1222 | /* | |
1223 | ** Pack integer 'n' with 'size' bytes and 'islittle' endianness. | |
1224 | ** The final 'if' handles the case when 'size' is larger than | |
1225 | ** the size of a Lua integer, correcting the extra sign-extension | |
1226 | ** bytes if necessary (by default they would be zeros). | |
1227 | */ | |
1228 | static void packint (luaL_Buffer *b, lua_Unsigned n, | |
1229 | int islittle, int size, int neg) { | |
1230 | char *buff = luaL_prepbuffsize(b, size); | |
1231 | int i; | |
1232 | buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ | |
1233 | for (i = 1; i < size; i++) { | |
1234 | n >>= NB; | |
1235 | buff[islittle ? i : size - 1 - i] = (char)(n & MC); | |
1236 | } | |
1237 | if (neg && size > SZINT) { /* negative number need sign extension? */ | |
1238 | for (i = SZINT; i < size; i++) /* correct extra bytes */ | |
1239 | buff[islittle ? i : size - 1 - i] = (char)MC; | |
1240 | } | |
1241 | luaL_addsize(b, size); /* add result to buffer */ | |
1242 | } | |
1243 | ||
1244 | ||
1245 | /* | |
1246 | ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if | |
1247 | ** given 'islittle' is different from native endianness. | |
1248 | */ | |
1249 | static void copywithendian (volatile char *dest, volatile const char *src, | |
1250 | int size, int islittle) { | |
1251 | if (islittle == nativeendian.little) { | |
1252 | while (size-- != 0) | |
1253 | *(dest++) = *(src++); | |
1254 | } | |
1255 | else { | |
1256 | dest += size - 1; | |
1257 | while (size-- != 0) | |
1258 | *(dest--) = *(src++); | |
1259 | } | |
1260 | } | |
1261 | ||
1262 | ||
1263 | static int str_pack (lua_State *L) { | |
1264 | luaL_Buffer b; | |
1265 | Header h; | |
1266 | const char *fmt = luaL_checkstring(L, 1); /* format string */ | |
1267 | int arg = 1; /* current argument to pack */ | |
1268 | size_t totalsize = 0; /* accumulate total size of result */ | |
1269 | initheader(L, &h); | |
1270 | lua_pushnil(L); /* mark to separate arguments from string buffer */ | |
1271 | luaL_buffinit(L, &b); | |
1272 | while (*fmt != '\0') { | |
1273 | int size, ntoalign; | |
1274 | KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); | |
1275 | totalsize += ntoalign + size; | |
1276 | while (ntoalign-- > 0) | |
1277 | luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */ | |
1278 | arg++; | |
1279 | switch (opt) { | |
1280 | case Kint: { /* signed integers */ | |
1281 | lua_Integer n = luaL_checkinteger(L, arg); | |
1282 | if (size < SZINT) { /* need overflow check? */ | |
1283 | lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); | |
1284 | luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); | |
1285 | } | |
1286 | packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); | |
1287 | break; | |
1288 | } | |
1289 | case Kuint: { /* unsigned integers */ | |
1290 | lua_Integer n = luaL_checkinteger(L, arg); | |
1291 | if (size < SZINT) /* need overflow check? */ | |
1292 | luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)), | |
1293 | arg, "unsigned overflow"); | |
1294 | packint(&b, (lua_Unsigned)n, h.islittle, size, 0); | |
1295 | break; | |
1296 | } | |
1297 | case Kfloat: { /* floating-point options */ | |
1298 | volatile Ftypes u; | |
1299 | char *buff = luaL_prepbuffsize(&b, size); | |
1300 | lua_Number n = luaL_checknumber(L, arg); /* get argument */ | |
1301 | if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */ | |
1302 | else if (size == sizeof(u.d)) u.d = (double)n; | |
1303 | else u.n = n; | |
1304 | /* move 'u' to final result, correcting endianness if needed */ | |
1305 | copywithendian(buff, u.buff, size, h.islittle); | |
1306 | luaL_addsize(&b, size); | |
1307 | break; | |
1308 | } | |
1309 | case Kchar: { /* fixed-size string */ | |
1310 | size_t len; | |
1311 | const char *s = luaL_checklstring(L, arg, &len); | |
1312 | luaL_argcheck(L, len == (size_t)size, arg, "wrong length"); | |
1313 | luaL_addlstring(&b, s, size); | |
1314 | break; | |
1315 | } | |
1316 | case Kstring: { /* strings with length count */ | |
1317 | size_t len; | |
1318 | const char *s = luaL_checklstring(L, arg, &len); | |
1319 | luaL_argcheck(L, size >= (int)sizeof(size_t) || | |
1320 | len < ((size_t)1 << (size * NB)), | |
1321 | arg, "string length does not fit in given size"); | |
1322 | packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */ | |
1323 | luaL_addlstring(&b, s, len); | |
1324 | totalsize += len; | |
1325 | break; | |
1326 | } | |
1327 | case Kzstr: { /* zero-terminated string */ | |
1328 | size_t len; | |
1329 | const char *s = luaL_checklstring(L, arg, &len); | |
1330 | luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros"); | |
1331 | luaL_addlstring(&b, s, len); | |
1332 | luaL_addchar(&b, '\0'); /* add zero at the end */ | |
1333 | totalsize += len + 1; | |
1334 | break; | |
1335 | } | |
1336 | case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE); /* FALLTHROUGH */ | |
1337 | case Kpaddalign: case Knop: | |
1338 | arg--; /* undo increment */ | |
1339 | break; | |
1340 | } | |
1341 | } | |
1342 | luaL_pushresult(&b); | |
1343 | return 1; | |
1344 | } | |
1345 | ||
1346 | ||
1347 | static int str_packsize (lua_State *L) { | |
1348 | Header h; | |
1349 | const char *fmt = luaL_checkstring(L, 1); /* format string */ | |
1350 | size_t totalsize = 0; /* accumulate total size of result */ | |
1351 | initheader(L, &h); | |
1352 | while (*fmt != '\0') { | |
1353 | int size, ntoalign; | |
1354 | KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); | |
1355 | size += ntoalign; /* total space used by option */ | |
1356 | luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, | |
1357 | "format result too large"); | |
1358 | totalsize += size; | |
1359 | switch (opt) { | |
1360 | case Kstring: /* strings with length count */ | |
1361 | case Kzstr: /* zero-terminated string */ | |
1362 | luaL_argerror(L, 1, "variable-length format"); | |
1363 | break; | |
1364 | default: break; | |
1365 | } | |
1366 | } | |
1367 | lua_pushinteger(L, (lua_Integer)totalsize); | |
1368 | return 1; | |
1369 | } | |
1370 | ||
1371 | ||
1372 | /* | |
1373 | ** Unpack an integer with 'size' bytes and 'islittle' endianness. | |
1374 | ** If size is smaller than the size of a Lua integer and integer | |
1375 | ** is signed, must do sign extension (propagating the sign to the | |
1376 | ** higher bits); if size is larger than the size of a Lua integer, | |
1377 | ** it must check the unread bytes to see whether they do not cause an | |
1378 | ** overflow. | |
1379 | */ | |
1380 | static lua_Integer unpackint (lua_State *L, const char *str, | |
1381 | int islittle, int size, int issigned) { | |
1382 | lua_Unsigned res = 0; | |
1383 | int i; | |
1384 | int limit = (size <= SZINT) ? size : SZINT; | |
1385 | for (i = limit - 1; i >= 0; i--) { | |
1386 | res <<= NB; | |
1387 | res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i]; | |
1388 | } | |
1389 | if (size < SZINT) { /* real size smaller than lua_Integer? */ | |
1390 | if (issigned) { /* needs sign extension? */ | |
1391 | lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1); | |
1392 | res = ((res ^ mask) - mask); /* do sign extension */ | |
1393 | } | |
1394 | } | |
1395 | else if (size > SZINT) { /* must check unread bytes */ | |
1396 | int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; | |
1397 | for (i = limit; i < size; i++) { | |
1398 | if ((unsigned char)str[islittle ? i : size - 1 - i] != mask) | |
1399 | luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); | |
1400 | } | |
1401 | } | |
1402 | return (lua_Integer)res; | |
1403 | } | |
1404 | ||
1405 | ||
1406 | static int str_unpack (lua_State *L) { | |
1407 | Header h; | |
1408 | const char *fmt = luaL_checkstring(L, 1); | |
1409 | size_t ld; | |
1410 | const char *data = luaL_checklstring(L, 2, &ld); | |
1411 | size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1; | |
1412 | int n = 0; /* number of results */ | |
1413 | luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); | |
1414 | initheader(L, &h); | |
1415 | while (*fmt != '\0') { | |
1416 | int size, ntoalign; | |
1417 | KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); | |
1418 | if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld) | |
1419 | luaL_argerror(L, 2, "data string too short"); | |
1420 | pos += ntoalign; /* skip alignment */ | |
1421 | /* stack space for item + next position */ | |
1422 | luaL_checkstack(L, 2, "too many results"); | |
1423 | n++; | |
1424 | switch (opt) { | |
1425 | case Kint: | |
1426 | case Kuint: { | |
1427 | lua_Integer res = unpackint(L, data + pos, h.islittle, size, | |
1428 | (opt == Kint)); | |
1429 | lua_pushinteger(L, res); | |
1430 | break; | |
1431 | } | |
1432 | case Kfloat: { | |
1433 | volatile Ftypes u; | |
1434 | lua_Number num; | |
1435 | copywithendian(u.buff, data + pos, size, h.islittle); | |
1436 | if (size == sizeof(u.f)) num = (lua_Number)u.f; | |
1437 | else if (size == sizeof(u.d)) num = (lua_Number)u.d; | |
1438 | else num = u.n; | |
1439 | lua_pushnumber(L, num); | |
1440 | break; | |
1441 | } | |
1442 | case Kchar: { | |
1443 | lua_pushlstring(L, data + pos, size); | |
1444 | break; | |
1445 | } | |
1446 | case Kstring: { | |
1447 | size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); | |
1448 | luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); | |
1449 | lua_pushlstring(L, data + pos + size, len); | |
1450 | pos += len; /* skip string */ | |
1451 | break; | |
1452 | } | |
1453 | case Kzstr: { | |
1454 | size_t len = (int)strlen(data + pos); | |
1455 | lua_pushlstring(L, data + pos, len); | |
1456 | pos += len + 1; /* skip string plus final '\0' */ | |
1457 | break; | |
1458 | } | |
1459 | case Kpaddalign: case Kpadding: case Knop: | |
1460 | n--; /* undo increment */ | |
1461 | break; | |
1462 | } | |
1463 | pos += size; | |
1464 | } | |
1465 | lua_pushinteger(L, pos + 1); /* next position */ | |
1466 | return n + 1; | |
1467 | } | |
1468 | ||
1469 | /* }====================================================== */ | |
1470 | ||
1471 | ||
1472 | static const luaL_Reg strlib[] = { | |
1473 | {"byte", str_byte}, | |
1474 | {"char", str_char}, | |
1475 | {"dump", str_dump}, | |
1476 | {"find", str_find}, | |
1477 | {"format", str_format}, | |
1478 | {"gmatch", gmatch}, | |
1479 | {"gsub", str_gsub}, | |
1480 | {"len", str_len}, | |
1481 | {"lower", str_lower}, | |
1482 | {"match", str_match}, | |
1483 | {"rep", str_rep}, | |
1484 | {"reverse", str_reverse}, | |
1485 | {"sub", str_sub}, | |
1486 | {"upper", str_upper}, | |
1487 | {"pack", str_pack}, | |
1488 | {"packsize", str_packsize}, | |
1489 | {"unpack", str_unpack}, | |
1490 | {NULL, NULL} | |
1491 | }; | |
1492 | ||
1493 | ||
1494 | static void createmetatable (lua_State *L) { | |
1495 | lua_createtable(L, 0, 1); /* table to be metatable for strings */ | |
1496 | lua_pushliteral(L, ""); /* dummy string */ | |
1497 | lua_pushvalue(L, -2); /* copy table */ | |
1498 | lua_setmetatable(L, -2); /* set table as metatable for strings */ | |
1499 | lua_pop(L, 1); /* pop dummy string */ | |
1500 | lua_pushvalue(L, -2); /* get string library */ | |
1501 | lua_setfield(L, -2, "__index"); /* metatable.__index = string */ | |
1502 | lua_pop(L, 1); /* pop metatable */ | |
1503 | } | |
1504 | ||
1505 | ||
1506 | /* | |
1507 | ** Open string library | |
1508 | */ | |
1509 | LUAMOD_API int luaopen_string (lua_State *L) { | |
1510 | luaL_newlib(L, strlib); | |
1511 | createmetatable(L); | |
1512 | return 1; | |
1513 | } | |
1514 |