interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / lstrlib.c

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