renamed 'hf mfdes readdata, writedata' to 'read/write'
[RRG-proxmark3.git] / client / deps / liblua / lstrlib.c
blob57b4ebc4bd9b19557d73b7a661442b201041d1f3
1 /*
2 ** $Id: lstrlib.c,v 1.178 2012/08/14 18:12:34 roberto Exp $
3 ** Standard library for string operations and pattern-matching
4 ** See Copyright Notice in lua.h
5 */
8 #include <ctype.h>
9 #include <stddef.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #define lstrlib_c
15 #define LUA_LIB
17 #include "lua.h"
19 #include "lauxlib.h"
20 #include "lualib.h"
24 ** maximum number of captures that a pattern can do during
25 ** pattern-matching. This limit is arbitrary.
27 #if !defined(LUA_MAXCAPTURES)
28 #define LUA_MAXCAPTURES 32
29 #endif
32 /* macro to `unsign' a character */
33 #define uchar(c) ((unsigned char)(c))
37 static int str_len(lua_State *L) {
38 size_t l;
39 luaL_checklstring(L, 1, &l);
40 lua_pushinteger(L, (lua_Integer)l);
41 return 1;
45 /* translate a relative string position: negative means back from end */
46 static size_t posrelat(ptrdiff_t pos, size_t len) {
47 if (pos >= 0) return (size_t)pos;
48 else if (0u - (size_t)pos > len) return 0;
49 else return len - ((size_t) - pos) + 1;
53 static int str_sub(lua_State *L) {
54 size_t l;
55 const char *s = luaL_checklstring(L, 1, &l);
56 size_t start = posrelat(luaL_checkinteger(L, 2), l);
57 size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
58 if (start < 1) start = 1;
59 if (end > l) end = l;
60 if (start <= end)
61 lua_pushlstring(L, s + start - 1, end - start + 1);
62 else lua_pushliteral(L, "");
63 return 1;
67 static int str_reverse(lua_State *L) {
68 size_t l, i;
69 luaL_Buffer b;
70 const char *s = luaL_checklstring(L, 1, &l);
71 char *p = luaL_buffinitsize(L, &b, l);
72 for (i = 0; i < l; i++)
73 p[i] = s[l - i - 1];
74 luaL_pushresultsize(&b, l);
75 return 1;
79 static int str_lower(lua_State *L) {
80 size_t l;
81 size_t 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] = tolower(uchar(s[i]));
87 luaL_pushresultsize(&b, l);
88 return 1;
92 static int str_upper(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] = toupper(uchar(s[i]));
100 luaL_pushresultsize(&b, l);
101 return 1;
105 /* reasonable limit to avoid arithmetic overflow */
106 #define MAXSIZE ((~(size_t)0) >> 1)
108 static int str_rep(lua_State *L) {
109 size_t l, lsep;
110 const char *s = luaL_checklstring(L, 1, &l);
111 int n = luaL_checkint(L, 2);
112 const char *sep = luaL_optlstring(L, 3, "", &lsep);
113 if (n <= 0) lua_pushliteral(L, "");
114 else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
115 return luaL_error(L, "resulting string too large");
116 else {
117 size_t totallen = n * l + (n - 1) * lsep;
118 luaL_Buffer b;
119 char *p = luaL_buffinitsize(L, &b, totallen);
120 while (n-- > 1) { /* first n-1 copies (followed by separator) */
121 memcpy(p, s, l * sizeof(char));
122 p += l;
123 if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
124 memcpy(p, sep, lsep * sizeof(char));
125 p += lsep;
128 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
129 luaL_pushresultsize(&b, totallen);
131 return 1;
135 static int str_byte(lua_State *L) {
136 size_t l;
137 const char *s = luaL_checklstring(L, 1, &l);
138 size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
139 size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
140 int n, i;
141 if (posi < 1) posi = 1;
142 if (pose > l) pose = l;
143 if (posi > pose) return 0; /* empty interval; return no values */
144 n = (int)(pose - posi + 1);
145 if (posi + n <= pose) /* (size_t -> int) overflow? */
146 return luaL_error(L, "string slice too long");
147 luaL_checkstack(L, n, "string slice too long");
148 for (i = 0; i < n; i++)
149 lua_pushinteger(L, uchar(s[posi + i - 1]));
150 return n;
154 static int str_char(lua_State *L) {
155 int n = lua_gettop(L); /* number of arguments */
156 int i;
157 luaL_Buffer b;
158 char *p = luaL_buffinitsize(L, &b, n);
159 for (i = 1; i <= n; i++) {
160 int c = luaL_checkint(L, i);
161 luaL_argcheck(L, uchar(c) == c, i, "value out of range");
162 p[i - 1] = uchar(c);
164 luaL_pushresultsize(&b, n);
165 return 1;
169 static int writer(lua_State *L, const void *b, size_t size, void *B) {
170 (void)L;
171 luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
172 return 0;
176 static int str_dump(lua_State *L) {
177 luaL_Buffer b;
178 luaL_checktype(L, 1, LUA_TFUNCTION);
179 lua_settop(L, 1);
180 luaL_buffinit(L, &b);
181 if (lua_dump(L, writer, &b) != 0)
182 return luaL_error(L, "unable to dump given function");
183 luaL_pushresult(&b);
184 return 1;
190 ** {======================================================
191 ** PATTERN MATCHING
192 ** =======================================================
196 #define CAP_UNFINISHED (-1)
197 #define CAP_POSITION (-2)
200 typedef struct MatchState {
201 int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
202 const char *src_init; /* init of source string */
203 const char *src_end; /* end ('\0') of source string */
204 const char *p_end; /* end ('\0') of pattern */
205 lua_State *L;
206 int level; /* total number of captures (finished or unfinished) */
207 struct {
208 const char *init;
209 ptrdiff_t len;
210 } capture[LUA_MAXCAPTURES];
211 } MatchState;
214 /* recursive function */
215 static const char *match(MatchState *ms, const char *s, const char *p);
218 /* maximum recursion depth for 'match' */
219 #if !defined(MAXCCALLS)
220 #define MAXCCALLS 200
221 #endif
224 #define L_ESC '%'
225 #define SPECIALS "^$*+?.([%-"
228 static int check_capture(MatchState *ms, int l) {
229 l -= '1';
230 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
231 return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
232 return l;
236 static int capture_to_close(MatchState *ms) {
237 int level = ms->level;
238 for (level--; level >= 0; level--)
239 if (ms->capture[level].len == CAP_UNFINISHED) return level;
240 return luaL_error(ms->L, "invalid pattern capture");
244 static const char *classend(MatchState *ms, const char *p) {
245 switch (*p++) {
246 case L_ESC: {
247 if (p == ms->p_end)
248 luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
249 return p + 1;
251 case '[': {
252 if (*p == '^') p++;
253 do { /* look for a `]' */
254 if (p == ms->p_end)
255 luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
256 if (*(p++) == L_ESC && p < ms->p_end)
257 p++; /* skip escapes (e.g. `%]') */
258 } while (*p != ']');
259 return p + 1;
261 default: {
262 return p;
268 static int match_class(int c, int cl) {
269 int res;
270 switch (tolower(cl)) {
271 case 'a' :
272 res = isalpha(c);
273 break;
274 case 'c' :
275 res = iscntrl(c);
276 break;
277 case 'd' :
278 res = isdigit(c);
279 break;
280 case 'g' :
281 res = isgraph(c);
282 break;
283 case 'l' :
284 res = islower(c);
285 break;
286 case 'p' :
287 res = ispunct(c);
288 break;
289 case 's' :
290 res = isspace(c);
291 break;
292 case 'u' :
293 res = isupper(c);
294 break;
295 case 'w' :
296 res = isalnum(c);
297 break;
298 case 'x' :
299 res = isxdigit(c);
300 break;
301 case 'z' :
302 res = (c == 0);
303 break; /* deprecated option */
304 default:
305 return (cl == c);
307 return (islower(cl) ? res : !res);
311 static int matchbracketclass(int c, const char *p, const char *ec) {
312 int sig = 1;
313 if (*(p + 1) == '^') {
314 sig = 0;
315 p++; /* skip the `^' */
317 while (++p < ec) {
318 if (*p == L_ESC) {
319 p++;
320 if (match_class(c, uchar(*p)))
321 return sig;
322 } else if ((*(p + 1) == '-') && (p + 2 < ec)) {
323 p += 2;
324 if (uchar(*(p - 2)) <= c && c <= uchar(*p))
325 return sig;
326 } else if (uchar(*p) == c) return sig;
328 return !sig;
332 static int singlematch(MatchState *ms, const char *s, const char *p,
333 const char *ep) {
334 if (s >= ms->src_end)
335 return 0;
336 else {
337 int c = uchar(*s);
338 switch (*p) {
339 case '.':
340 return 1; /* matches any char */
341 case L_ESC:
342 return match_class(c, uchar(*(p + 1)));
343 case '[':
344 return matchbracketclass(c, p, ep - 1);
345 default:
346 return (uchar(*p) == c);
352 static const char *matchbalance(MatchState *ms, const char *s,
353 const char *p) {
354 if (p >= ms->p_end - 1)
355 luaL_error(ms->L, "malformed pattern "
356 "(missing arguments to " LUA_QL("%%b") ")");
357 if (*s != *p) return NULL;
358 else {
359 int b = *p;
360 int e = *(p + 1);
361 int cont = 1;
362 while (++s < ms->src_end) {
363 if (*s == e) {
364 if (--cont == 0) return s + 1;
365 } else if (*s == b) cont++;
368 return NULL; /* string ends out of balance */
372 static const char *max_expand(MatchState *ms, const char *s,
373 const char *p, const char *ep) {
374 ptrdiff_t i = 0; /* counts maximum expand for item */
375 while (singlematch(ms, s + i, p, ep))
376 i++;
377 /* keeps trying to match with the maximum repetitions */
378 while (i >= 0) {
379 const char *res = match(ms, (s + i), ep + 1);
380 if (res) return res;
381 i--; /* else didn't match; reduce 1 repetition to try again */
383 return NULL;
387 static const char *min_expand(MatchState *ms, const char *s,
388 const char *p, const char *ep) {
389 for (;;) {
390 const char *res = match(ms, s, ep + 1);
391 if (res != NULL)
392 return res;
393 else if (singlematch(ms, s, p, ep))
394 s++; /* try with one more repetition */
395 else return NULL;
400 static const char *start_capture(MatchState *ms, const char *s,
401 const char *p, int what) {
402 const char *res;
403 int level = ms->level;
404 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
405 ms->capture[level].init = s;
406 ms->capture[level].len = what;
407 ms->level = level + 1;
408 if ((res = match(ms, s, p)) == NULL) /* match failed? */
409 ms->level--; /* undo capture */
410 return res;
414 static const char *end_capture(MatchState *ms, const char *s,
415 const char *p) {
416 int l = capture_to_close(ms);
417 const char *res;
418 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
419 if ((res = match(ms, s, p)) == NULL) /* match failed? */
420 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
421 return res;
425 static const char *match_capture(MatchState *ms, const char *s, int l) {
426 size_t len;
427 l = check_capture(ms, l);
428 len = ms->capture[l].len;
429 if ((size_t)(ms->src_end - s) >= len &&
430 memcmp(ms->capture[l].init, s, len) == 0)
431 return s + len;
432 else return NULL;
436 static const char *match(MatchState *ms, const char *s, const char *p) {
437 if (ms->matchdepth-- == 0)
438 luaL_error(ms->L, "pattern too complex");
439 init: /* using goto's to optimize tail recursion */
440 if (p != ms->p_end) { /* end of pattern? */
441 switch (*p) {
442 case '(': { /* start capture */
443 if (*(p + 1) == ')') /* position capture? */
444 s = start_capture(ms, s, p + 2, CAP_POSITION);
445 else
446 s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
447 break;
449 case ')': { /* end capture */
450 s = end_capture(ms, s, p + 1);
451 break;
453 case '$': {
454 if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
455 goto dflt; /* no; go to default */
456 s = (s == ms->src_end) ? s : NULL; /* check end of string */
457 break;
459 case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
460 switch (*(p + 1)) {
461 case 'b': { /* balanced string? */
462 s = matchbalance(ms, s, p + 2);
463 if (s != NULL) {
464 p += 4;
465 goto init; /* return match(ms, s, p + 4); */
466 } /* else fail (s == NULL) */
467 break;
469 case 'f': { /* frontier? */
470 const char *ep;
471 char previous;
472 p += 2;
473 if (*p != '[')
474 luaL_error(ms->L, "missing " LUA_QL("[") " after "
475 LUA_QL("%%f") " in pattern");
476 ep = classend(ms, p); /* points to what is next */
477 previous = (s == ms->src_init) ? '\0' : *(s - 1);
478 if (!matchbracketclass(uchar(previous), p, ep - 1) &&
479 matchbracketclass(uchar(*s), p, ep - 1)) {
480 p = ep;
481 goto init; /* return match(ms, s, ep); */
483 s = NULL; /* match failed */
484 break;
486 case '0':
487 case '1':
488 case '2':
489 case '3':
490 case '4':
491 case '5':
492 case '6':
493 case '7':
494 case '8':
495 case '9': { /* capture results (%0-%9)? */
496 s = match_capture(ms, s, uchar(*(p + 1)));
497 if (s != NULL) {
498 p += 2;
499 goto init; /* return match(ms, s, p + 2) */
501 break;
503 default:
504 goto dflt;
506 break;
508 default:
509 dflt: { /* pattern class plus optional suffix */
510 const char *ep = classend(ms, p); /* points to optional suffix */
511 /* does not match at least once? */
512 if (!singlematch(ms, s, p, ep)) {
513 if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
514 p = ep + 1;
515 goto init; /* return match(ms, s, ep + 1); */
516 } else /* '+' or no suffix */
517 s = NULL; /* fail */
518 } else { /* matched once */
519 switch (*ep) { /* handle optional suffix */
520 case '?': { /* optional */
521 const char *res;
522 if ((res = match(ms, s + 1, ep + 1)) != NULL)
523 s = res;
524 else {
525 p = ep + 1;
526 goto init; /* else return match(ms, s, ep + 1); */
528 break;
530 case '+': /* 1 or more repetitions */
531 s++; /* 1 match already done */
532 /* go through */
533 case '*': /* 0 or more repetitions */
534 s = max_expand(ms, s, p, ep);
535 break;
536 case '-': /* 0 or more repetitions (minimum) */
537 s = min_expand(ms, s, p, ep);
538 break;
539 default: /* no suffix */
540 s++;
541 p = ep;
542 goto init; /* return match(ms, s + 1, ep); */
545 break;
549 ms->matchdepth++;
550 return s;
555 static const char *lmemfind(const char *s1, size_t l1,
556 const char *s2, size_t l2) {
557 if (l2 == 0) return s1; /* empty strings are everywhere */
558 else if (l2 > l1) return NULL; /* avoids a negative `l1' */
559 else {
560 const char *init; /* to search for a `*s2' inside `s1' */
561 l2--; /* 1st char will be checked by `memchr' */
562 l1 = l1 - l2; /* `s2' cannot be found after that */
563 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
564 init++; /* 1st char is already checked */
565 if (memcmp(init, s2 + 1, l2) == 0)
566 return init - 1;
567 else { /* correct `l1' and `s1' to try again */
568 l1 -= init - s1;
569 s1 = init;
572 return NULL; /* not found */
577 static void push_onecapture(MatchState *ms, int i, const char *s,
578 const char *e) {
579 if (i >= ms->level) {
580 if (i == 0) /* ms->level == 0, too */
581 lua_pushlstring(ms->L, s, e - s); /* add whole match */
582 else
583 luaL_error(ms->L, "invalid capture index");
584 } else {
585 ptrdiff_t l = ms->capture[i].len;
586 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
587 if (l == CAP_POSITION)
588 lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
589 else
590 lua_pushlstring(ms->L, ms->capture[i].init, l);
595 static int push_captures(MatchState *ms, const char *s, const char *e) {
596 int i;
597 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
598 luaL_checkstack(ms->L, nlevels, "too many captures");
599 for (i = 0; i < nlevels; i++)
600 push_onecapture(ms, i, s, e);
601 return nlevels; /* number of strings pushed */
605 /* check whether pattern has no special characters */
606 static int nospecials(const char *p, size_t l) {
607 size_t upto = 0;
608 do {
609 if (strpbrk(p + upto, SPECIALS))
610 return 0; /* pattern has a special character */
611 upto += strlen(p + upto) + 1; /* may have more after \0 */
612 } while (upto <= l);
613 return 1; /* no special chars found */
617 static int str_find_aux(lua_State *L, int find) {
618 size_t ls, lp;
619 const char *s = luaL_checklstring(L, 1, &ls);
620 const char *p = luaL_checklstring(L, 2, &lp);
621 size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
622 if (init < 1) init = 1;
623 else if (init > ls + 1) { /* start after string's end? */
624 lua_pushnil(L); /* cannot find anything */
625 return 1;
627 /* explicit request or no special characters? */
628 if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
629 /* do a plain search */
630 const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
631 if (s2) {
632 lua_pushinteger(L, s2 - s + 1);
633 lua_pushinteger(L, s2 - s + lp);
634 return 2;
636 } else {
637 MatchState ms;
638 const char *s1 = s + init - 1;
639 int anchor = (*p == '^');
640 if (anchor) {
641 p++;
642 lp--; /* skip anchor character */
644 ms.L = L;
645 ms.matchdepth = MAXCCALLS;
646 ms.src_init = s;
647 ms.src_end = s + ls;
648 ms.p_end = p + lp;
649 do {
650 const char *res;
651 ms.level = 0;
652 lua_assert(ms.matchdepth == MAXCCALLS);
653 if ((res = match(&ms, s1, p)) != NULL) {
654 if (find) {
655 lua_pushinteger(L, s1 - s + 1); /* start */
656 lua_pushinteger(L, res - s); /* end */
657 return push_captures(&ms, NULL, 0) + 2;
658 } else
659 return push_captures(&ms, s1, res);
661 } while (s1++ < ms.src_end && !anchor);
663 lua_pushnil(L); /* not found */
664 return 1;
668 static int str_find(lua_State *L) {
669 return str_find_aux(L, 1);
673 static int str_match(lua_State *L) {
674 return str_find_aux(L, 0);
678 static int gmatch_aux(lua_State *L) {
679 MatchState ms;
680 size_t ls, lp;
681 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
682 const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
683 const char *src;
684 ms.L = L;
685 ms.matchdepth = MAXCCALLS;
686 ms.src_init = s;
687 ms.src_end = s + ls;
688 ms.p_end = p + lp;
689 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
690 src <= ms.src_end;
691 src++) {
692 const char *e;
693 ms.level = 0;
694 lua_assert(ms.matchdepth == MAXCCALLS);
695 if ((e = match(&ms, src, p)) != NULL) {
696 lua_Integer newstart = e - s;
697 if (e == src) newstart++; /* empty match? go at least one position */
698 lua_pushinteger(L, newstart);
699 lua_replace(L, lua_upvalueindex(3));
700 return push_captures(&ms, src, e);
703 return 0; /* not found */
707 static int gmatch(lua_State *L) {
708 luaL_checkstring(L, 1);
709 luaL_checkstring(L, 2);
710 lua_settop(L, 2);
711 lua_pushinteger(L, 0);
712 lua_pushcclosure(L, gmatch_aux, 3);
713 return 1;
717 static void add_s(MatchState *ms, luaL_Buffer *b, const char *s,
718 const char *e) {
719 size_t l, i;
720 const char *news = lua_tolstring(ms->L, 3, &l);
721 for (i = 0; i < l; i++) {
722 if (news[i] != L_ESC)
723 luaL_addchar(b, news[i]);
724 else {
725 i++; /* skip ESC */
726 if (!isdigit(uchar(news[i]))) {
727 if (news[i] != L_ESC)
728 luaL_error(ms->L, "invalid use of " LUA_QL("%c")
729 " in replacement string", L_ESC);
730 luaL_addchar(b, news[i]);
731 } else if (news[i] == '0')
732 luaL_addlstring(b, s, e - s);
733 else {
734 push_onecapture(ms, news[i] - '1', s, e);
735 luaL_addvalue(b); /* add capture to accumulated result */
742 static void add_value(MatchState *ms, luaL_Buffer *b, const char *s,
743 const char *e, int tr) {
744 lua_State *L = ms->L;
745 switch (tr) {
746 case LUA_TFUNCTION: {
747 int n;
748 lua_pushvalue(L, 3);
749 n = push_captures(ms, s, e);
750 lua_call(L, n, 1);
751 break;
753 case LUA_TTABLE: {
754 push_onecapture(ms, 0, s, e);
755 lua_gettable(L, 3);
756 break;
758 default: { /* LUA_TNUMBER or LUA_TSTRING */
759 add_s(ms, b, s, e);
760 return;
763 if (!lua_toboolean(L, -1)) { /* nil or false? */
764 lua_pop(L, 1);
765 lua_pushlstring(L, s, e - s); /* keep original text */
766 } else if (!lua_isstring(L, -1))
767 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
768 luaL_addvalue(b); /* add result to accumulator */
772 static int str_gsub(lua_State *L) {
773 size_t srcl, lp;
774 const char *src = luaL_checklstring(L, 1, &srcl);
775 const char *p = luaL_checklstring(L, 2, &lp);
776 int tr = lua_type(L, 3);
777 size_t max_s = luaL_optinteger(L, 4, srcl + 1);
778 int anchor = (*p == '^');
779 size_t n = 0;
780 MatchState ms;
781 luaL_Buffer b;
782 luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
783 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
784 "string/function/table expected");
785 luaL_buffinit(L, &b);
786 if (anchor) {
787 p++;
788 lp--; /* skip anchor character */
790 ms.L = L;
791 ms.matchdepth = MAXCCALLS;
792 ms.src_init = src;
793 ms.src_end = src + srcl;
794 ms.p_end = p + lp;
795 while (n < max_s) {
796 const char *e;
797 ms.level = 0;
798 lua_assert(ms.matchdepth == MAXCCALLS);
799 e = match(&ms, src, p);
800 if (e) {
801 n++;
802 add_value(&ms, &b, src, e, tr);
804 if (e && e > src) /* non empty match? */
805 src = e; /* skip it */
806 else if (src < ms.src_end)
807 luaL_addchar(&b, *src++);
808 else break;
809 if (anchor) break;
811 luaL_addlstring(&b, src, ms.src_end - src);
812 luaL_pushresult(&b);
813 lua_pushinteger(L, n); /* number of substitutions */
814 return 2;
817 /* }====================================================== */
822 ** {======================================================
823 ** STRING FORMAT
824 ** =======================================================
828 ** LUA_INTFRMLEN is the length modifier for integer conversions in
829 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
830 ** the previous length
832 #if !defined(LUA_INTFRMLEN) /* { */
833 #if defined(LUA_USE_LONGLONG)
835 #define LUA_INTFRMLEN "ll"
836 #define LUA_INTFRM_T long long
838 #else
840 #define LUA_INTFRMLEN "l"
841 #define LUA_INTFRM_T long
843 #endif
844 #endif /* } */
848 ** LUA_FLTFRMLEN is the length modifier for float conversions in
849 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
850 ** the previous length
852 #if !defined(LUA_FLTFRMLEN)
854 #define LUA_FLTFRMLEN ""
855 #define LUA_FLTFRM_T double
857 #endif
860 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
861 #define MAX_ITEM 512
862 /* valid flags in a format specification */
863 #define FLAGS "-+ #0"
865 ** maximum size of each format specification (such as '%-099.99d')
866 ** (+10 accounts for %99.99x plus margin of error)
868 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
871 static void addquoted(lua_State *L, luaL_Buffer *b, int arg) {
872 size_t l;
873 const char *s = luaL_checklstring(L, arg, &l);
874 luaL_addchar(b, '"');
875 while (l--) {
876 if (*s == '"' || *s == '\\' || *s == '\n') {
877 luaL_addchar(b, '\\');
878 luaL_addchar(b, *s);
879 } else if (*s == '\0' || iscntrl(uchar(*s))) {
880 char buff[10];
881 if (!isdigit(uchar(*(s + 1))))
882 sprintf(buff, "\\%d", (int)uchar(*s));
883 else
884 sprintf(buff, "\\%03d", (int)uchar(*s));
885 luaL_addstring(b, buff);
886 } else
887 luaL_addchar(b, *s);
888 s++;
890 luaL_addchar(b, '"');
893 static const char *scanformat(lua_State *L, const char *strfrmt, char *form) {
894 const char *p = strfrmt;
895 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
896 if ((size_t)(p - strfrmt) >= sizeof(FLAGS) / sizeof(char))
897 luaL_error(L, "invalid format (repeated flags)");
898 if (isdigit(uchar(*p))) p++; /* skip width */
899 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
900 if (*p == '.') {
901 p++;
902 if (isdigit(uchar(*p))) p++; /* skip precision */
903 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
905 if (isdigit(uchar(*p)))
906 luaL_error(L, "invalid format (width or precision too long)");
907 *(form++) = '%';
908 memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
909 form += p - strfrmt + 1;
910 *form = '\0';
911 return p;
916 ** add length modifier into formats
918 static void addlenmod(char *form, const char *lenmod) {
919 size_t l = strlen(form);
920 size_t lm = strlen(lenmod);
921 char spec = form[l - 1];
922 strcpy(form + l - 1, lenmod);
923 form[l + lm - 1] = spec;
924 form[l + lm] = '\0';
928 static int str_format(lua_State *L) {
929 int top = lua_gettop(L);
930 int arg = 1;
931 size_t sfl;
932 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
933 const char *strfrmt_end = strfrmt + sfl;
934 luaL_Buffer b;
935 luaL_buffinit(L, &b);
936 while (strfrmt < strfrmt_end) {
937 if (*strfrmt != L_ESC)
938 luaL_addchar(&b, *strfrmt++);
939 else if (*++strfrmt == L_ESC)
940 luaL_addchar(&b, *strfrmt++); /* %% */
941 else { /* format item */
942 char form[MAX_FORMAT]; /* to store the format (`%...') */
943 char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
944 int nb = 0; /* number of bytes in added item */
945 if (++arg > top)
946 luaL_argerror(L, arg, "no value");
947 strfrmt = scanformat(L, strfrmt, form);
948 switch (*strfrmt++) {
949 case 'c': {
950 nb = sprintf(buff, form, luaL_checkint(L, arg));
951 break;
953 case 'd':
954 case 'i': {
955 lua_Number n = luaL_checknumber(L, arg);
956 LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
957 lua_Number diff = n - (lua_Number)ni;
958 luaL_argcheck(L, -1 < diff && diff < 1, arg,
959 "not a number in proper range");
960 addlenmod(form, LUA_INTFRMLEN);
961 nb = sprintf(buff, form, ni);
962 break;
964 case 'o':
965 case 'u':
966 case 'x':
967 case 'X': {
968 lua_Number n = luaL_checknumber(L, arg);
969 unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
970 lua_Number diff = n - (lua_Number)ni;
971 luaL_argcheck(L, -1 < diff && diff < 1, arg,
972 "not a non-negative number in proper range");
973 addlenmod(form, LUA_INTFRMLEN);
974 nb = sprintf(buff, form, ni);
975 break;
977 case 'e':
978 case 'E':
979 case 'f':
980 #if defined(LUA_USE_AFORMAT)
981 case 'a':
982 case 'A':
983 #endif
984 case 'g':
985 case 'G': {
986 addlenmod(form, LUA_FLTFRMLEN);
987 nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
988 break;
990 case 'q': {
991 addquoted(L, &b, arg);
992 break;
994 case 's': {
995 size_t l;
996 const char *s = luaL_tolstring(L, arg, &l);
997 if (!strchr(form, '.') && l >= 100) {
998 /* no precision and string is too long to be formatted;
999 keep original string */
1000 luaL_addvalue(&b);
1001 break;
1002 } else {
1003 nb = sprintf(buff, form, s);
1004 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
1005 break;
1008 default: { /* also treat cases `pnLlh' */
1009 return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
1010 LUA_QL("format"), *(strfrmt - 1));
1013 luaL_addsize(&b, nb);
1016 luaL_pushresult(&b);
1017 return 1;
1020 /* }====================================================== */
1023 static const luaL_Reg strlib[] = {
1024 {"byte", str_byte},
1025 {"char", str_char},
1026 {"dump", str_dump},
1027 {"find", str_find},
1028 {"format", str_format},
1029 {"gmatch", gmatch},
1030 {"gsub", str_gsub},
1031 {"len", str_len},
1032 {"lower", str_lower},
1033 {"match", str_match},
1034 {"rep", str_rep},
1035 {"reverse", str_reverse},
1036 {"sub", str_sub},
1037 {"upper", str_upper},
1038 {NULL, NULL}
1042 static void createmetatable(lua_State *L) {
1043 lua_createtable(L, 0, 1); /* table to be metatable for strings */
1044 lua_pushliteral(L, ""); /* dummy string */
1045 lua_pushvalue(L, -2); /* copy table */
1046 lua_setmetatable(L, -2); /* set table as metatable for strings */
1047 lua_pop(L, 1); /* pop dummy string */
1048 lua_pushvalue(L, -2); /* get string library */
1049 lua_setfield(L, -2, "__index"); /* metatable.__index = string */
1050 lua_pop(L, 1); /* pop metatable */
1055 ** Open string library
1057 LUAMOD_API int luaopen_string(lua_State *L) {
1058 luaL_newlib(L, strlib);
1059 createmetatable(L);
1060 return 1;