2 ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Standard library for string operations and pattern-matching
4 ** See Copyright Notice in lua.h
9 #include <sys/zfs_context.h>
21 ** maximum number of captures that a pattern can do during
22 ** pattern-matching. This limit is arbitrary.
24 #if !defined(LUA_MAXCAPTURES)
25 #define LUA_MAXCAPTURES 32
29 /* macro to `unsign' a character */
30 #define uchar(c) ((unsigned char)(c))
33 * PATCHED: add missing character macros.
35 #define tolower(C) (((C) >= 'A' && (C) <= 'Z') ? (C) - 'A' + 'a' : (C))
36 #define toupper(C) (((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A': (C))
37 #define iscntrl(C) ((((C) >= 0) && ((C) <= 0x1f)) || ((C) == 0x7f))
38 #define isgraph(C) ((C) >= 0x21 && (C) <= 0x7E)
39 #define ispunct(C) (((C) >= 0x21 && (C) <= 0x2F) || \
40 ((C) >= 0x3A && (C) <= 0x40) || \
41 ((C) >= 0x5B && (C) <= 0x60) || \
42 ((C) >= 0x7B && (C) <= 0x7E))
45 * The provided version of sprintf returns a char *, but str_format expects
46 * it to return the number of characters printed. This version has the expected
49 static size_t str_sprintf(char *buf
, const char *fmt
, ...) {
54 len
= vsnprintf(buf
, INT_MAX
, fmt
, args
);
61 static int str_len (lua_State
*L
) {
63 luaL_checklstring(L
, 1, &l
);
64 lua_pushinteger(L
, (lua_Integer
)l
);
69 /* translate a relative string position: negative means back from end */
70 static size_t posrelat (ptrdiff_t pos
, size_t len
) {
71 if (pos
>= 0) return (size_t)pos
;
72 else if (0u - (size_t)pos
> len
) return 0;
73 else return len
- ((size_t)-pos
) + 1;
77 static int str_sub (lua_State
*L
) {
79 const char *s
= luaL_checklstring(L
, 1, &l
);
80 size_t start
= posrelat(luaL_checkinteger(L
, 2), l
);
81 size_t end
= posrelat(luaL_optinteger(L
, 3, -1), l
);
82 if (start
< 1) start
= 1;
85 lua_pushlstring(L
, s
+ start
- 1, end
- start
+ 1);
86 else lua_pushliteral(L
, "");
91 static int str_reverse (lua_State
*L
) {
94 const char *s
= luaL_checklstring(L
, 1, &l
);
95 char *p
= luaL_buffinitsize(L
, &b
, l
);
96 for (i
= 0; i
< l
; i
++)
98 luaL_pushresultsize(&b
, l
);
103 static int str_lower (lua_State
*L
) {
107 const char *s
= luaL_checklstring(L
, 1, &l
);
108 char *p
= luaL_buffinitsize(L
, &b
, l
);
110 p
[i
] = tolower(uchar(s
[i
]));
111 luaL_pushresultsize(&b
, l
);
116 static int str_upper (lua_State
*L
) {
120 const char *s
= luaL_checklstring(L
, 1, &l
);
121 char *p
= luaL_buffinitsize(L
, &b
, l
);
123 p
[i
] = toupper(uchar(s
[i
]));
124 luaL_pushresultsize(&b
, l
);
129 /* reasonable limit to avoid arithmetic overflow */
130 #define MAXSIZE ((~(size_t)0) >> 1)
132 static int str_rep (lua_State
*L
) {
134 const char *s
= luaL_checklstring(L
, 1, &l
);
135 int n
= luaL_checkint(L
, 2);
136 const char *sep
= luaL_optlstring(L
, 3, "", &lsep
);
137 if (n
<= 0) lua_pushliteral(L
, "");
138 else if (l
+ lsep
< l
|| l
+ lsep
>= MAXSIZE
/ n
) /* may overflow? */
139 return luaL_error(L
, "resulting string too large");
141 size_t totallen
= n
* l
+ (n
- 1) * lsep
;
143 char *p
= luaL_buffinitsize(L
, &b
, totallen
);
144 while (n
-- > 1) { /* first n-1 copies (followed by separator) */
145 memcpy(p
, s
, l
* sizeof(char)); p
+= l
;
146 if (lsep
> 0) { /* avoid empty 'memcpy' (may be expensive) */
147 memcpy(p
, sep
, lsep
* sizeof(char)); p
+= lsep
;
150 memcpy(p
, s
, l
* sizeof(char)); /* last copy (not followed by separator) */
151 luaL_pushresultsize(&b
, totallen
);
157 static int str_byte (lua_State
*L
) {
159 const char *s
= luaL_checklstring(L
, 1, &l
);
160 size_t posi
= posrelat(luaL_optinteger(L
, 2, 1), l
);
161 size_t pose
= posrelat(luaL_optinteger(L
, 3, posi
), l
);
163 if (posi
< 1) posi
= 1;
164 if (pose
> l
) pose
= l
;
165 if (posi
> pose
) return 0; /* empty interval; return no values */
166 n
= (int)(pose
- posi
+ 1);
167 if (posi
+ n
<= pose
) /* (size_t -> int) overflow? */
168 return luaL_error(L
, "string slice too long");
169 luaL_checkstack(L
, n
, "string slice too long");
171 lua_pushinteger(L
, uchar(s
[posi
+i
-1]));
176 static int str_char (lua_State
*L
) {
177 int n
= lua_gettop(L
); /* number of arguments */
180 char *p
= luaL_buffinitsize(L
, &b
, n
);
181 for (i
=1; i
<=n
; i
++) {
182 int c
= luaL_checkint(L
, i
);
183 luaL_argcheck(L
, uchar(c
) == c
, i
, "value out of range");
186 luaL_pushresultsize(&b
, n
);
191 static int writer (lua_State
*L
, const void* b
, size_t size
, void* B
) {
193 luaL_addlstring((luaL_Buffer
*) B
, (const char *)b
, size
);
198 static int str_dump (lua_State
*L
) {
200 luaL_checktype(L
, 1, LUA_TFUNCTION
);
203 if (lua_dump(L
, writer
, &b
) != 0)
204 return luaL_error(L
, "unable to dump given function");
212 ** {======================================================
214 ** =======================================================
218 #define CAP_UNFINISHED (-1)
219 #define CAP_POSITION (-2)
222 typedef struct MatchState
{
223 int matchdepth
; /* control for recursive depth (to avoid C stack overflow) */
224 const char *src_init
; /* init of source string */
225 const char *src_end
; /* end ('\0') of source string */
226 const char *p_end
; /* end ('\0') of pattern */
228 int level
; /* total number of captures (finished or unfinished) */
232 } capture
[LUA_MAXCAPTURES
];
236 /* recursive function */
237 static const char *match (MatchState
*ms
, const char *s
, const char *p
);
240 /* maximum recursion depth for 'match' */
241 #if !defined(MAXCCALLS)
242 #define MAXCCALLS 200
247 #define SPECIALS "^$*+?.([%-"
250 static int check_capture (MatchState
*ms
, int l
) {
252 if (l
< 0 || l
>= ms
->level
|| ms
->capture
[l
].len
== CAP_UNFINISHED
)
253 return luaL_error(ms
->L
, "invalid capture index %%%d", l
+ 1);
258 static int capture_to_close (MatchState
*ms
) {
259 int level
= ms
->level
;
260 for (level
--; level
>=0; level
--)
261 if (ms
->capture
[level
].len
== CAP_UNFINISHED
) return level
;
262 return luaL_error(ms
->L
, "invalid pattern capture");
266 static const char *classend (MatchState
*ms
, const char *p
) {
270 luaL_error(ms
->L
, "malformed pattern (ends with " LUA_QL("%%") ")");
275 do { /* look for a `]' */
277 luaL_error(ms
->L
, "malformed pattern (missing " LUA_QL("]") ")");
278 if (*(p
++) == L_ESC
&& p
< ms
->p_end
)
279 p
++; /* skip escapes (e.g. `%]') */
290 static int match_class (int c
, int cl
) {
292 switch (tolower(cl
)) {
293 case 'a' : res
= isalpha(c
); break;
294 case 'c' : res
= iscntrl(c
); break;
295 case 'd' : res
= isdigit(c
); break;
296 case 'g' : res
= isgraph(c
); break;
297 case 'l' : res
= islower(c
); break;
298 case 'p' : res
= ispunct(c
); break;
299 case 's' : res
= isspace(c
); break;
300 case 'u' : res
= isupper(c
); break;
301 case 'w' : res
= isalnum(c
); break;
302 case 'x' : res
= isxdigit(c
); break;
303 case 'z' : res
= (c
== 0); break; /* deprecated option */
304 default: return (cl
== c
);
306 return (islower(cl
) ? res
: !res
);
310 static int matchbracketclass (int c
, const char *p
, const char *ec
) {
314 p
++; /* skip the `^' */
319 if (match_class(c
, uchar(*p
)))
322 else if ((*(p
+1) == '-') && (p
+2 < ec
)) {
324 if (uchar(*(p
-2)) <= c
&& c
<= uchar(*p
))
327 else if (uchar(*p
) == c
) return sig
;
333 static int singlematch (MatchState
*ms
, const char *s
, const char *p
,
335 if (s
>= ms
->src_end
)
340 case '.': return 1; /* matches any char */
341 case L_ESC
: return match_class(c
, uchar(*(p
+1)));
342 case '[': return matchbracketclass(c
, p
, ep
-1);
343 default: return (uchar(*p
) == c
);
349 static const char *matchbalance (MatchState
*ms
, const char *s
,
351 if (p
>= ms
->p_end
- 1)
352 luaL_error(ms
->L
, "malformed pattern "
353 "(missing arguments to " LUA_QL("%%b") ")");
354 if (*s
!= *p
) return NULL
;
359 while (++s
< ms
->src_end
) {
361 if (--cont
== 0) return s
+1;
363 else if (*s
== b
) cont
++;
366 return NULL
; /* string ends out of balance */
370 static const char *max_expand (MatchState
*ms
, const char *s
,
371 const char *p
, const char *ep
) {
372 ptrdiff_t i
= 0; /* counts maximum expand for item */
373 while (singlematch(ms
, s
+ i
, p
, ep
))
375 /* keeps trying to match with the maximum repetitions */
377 const char *res
= match(ms
, (s
+i
), ep
+1);
379 i
--; /* else didn't match; reduce 1 repetition to try again */
385 static const char *min_expand (MatchState
*ms
, const char *s
,
386 const char *p
, const char *ep
) {
388 const char *res
= match(ms
, s
, ep
+1);
391 else if (singlematch(ms
, s
, p
, ep
))
392 s
++; /* try with one more repetition */
398 static const char *start_capture (MatchState
*ms
, const char *s
,
399 const char *p
, int what
) {
401 int level
= ms
->level
;
402 if (level
>= LUA_MAXCAPTURES
) luaL_error(ms
->L
, "too many captures");
403 ms
->capture
[level
].init
= s
;
404 ms
->capture
[level
].len
= what
;
406 if ((res
=match(ms
, s
, p
)) == NULL
) /* match failed? */
407 ms
->level
--; /* undo capture */
412 static const char *end_capture (MatchState
*ms
, const char *s
,
414 int l
= capture_to_close(ms
);
416 ms
->capture
[l
].len
= s
- ms
->capture
[l
].init
; /* close capture */
417 if ((res
= match(ms
, s
, p
)) == NULL
) /* match failed? */
418 ms
->capture
[l
].len
= CAP_UNFINISHED
; /* undo capture */
423 static const char *match_capture (MatchState
*ms
, const char *s
, int l
) {
425 l
= check_capture(ms
, l
);
426 len
= ms
->capture
[l
].len
;
427 if ((size_t)(ms
->src_end
-s
) >= len
&&
428 memcmp(ms
->capture
[l
].init
, s
, len
) == 0)
434 static const char *match (MatchState
*ms
, const char *s
, const char *p
) {
435 if (ms
->matchdepth
-- == 0)
436 luaL_error(ms
->L
, "pattern too complex");
437 init
: /* using goto's to optimize tail recursion */
438 if (p
!= ms
->p_end
) { /* end of pattern? */
440 case '(': { /* start capture */
441 if (*(p
+ 1) == ')') /* position capture? */
442 s
= start_capture(ms
, s
, p
+ 2, CAP_POSITION
);
444 s
= start_capture(ms
, s
, p
+ 1, CAP_UNFINISHED
);
447 case ')': { /* end capture */
448 s
= end_capture(ms
, s
, p
+ 1);
452 if ((p
+ 1) != ms
->p_end
) /* is the `$' the last char in pattern? */
453 goto dflt
; /* no; go to default */
454 s
= (s
== ms
->src_end
) ? s
: NULL
; /* check end of string */
457 case L_ESC
: { /* escaped sequences not in the format class[*+?-]? */
459 case 'b': { /* balanced string? */
460 s
= matchbalance(ms
, s
, p
+ 2);
462 p
+= 4; goto init
; /* return match(ms, s, p + 4); */
463 } /* else fail (s == NULL) */
466 case 'f': { /* frontier? */
467 const char *ep
; char previous
;
470 luaL_error(ms
->L
, "missing " LUA_QL("[") " after "
471 LUA_QL("%%f") " in pattern");
472 ep
= classend(ms
, p
); /* points to what is next */
473 previous
= (s
== ms
->src_init
) ? '\0' : *(s
- 1);
474 if (!matchbracketclass(uchar(previous
), p
, ep
- 1) &&
475 matchbracketclass(uchar(*s
), p
, ep
- 1)) {
476 p
= ep
; goto init
; /* return match(ms, s, ep); */
478 s
= NULL
; /* match failed */
481 case '0': case '1': case '2': case '3':
482 case '4': case '5': case '6': case '7':
483 case '8': case '9': { /* capture results (%0-%9)? */
484 s
= match_capture(ms
, s
, uchar(*(p
+ 1)));
486 p
+= 2; goto init
; /* return match(ms, s, p + 2) */
494 default: dflt
: { /* pattern class plus optional suffix */
495 const char *ep
= classend(ms
, p
); /* points to optional suffix */
496 /* does not match at least once? */
497 if (!singlematch(ms
, s
, p
, ep
)) {
498 if (*ep
== '*' || *ep
== '?' || *ep
== '-') { /* accept empty? */
499 p
= ep
+ 1; goto init
; /* return match(ms, s, ep + 1); */
501 else /* '+' or no suffix */
504 else { /* matched once */
505 switch (*ep
) { /* handle optional suffix */
506 case '?': { /* optional */
508 if ((res
= match(ms
, s
+ 1, ep
+ 1)) != NULL
)
511 p
= ep
+ 1; goto init
; /* else return match(ms, s, ep + 1); */
515 case '+': /* 1 or more repetitions */
516 s
++; /* 1 match already done */
518 case '*': /* 0 or more repetitions */
519 s
= max_expand(ms
, s
, p
, ep
);
521 case '-': /* 0 or more repetitions (minimum) */
522 s
= min_expand(ms
, s
, p
, ep
);
524 default: /* no suffix */
525 s
++; p
= ep
; goto init
; /* return match(ms, s + 1, ep); */
538 static const char *lmemfind (const char *s1
, size_t l1
,
539 const char *s2
, size_t l2
) {
540 if (l2
== 0) return s1
; /* empty strings are everywhere */
541 else if (l2
> l1
) return NULL
; /* avoids a negative `l1' */
543 const char *init
; /* to search for a `*s2' inside `s1' */
544 l2
--; /* 1st char will be checked by `memchr' */
545 l1
= l1
-l2
; /* `s2' cannot be found after that */
546 while (l1
> 0 && (init
= (const char *)memchr(s1
, *s2
, l1
)) != NULL
) {
547 init
++; /* 1st char is already checked */
548 if (memcmp(init
, s2
+1, l2
) == 0)
550 else { /* correct `l1' and `s1' to try again */
555 return NULL
; /* not found */
560 static void push_onecapture (MatchState
*ms
, int i
, const char *s
,
562 if (i
>= ms
->level
) {
563 if (i
== 0) /* ms->level == 0, too */
564 lua_pushlstring(ms
->L
, s
, e
- s
); /* add whole match */
566 luaL_error(ms
->L
, "invalid capture index");
569 ptrdiff_t l
= ms
->capture
[i
].len
;
570 if (l
== CAP_UNFINISHED
) luaL_error(ms
->L
, "unfinished capture");
571 if (l
== CAP_POSITION
)
572 lua_pushinteger(ms
->L
, ms
->capture
[i
].init
- ms
->src_init
+ 1);
574 lua_pushlstring(ms
->L
, ms
->capture
[i
].init
, l
);
579 static int push_captures (MatchState
*ms
, const char *s
, const char *e
) {
581 int nlevels
= (ms
->level
== 0 && s
) ? 1 : ms
->level
;
582 luaL_checkstack(ms
->L
, nlevels
, "too many captures");
583 for (i
= 0; i
< nlevels
; i
++)
584 push_onecapture(ms
, i
, s
, e
);
585 return nlevels
; /* number of strings pushed */
589 /* check whether pattern has no special characters */
590 static int nospecials (const char *p
, size_t l
) {
593 if (strpbrk(p
+ upto
, SPECIALS
))
594 return 0; /* pattern has a special character */
595 upto
+= strlen(p
+ upto
) + 1; /* may have more after \0 */
597 return 1; /* no special chars found */
601 static int str_find_aux (lua_State
*L
, int find
) {
603 const char *s
= luaL_checklstring(L
, 1, &ls
);
604 const char *p
= luaL_checklstring(L
, 2, &lp
);
605 size_t init
= posrelat(luaL_optinteger(L
, 3, 1), ls
);
606 if (init
< 1) init
= 1;
607 else if (init
> ls
+ 1) { /* start after string's end? */
608 lua_pushnil(L
); /* cannot find anything */
611 /* explicit request or no special characters? */
612 if (find
&& (lua_toboolean(L
, 4) || nospecials(p
, lp
))) {
613 /* do a plain search */
614 const char *s2
= lmemfind(s
+ init
- 1, ls
- init
+ 1, p
, lp
);
616 lua_pushinteger(L
, s2
- s
+ 1);
617 lua_pushinteger(L
, s2
- s
+ lp
);
623 const char *s1
= s
+ init
- 1;
624 int anchor
= (*p
== '^');
626 p
++; lp
--; /* skip anchor character */
629 ms
.matchdepth
= MAXCCALLS
;
636 lua_assert(ms
.matchdepth
== MAXCCALLS
);
637 if ((res
=match(&ms
, s1
, p
)) != NULL
) {
639 lua_pushinteger(L
, s1
- s
+ 1); /* start */
640 lua_pushinteger(L
, res
- s
); /* end */
641 return push_captures(&ms
, NULL
, 0) + 2;
644 return push_captures(&ms
, s1
, res
);
646 } while (s1
++ < ms
.src_end
&& !anchor
);
648 lua_pushnil(L
); /* not found */
653 static int str_find (lua_State
*L
) {
654 return str_find_aux(L
, 1);
658 static int str_match (lua_State
*L
) {
659 return str_find_aux(L
, 0);
663 static int gmatch_aux (lua_State
*L
) {
666 const char *s
= lua_tolstring(L
, lua_upvalueindex(1), &ls
);
667 const char *p
= lua_tolstring(L
, lua_upvalueindex(2), &lp
);
670 ms
.matchdepth
= MAXCCALLS
;
674 for (src
= s
+ (size_t)lua_tointeger(L
, lua_upvalueindex(3));
679 lua_assert(ms
.matchdepth
== MAXCCALLS
);
680 if ((e
= match(&ms
, src
, p
)) != NULL
) {
681 lua_Integer newstart
= e
-s
;
682 if (e
== src
) newstart
++; /* empty match? go at least one position */
683 lua_pushinteger(L
, newstart
);
684 lua_replace(L
, lua_upvalueindex(3));
685 return push_captures(&ms
, src
, e
);
688 return 0; /* not found */
692 static int str_gmatch (lua_State
*L
) {
693 luaL_checkstring(L
, 1);
694 luaL_checkstring(L
, 2);
696 lua_pushinteger(L
, 0);
697 lua_pushcclosure(L
, gmatch_aux
, 3);
702 static void add_s (MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
705 const char *news
= lua_tolstring(ms
->L
, 3, &l
);
706 for (i
= 0; i
< l
; i
++) {
707 if (news
[i
] != L_ESC
)
708 luaL_addchar(b
, news
[i
]);
711 if (!isdigit(uchar(news
[i
]))) {
712 if (news
[i
] != L_ESC
)
713 luaL_error(ms
->L
, "invalid use of " LUA_QL("%c")
714 " in replacement string", L_ESC
);
715 luaL_addchar(b
, news
[i
]);
717 else if (news
[i
] == '0')
718 luaL_addlstring(b
, s
, e
- s
);
720 push_onecapture(ms
, news
[i
] - '1', s
, e
);
721 luaL_addvalue(b
); /* add capture to accumulated result */
728 static void add_value (MatchState
*ms
, luaL_Buffer
*b
, const char *s
,
729 const char *e
, int tr
) {
730 lua_State
*L
= ms
->L
;
732 case LUA_TFUNCTION
: {
735 n
= push_captures(ms
, s
, e
);
740 push_onecapture(ms
, 0, s
, e
);
744 default: { /* LUA_TNUMBER or LUA_TSTRING */
749 if (!lua_toboolean(L
, -1)) { /* nil or false? */
751 lua_pushlstring(L
, s
, e
- s
); /* keep original text */
753 else if (!lua_isstring(L
, -1))
754 luaL_error(L
, "invalid replacement value (a %s)", luaL_typename(L
, -1));
755 luaL_addvalue(b
); /* add result to accumulator */
759 static int str_gsub (lua_State
*L
) {
761 const char *src
= luaL_checklstring(L
, 1, &srcl
);
762 const char *p
= luaL_checklstring(L
, 2, &lp
);
763 int tr
= lua_type(L
, 3);
764 size_t max_s
= luaL_optinteger(L
, 4, srcl
+1);
765 int anchor
= (*p
== '^');
769 luaL_argcheck(L
, tr
== LUA_TNUMBER
|| tr
== LUA_TSTRING
||
770 tr
== LUA_TFUNCTION
|| tr
== LUA_TTABLE
, 3,
771 "string/function/table expected");
772 luaL_buffinit(L
, &b
);
774 p
++; lp
--; /* skip anchor character */
777 ms
.matchdepth
= MAXCCALLS
;
779 ms
.src_end
= src
+srcl
;
784 lua_assert(ms
.matchdepth
== MAXCCALLS
);
785 e
= match(&ms
, src
, p
);
788 add_value(&ms
, &b
, src
, e
, tr
);
790 if (e
&& e
>src
) /* non empty match? */
791 src
= e
; /* skip it */
792 else if (src
< ms
.src_end
)
793 luaL_addchar(&b
, *src
++);
797 luaL_addlstring(&b
, src
, ms
.src_end
-src
);
799 lua_pushinteger(L
, n
); /* number of substitutions */
803 /* }====================================================== */
808 ** {======================================================
810 ** =======================================================
814 ** LUA_INTFRMLEN is the length modifier for integer conversions in
815 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
816 ** the previous length
818 #if !defined(LUA_INTFRMLEN) /* { */
819 #if defined(LUA_USE_LONGLONG)
821 #define LUA_INTFRMLEN "ll"
822 #define LUA_INTFRM_T long long
826 #define LUA_INTFRMLEN "l"
827 #define LUA_INTFRM_T long
834 ** LUA_FLTFRMLEN is the length modifier for float conversions in
835 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
836 ** the previous length
838 #if !defined(LUA_FLTFRMLEN)
840 #define LUA_FLTFRMLEN ""
841 #define LUA_FLTFRM_T double
846 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
848 /* valid flags in a format specification */
849 #define FLAGS "-+ #0"
851 ** maximum size of each format specification (such as '%-099.99d')
852 ** (+10 accounts for %99.99x plus margin of error)
854 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
857 static void addquoted (lua_State
*L
, luaL_Buffer
*b
, int arg
) {
859 const char *s
= luaL_checklstring(L
, arg
, &l
);
860 luaL_addchar(b
, '"');
862 if (*s
== '"' || *s
== '\\' || *s
== '\n') {
863 luaL_addchar(b
, '\\');
866 else if (*s
== '\0' || iscntrl(uchar(*s
))) {
868 if (!isdigit(uchar(*(s
+1))))
869 sprintf(buff
, "\\%d", (int)uchar(*s
));
871 sprintf(buff
, "\\%03d", (int)uchar(*s
));
872 luaL_addstring(b
, buff
);
878 luaL_addchar(b
, '"');
881 static const char *scanformat (lua_State
*L
, const char *strfrmt
, char *form
) {
882 const char *p
= strfrmt
;
883 while (*p
!= '\0' && strchr(FLAGS
, *p
) != NULL
) p
++; /* skip flags */
884 if ((size_t)(p
- strfrmt
) >= sizeof(FLAGS
)/sizeof(char))
885 luaL_error(L
, "invalid format (repeated flags)");
886 if (isdigit(uchar(*p
))) p
++; /* skip width */
887 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
890 if (isdigit(uchar(*p
))) p
++; /* skip precision */
891 if (isdigit(uchar(*p
))) p
++; /* (2 digits at most) */
893 if (isdigit(uchar(*p
)))
894 luaL_error(L
, "invalid format (width or precision too long)");
896 memcpy(form
, strfrmt
, (p
- strfrmt
+ 1) * sizeof(char));
897 form
+= p
- strfrmt
+ 1;
904 ** add length modifier into formats
906 static void addlenmod (char *form
, const char *lenmod
) {
907 size_t l
= strlen(form
);
908 size_t lm
= strlen(lenmod
);
909 char spec
= form
[l
- 1];
910 strcpy(form
+ l
- 1, lenmod
);
911 form
[l
+ lm
- 1] = spec
;
916 static int str_format (lua_State
*L
) {
917 int top
= lua_gettop(L
);
920 const char *strfrmt
= luaL_checklstring(L
, arg
, &sfl
);
921 const char *strfrmt_end
= strfrmt
+sfl
;
923 luaL_buffinit(L
, &b
);
924 while (strfrmt
< strfrmt_end
) {
925 if (*strfrmt
!= L_ESC
)
926 luaL_addchar(&b
, *strfrmt
++);
927 else if (*++strfrmt
== L_ESC
)
928 luaL_addchar(&b
, *strfrmt
++); /* %% */
929 else { /* format item */
930 char form
[MAX_FORMAT
]; /* to store the format (`%...') */
931 char *buff
= luaL_prepbuffsize(&b
, MAX_ITEM
); /* to put formatted item */
932 int nb
= 0; /* number of bytes in added item */
934 luaL_argerror(L
, arg
, "no value");
935 strfrmt
= scanformat(L
, strfrmt
, form
);
936 switch (*strfrmt
++) {
938 nb
= str_sprintf(buff
, form
, luaL_checkint(L
, arg
));
941 case 'd': case 'i': {
942 lua_Number n
= luaL_checknumber(L
, arg
);
943 LUA_INTFRM_T ni
= (LUA_INTFRM_T
)n
;
944 lua_Number diff
= n
- (lua_Number
)ni
;
945 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
946 "not a number in proper range");
947 addlenmod(form
, LUA_INTFRMLEN
);
948 nb
= str_sprintf(buff
, form
, ni
);
951 case 'o': case 'u': case 'x': case 'X': {
952 lua_Number n
= luaL_checknumber(L
, arg
);
953 unsigned LUA_INTFRM_T ni
= (unsigned LUA_INTFRM_T
)n
;
954 lua_Number diff
= n
- (lua_Number
)ni
;
955 luaL_argcheck(L
, -1 < diff
&& diff
< 1, arg
,
956 "not a non-negative number in proper range");
957 addlenmod(form
, LUA_INTFRMLEN
);
958 nb
= str_sprintf(buff
, form
, ni
);
961 #if defined(LUA_USE_FLOAT_FORMATS)
962 case 'e': case 'E': case 'f':
963 #if defined(LUA_USE_AFORMAT)
966 case 'g': case 'G': {
967 addlenmod(form
, LUA_FLTFRMLEN
);
968 nb
= str_sprintf(buff
, form
, (LUA_FLTFRM_T
)luaL_checknumber(L
, arg
));
973 addquoted(L
, &b
, arg
);
978 const char *s
= luaL_tolstring(L
, arg
, &l
);
979 if (!strchr(form
, '.') && l
>= 100) {
980 /* no precision and string is too long to be formatted;
981 keep original string */
986 nb
= str_sprintf(buff
, form
, s
);
987 lua_pop(L
, 1); /* remove result from 'luaL_tolstring' */
991 default: { /* also treat cases `pnLlh' */
992 return luaL_error(L
, "invalid option " LUA_QL("%%%c") " to "
993 LUA_QL("format"), *(strfrmt
- 1));
996 luaL_addsize(&b
, nb
);
1003 /* }====================================================== */
1006 static const luaL_Reg strlib
[] = {
1011 {"format", str_format
},
1012 {"gmatch", str_gmatch
},
1015 {"lower", str_lower
},
1016 {"match", str_match
},
1018 {"reverse", str_reverse
},
1020 {"upper", str_upper
},
1025 static void createmetatable (lua_State
*L
) {
1026 lua_createtable(L
, 0, 1); /* table to be metatable for strings */
1027 lua_pushliteral(L
, ""); /* dummy string */
1028 lua_pushvalue(L
, -2); /* copy table */
1029 lua_setmetatable(L
, -2); /* set table as metatable for strings */
1030 lua_pop(L
, 1); /* pop dummy string */
1031 lua_pushvalue(L
, -2); /* get string library */
1032 lua_setfield(L
, -2, "__index"); /* metatable.__index = string */
1033 lua_pop(L
, 1); /* pop metatable */
1038 ** Open string library
1040 LUAMOD_API
int luaopen_string (lua_State
*L
) {
1041 luaL_newlib(L
, strlib
);