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