LCOV - code coverage report
Current view: top level - external/lua/src - lstrlib.c (source / functions) Hit Total Coverage
Test: rapport Lines: 15 903 1.7 %
Date: 2021-12-10 16:22:55 Functions: 2 71 2.8 %
Branches: 0 554 0.0 %

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

Generated by: LCOV version 1.15