Path: blob/main/sys/contrib/openzfs/module/lua/lstrlib.c
48383 views
// SPDX-License-Identifier: MIT1/*2** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $3** Standard library for string operations and pattern-matching4** See Copyright Notice in lua.h5*/678#define lstrlib_c9#define LUA_LIB1011#include <sys/lua/lua.h>1213#include <sys/lua/lauxlib.h>14#include <sys/lua/lualib.h>151617/*18** maximum number of captures that a pattern can do during19** pattern-matching. This limit is arbitrary.20*/21#if !defined(LUA_MAXCAPTURES)22#define LUA_MAXCAPTURES 1623#endif242526/* macro to `unsign' a character */27#define uchar(c) ((unsigned char)(c))2829/*30* The provided version of sprintf returns a char *, but str_format expects31* it to return the number of characters printed. This version has the expected32* behavior.33*/34static size_t str_sprintf(char *buf, const char *fmt, ...) {35va_list args;36size_t len;3738va_start(args, fmt);39len = vsnprintf(buf, INT_MAX, fmt, args);40va_end(args);4142return len;43}444546static int str_len (lua_State *L) {47size_t l;48luaL_checklstring(L, 1, &l);49lua_pushinteger(L, (lua_Integer)l);50return 1;51}525354/* translate a relative string position: negative means back from end */55static size_t posrelat (ptrdiff_t pos, size_t len) {56if (pos >= 0) return (size_t)pos;57else if (0u - (size_t)pos > len) return 0;58else return len - ((size_t)-pos) + 1;59}606162static int str_sub (lua_State *L) {63size_t l;64const char *s = luaL_checklstring(L, 1, &l);65size_t start = posrelat(luaL_checkinteger(L, 2), l);66size_t end = posrelat(luaL_optinteger(L, 3, -1), l);67if (start < 1) start = 1;68if (end > l) end = l;69if (start <= end)70lua_pushlstring(L, s + start - 1, end - start + 1);71else lua_pushliteral(L, "");72return 1;73}747576static int str_reverse (lua_State *L) {77size_t l, i;78luaL_Buffer b;79const char *s = luaL_checklstring(L, 1, &l);80char *p = luaL_buffinitsize(L, &b, l);81for (i = 0; i < l; i++)82p[i] = s[l - i - 1];83luaL_pushresultsize(&b, l);84return 1;85}868788static int str_lower (lua_State *L) {89size_t l;90size_t i;91luaL_Buffer b;92const char *s = luaL_checklstring(L, 1, &l);93char *p = luaL_buffinitsize(L, &b, l);94for (i=0; i<l; i++)95p[i] = tolower(uchar(s[i]));96luaL_pushresultsize(&b, l);97return 1;98}99100101static int str_upper (lua_State *L) {102size_t l;103size_t i;104luaL_Buffer b;105const char *s = luaL_checklstring(L, 1, &l);106char *p = luaL_buffinitsize(L, &b, l);107for (i=0; i<l; i++)108p[i] = toupper(uchar(s[i]));109luaL_pushresultsize(&b, l);110return 1;111}112113114/* reasonable limit to avoid arithmetic overflow */115#define MAXSIZE ((~(size_t)0) >> 1)116117static int str_rep (lua_State *L) {118size_t l, lsep;119const char *s = luaL_checklstring(L, 1, &l);120int n = luaL_checkint(L, 2);121const char *sep = luaL_optlstring(L, 3, "", &lsep);122if (n <= 0) lua_pushliteral(L, "");123else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */124return luaL_error(L, "resulting string too large");125else {126size_t totallen = n * l + (n - 1) * lsep;127luaL_Buffer b;128char *p = luaL_buffinitsize(L, &b, totallen);129while (n-- > 1) { /* first n-1 copies (followed by separator) */130memcpy(p, s, l * sizeof(char)); p += l;131if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */132memcpy(p, sep, lsep * sizeof(char)); p += lsep;133}134}135memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */136luaL_pushresultsize(&b, totallen);137}138return 1;139}140141142static int str_byte (lua_State *L) {143size_t l;144const char *s = luaL_checklstring(L, 1, &l);145size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);146size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);147int n, i;148if (posi < 1) posi = 1;149if (pose > l) pose = l;150if (posi > pose) return 0; /* empty interval; return no values */151n = (int)(pose - posi + 1);152if (posi + n <= pose) /* (size_t -> int) overflow? */153return luaL_error(L, "string slice too long");154luaL_checkstack(L, n, "string slice too long");155for (i=0; i<n; i++)156lua_pushinteger(L, uchar(s[posi+i-1]));157return n;158}159160161static int str_char (lua_State *L) {162int n = lua_gettop(L); /* number of arguments */163int i;164luaL_Buffer b;165char *p = luaL_buffinitsize(L, &b, n);166for (i=1; i<=n; i++) {167int c = luaL_checkint(L, i);168luaL_argcheck(L, uchar(c) == c, i, "value out of range");169p[i - 1] = uchar(c);170}171luaL_pushresultsize(&b, n);172return 1;173}174175176#if defined(LUA_USE_DUMP)177static int writer (lua_State *L, const void* b, size_t size, void* B) {178(void)L;179luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);180return 0;181}182183184static int str_dump (lua_State *L) {185luaL_Buffer b;186luaL_checktype(L, 1, LUA_TFUNCTION);187lua_settop(L, 1);188luaL_buffinit(L,&b);189if (lua_dump(L, writer, &b) != 0)190return luaL_error(L, "unable to dump given function");191luaL_pushresult(&b);192return 1;193}194#endif195196197/*198** {======================================================199** PATTERN MATCHING200** =======================================================201*/202203204#define CAP_UNFINISHED (-1)205#define CAP_POSITION (-2)206207208typedef struct MatchState {209int matchdepth; /* control for recursive depth (to avoid C stack overflow) */210const char *src_init; /* init of source string */211const char *src_end; /* end ('\0') of source string */212const char *p_end; /* end ('\0') of pattern */213lua_State *L;214int level; /* total number of captures (finished or unfinished) */215struct {216const char *init;217ptrdiff_t len;218} capture[LUA_MAXCAPTURES];219} MatchState;220221222/* recursive function */223static const char *match (MatchState *ms, const char *s, const char *p);224225226/* maximum recursion depth for 'match' */227#if !defined(MAXCCALLS)228#define MAXCCALLS 200229#endif230231232#define L_ESC '%'233#define SPECIALS "^$*+?.([%-"234235236static int check_capture (MatchState *ms, int l) {237l -= '1';238if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)239return luaL_error(ms->L, "invalid capture index %%%d", l + 1);240return l;241}242243244static int capture_to_close (MatchState *ms) {245int level = ms->level;246for (level--; level>=0; level--)247if (ms->capture[level].len == CAP_UNFINISHED) return level;248return luaL_error(ms->L, "invalid pattern capture");249}250251252static const char *classend (MatchState *ms, const char *p) {253switch (*p++) {254case L_ESC: {255if (p == ms->p_end)256luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");257return p+1;258}259case '[': {260if (*p == '^') p++;261do { /* look for a `]' */262if (p == ms->p_end)263luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");264if (*(p++) == L_ESC && p < ms->p_end)265p++; /* skip escapes (e.g. `%]') */266} while (*p != ']');267return p+1;268}269default: {270return p;271}272}273}274275276static int match_class (int c, int cl) {277int res;278switch (tolower(cl)) {279case 'a' : res = isalpha(c); break;280case 'c' : res = iscntrl(c); break;281case 'd' : res = isdigit(c); break;282case 'g' : res = isgraph(c); break;283case 'l' : res = islower(c); break;284case 'p' : res = ispunct(c); break;285case 's' : res = isspace(c); break;286case 'u' : res = isupper(c); break;287case 'w' : res = isalnum(c); break;288case 'x' : res = isxdigit(c); break;289case 'z' : res = (c == 0); break; /* deprecated option */290default: return (cl == c);291}292return (islower(cl) ? res : !res);293}294295296static int matchbracketclass (int c, const char *p, const char *ec) {297int sig = 1;298if (*(p+1) == '^') {299sig = 0;300p++; /* skip the `^' */301}302while (++p < ec) {303if (*p == L_ESC) {304p++;305if (match_class(c, uchar(*p)))306return sig;307}308else if ((*(p+1) == '-') && (p+2 < ec)) {309p+=2;310if (uchar(*(p-2)) <= c && c <= uchar(*p))311return sig;312}313else if (uchar(*p) == c) return sig;314}315return !sig;316}317318319static int singlematch (MatchState *ms, const char *s, const char *p,320const char *ep) {321if (s >= ms->src_end)322return 0;323else {324int c = uchar(*s);325switch (*p) {326case '.': return 1; /* matches any char */327case L_ESC: return match_class(c, uchar(*(p+1)));328case '[': return matchbracketclass(c, p, ep-1);329default: return (uchar(*p) == c);330}331}332}333334335static const char *matchbalance (MatchState *ms, const char *s,336const char *p) {337if (p >= ms->p_end - 1)338luaL_error(ms->L, "malformed pattern "339"(missing arguments to " LUA_QL("%%b") ")");340if (*s != *p) return NULL;341else {342int b = *p;343int e = *(p+1);344int cont = 1;345while (++s < ms->src_end) {346if (*s == e) {347if (--cont == 0) return s+1;348}349else if (*s == b) cont++;350}351}352return NULL; /* string ends out of balance */353}354355356static const char *max_expand (MatchState *ms, const char *s,357const char *p, const char *ep) {358ptrdiff_t i = 0; /* counts maximum expand for item */359while (singlematch(ms, s + i, p, ep))360i++;361/* keeps trying to match with the maximum repetitions */362while (i>=0) {363const char *res = match(ms, (s+i), ep+1);364if (res) return res;365i--; /* else didn't match; reduce 1 repetition to try again */366}367return NULL;368}369370371static const char *min_expand (MatchState *ms, const char *s,372const char *p, const char *ep) {373for (;;) {374const char *res = match(ms, s, ep+1);375if (res != NULL)376return res;377else if (singlematch(ms, s, p, ep))378s++; /* try with one more repetition */379else return NULL;380}381}382383384static const char *start_capture (MatchState *ms, const char *s,385const char *p, int what) {386const char *res;387int level = ms->level;388if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");389ms->capture[level].init = s;390ms->capture[level].len = what;391ms->level = level+1;392if ((res=match(ms, s, p)) == NULL) /* match failed? */393ms->level--; /* undo capture */394return res;395}396397398static const char *end_capture (MatchState *ms, const char *s,399const char *p) {400int l = capture_to_close(ms);401const char *res;402ms->capture[l].len = s - ms->capture[l].init; /* close capture */403if ((res = match(ms, s, p)) == NULL) /* match failed? */404ms->capture[l].len = CAP_UNFINISHED; /* undo capture */405return res;406}407408409static const char *match_capture (MatchState *ms, const char *s, int l) {410size_t len;411l = check_capture(ms, l);412len = ms->capture[l].len;413if ((size_t)(ms->src_end-s) >= len &&414memcmp(ms->capture[l].init, s, len) == 0)415return s+len;416else return NULL;417}418419420static const char *match (MatchState *ms, const char *s, const char *p) {421if (ms->matchdepth-- == 0)422luaL_error(ms->L, "pattern too complex");423init: /* using goto's to optimize tail recursion */424if (p != ms->p_end) { /* end of pattern? */425switch (*p) {426case '(': { /* start capture */427if (*(p + 1) == ')') /* position capture? */428s = start_capture(ms, s, p + 2, CAP_POSITION);429else430s = start_capture(ms, s, p + 1, CAP_UNFINISHED);431break;432}433case ')': { /* end capture */434s = end_capture(ms, s, p + 1);435break;436}437case '$': {438if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */439goto dflt; /* no; go to default */440s = (s == ms->src_end) ? s : NULL; /* check end of string */441break;442}443case L_ESC: { /* escaped sequences not in the format class[*+?-]? */444switch (*(p + 1)) {445case 'b': { /* balanced string? */446s = matchbalance(ms, s, p + 2);447if (s != NULL) {448p += 4; goto init; /* return match(ms, s, p + 4); */449} /* else fail (s == NULL) */450break;451}452case 'f': { /* frontier? */453const char *ep; char previous;454p += 2;455if (*p != '[')456luaL_error(ms->L, "missing " LUA_QL("[") " after "457LUA_QL("%%f") " in pattern");458ep = classend(ms, p); /* points to what is next */459previous = (s == ms->src_init) ? '\0' : *(s - 1);460if (!matchbracketclass(uchar(previous), p, ep - 1) &&461matchbracketclass(uchar(*s), p, ep - 1)) {462p = ep; goto init; /* return match(ms, s, ep); */463}464s = NULL; /* match failed */465break;466}467case '0': case '1': case '2': case '3':468case '4': case '5': case '6': case '7':469case '8': case '9': { /* capture results (%0-%9)? */470s = match_capture(ms, s, uchar(*(p + 1)));471if (s != NULL) {472p += 2; goto init; /* return match(ms, s, p + 2) */473}474break;475}476default: goto dflt;477}478break;479}480default: dflt: { /* pattern class plus optional suffix */481const char *ep = classend(ms, p); /* points to optional suffix */482/* does not match at least once? */483if (!singlematch(ms, s, p, ep)) {484if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */485p = ep + 1; goto init; /* return match(ms, s, ep + 1); */486}487else /* '+' or no suffix */488s = NULL; /* fail */489}490else { /* matched once */491switch (*ep) { /* handle optional suffix */492case '?': { /* optional */493const char *res;494if ((res = match(ms, s + 1, ep + 1)) != NULL)495s = res;496else {497p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */498}499break;500}501case '+': /* 1 or more repetitions */502s++; /* 1 match already done */503zfs_fallthrough;504case '*': /* 0 or more repetitions */505s = max_expand(ms, s, p, ep);506break;507case '-': /* 0 or more repetitions (minimum) */508s = min_expand(ms, s, p, ep);509break;510default: /* no suffix */511s++; p = ep; goto init; /* return match(ms, s + 1, ep); */512}513}514break;515}516}517}518ms->matchdepth++;519return s;520}521522523524static const char *lmemfind (const char *s1, size_t l1,525const char *s2, size_t l2) {526if (l2 == 0) return s1; /* empty strings are everywhere */527else if (l2 > l1) return NULL; /* avoids a negative `l1' */528else {529const char *init; /* to search for a `*s2' inside `s1' */530l2--; /* 1st char will be checked by `memchr' */531l1 = l1-l2; /* `s2' cannot be found after that */532while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {533init++; /* 1st char is already checked */534if (memcmp(init, s2+1, l2) == 0)535return init-1;536else { /* correct `l1' and `s1' to try again */537l1 -= init-s1;538s1 = init;539}540}541return NULL; /* not found */542}543}544545546static void push_onecapture (MatchState *ms, int i, const char *s,547const char *e) {548if (i >= ms->level) {549if (i == 0) /* ms->level == 0, too */550lua_pushlstring(ms->L, s, e - s); /* add whole match */551else552luaL_error(ms->L, "invalid capture index");553}554else {555ptrdiff_t l = ms->capture[i].len;556if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");557if (l == CAP_POSITION)558lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);559else560lua_pushlstring(ms->L, ms->capture[i].init, l);561}562}563564565static int push_captures (MatchState *ms, const char *s, const char *e) {566int i;567int nlevels = (ms->level == 0 && s) ? 1 : ms->level;568luaL_checkstack(ms->L, nlevels, "too many captures");569for (i = 0; i < nlevels; i++)570push_onecapture(ms, i, s, e);571return nlevels; /* number of strings pushed */572}573574575/* check whether pattern has no special characters */576static int nospecials (const char *p, size_t l) {577size_t upto = 0;578do {579if (strpbrk(p + upto, SPECIALS))580return 0; /* pattern has a special character */581upto += strlen(p + upto) + 1; /* may have more after \0 */582} while (upto <= l);583return 1; /* no special chars found */584}585586587static int str_find_aux (lua_State *L, int find) {588size_t ls, lp;589const char *s = luaL_checklstring(L, 1, &ls);590const char *p = luaL_checklstring(L, 2, &lp);591size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);592if (init < 1) init = 1;593else if (init > ls + 1) { /* start after string's end? */594lua_pushnil(L); /* cannot find anything */595return 1;596}597/* explicit request or no special characters? */598if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {599/* do a plain search */600const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);601if (s2) {602lua_pushinteger(L, s2 - s + 1);603lua_pushinteger(L, s2 - s + lp);604return 2;605}606}607else {608MatchState ms;609const char *s1 = s + init - 1;610int anchor = (*p == '^');611if (anchor) {612p++; lp--; /* skip anchor character */613}614ms.L = L;615ms.matchdepth = MAXCCALLS;616ms.src_init = s;617ms.src_end = s + ls;618ms.p_end = p + lp;619do {620const char *res;621ms.level = 0;622lua_assert(ms.matchdepth == MAXCCALLS);623if ((res=match(&ms, s1, p)) != NULL) {624if (find) {625lua_pushinteger(L, s1 - s + 1); /* start */626lua_pushinteger(L, res - s); /* end */627return push_captures(&ms, NULL, 0) + 2;628}629else630return push_captures(&ms, s1, res);631}632} while (s1++ < ms.src_end && !anchor);633}634lua_pushnil(L); /* not found */635return 1;636}637638639static int str_find (lua_State *L) {640return str_find_aux(L, 1);641}642643644static int str_match (lua_State *L) {645return str_find_aux(L, 0);646}647648649static int gmatch_aux (lua_State *L) {650MatchState ms;651size_t ls, lp;652const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);653const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);654const char *src;655ms.L = L;656ms.matchdepth = MAXCCALLS;657ms.src_init = s;658ms.src_end = s+ls;659ms.p_end = p + lp;660for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));661src <= ms.src_end;662src++) {663const char *e;664ms.level = 0;665lua_assert(ms.matchdepth == MAXCCALLS);666if ((e = match(&ms, src, p)) != NULL) {667lua_Integer newstart = e-s;668if (e == src) newstart++; /* empty match? go at least one position */669lua_pushinteger(L, newstart);670lua_replace(L, lua_upvalueindex(3));671return push_captures(&ms, src, e);672}673}674return 0; /* not found */675}676677678static int str_gmatch (lua_State *L) {679luaL_checkstring(L, 1);680luaL_checkstring(L, 2);681lua_settop(L, 2);682lua_pushinteger(L, 0);683lua_pushcclosure(L, gmatch_aux, 3);684return 1;685}686687688static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,689const char *e) {690size_t l, i;691const char *news = lua_tolstring(ms->L, 3, &l);692for (i = 0; i < l; i++) {693if (news[i] != L_ESC)694luaL_addchar(b, news[i]);695else {696i++; /* skip ESC */697if (!isdigit(uchar(news[i]))) {698if (news[i] != L_ESC)699luaL_error(ms->L, "invalid use of " LUA_QL("%c")700" in replacement string", L_ESC);701luaL_addchar(b, news[i]);702}703else if (news[i] == '0')704luaL_addlstring(b, s, e - s);705else {706push_onecapture(ms, news[i] - '1', s, e);707luaL_addvalue(b); /* add capture to accumulated result */708}709}710}711}712713714static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,715const char *e, int tr) {716lua_State *L = ms->L;717switch (tr) {718case LUA_TFUNCTION: {719int n;720lua_pushvalue(L, 3);721n = push_captures(ms, s, e);722lua_call(L, n, 1);723break;724}725case LUA_TTABLE: {726push_onecapture(ms, 0, s, e);727lua_gettable(L, 3);728break;729}730default: { /* LUA_TNUMBER or LUA_TSTRING */731add_s(ms, b, s, e);732return;733}734}735if (!lua_toboolean(L, -1)) { /* nil or false? */736lua_pop(L, 1);737lua_pushlstring(L, s, e - s); /* keep original text */738}739else if (!lua_isstring(L, -1))740luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));741luaL_addvalue(b); /* add result to accumulator */742}743744745static int str_gsub (lua_State *L) {746size_t srcl, lp;747const char *src = luaL_checklstring(L, 1, &srcl);748const char *p = luaL_checklstring(L, 2, &lp);749int tr = lua_type(L, 3);750size_t max_s = luaL_optinteger(L, 4, srcl+1);751int anchor = (*p == '^');752size_t n = 0;753MatchState ms;754luaL_Buffer b;755luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||756tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,757"string/function/table expected");758luaL_buffinit(L, &b);759if (anchor) {760p++; lp--; /* skip anchor character */761}762ms.L = L;763ms.matchdepth = MAXCCALLS;764ms.src_init = src;765ms.src_end = src+srcl;766ms.p_end = p + lp;767while (n < max_s) {768const char *e;769ms.level = 0;770lua_assert(ms.matchdepth == MAXCCALLS);771e = match(&ms, src, p);772if (e) {773n++;774add_value(&ms, &b, src, e, tr);775}776if (e && e>src) /* non empty match? */777src = e; /* skip it */778else if (src < ms.src_end)779luaL_addchar(&b, *src++);780else break;781if (anchor) break;782}783luaL_addlstring(&b, src, ms.src_end-src);784luaL_pushresult(&b);785lua_pushinteger(L, n); /* number of substitutions */786return 2;787}788789/* }====================================================== */790791792793/*794** {======================================================795** STRING FORMAT796** =======================================================797*/798799/*800** LUA_INTFRMLEN is the length modifier for integer conversions in801** 'string.format'; LUA_INTFRM_T is the integer type corresponding to802** the previous length803*/804#if !defined(LUA_INTFRMLEN) /* { */805#if defined(LUA_USE_LONGLONG)806807#define LUA_INTFRMLEN "ll"808#define LUA_INTFRM_T long long809810#else811812#define LUA_INTFRMLEN "l"813#define LUA_INTFRM_T long814815#endif816#endif /* } */817818819/*820** LUA_FLTFRMLEN is the length modifier for float conversions in821** 'string.format'; LUA_FLTFRM_T is the float type corresponding to822** the previous length823*/824#if !defined(LUA_FLTFRMLEN)825826#define LUA_FLTFRMLEN ""827#define LUA_FLTFRM_T double828829#endif830831832/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */833#define MAX_ITEM 512834/* valid flags in a format specification */835#define FLAGS "-+ #0"836/*837** maximum size of each format specification (such as '%-099.99d')838** (+10 accounts for %99.99x plus margin of error)839*/840#define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)841842843static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {844size_t l;845const char *s = luaL_checklstring(L, arg, &l);846luaL_addchar(b, '"');847while (l--) {848if (*s == '"' || *s == '\\' || *s == '\n') {849luaL_addchar(b, '\\');850luaL_addchar(b, *s);851}852else if (*s == '\0' || iscntrl(uchar(*s))) {853char buff[10];854if (!isdigit(uchar(*(s+1))))855snprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));856else857snprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));858luaL_addstring(b, buff);859}860else861luaL_addchar(b, *s);862s++;863}864luaL_addchar(b, '"');865}866867static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {868const char *p = strfrmt;869while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */870if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))871luaL_error(L, "invalid format (repeated flags)");872if (isdigit(uchar(*p))) p++; /* skip width */873if (isdigit(uchar(*p))) p++; /* (2 digits at most) */874if (*p == '.') {875p++;876if (isdigit(uchar(*p))) p++; /* skip precision */877if (isdigit(uchar(*p))) p++; /* (2 digits at most) */878}879if (isdigit(uchar(*p)))880luaL_error(L, "invalid format (width or precision too long)");881*(form++) = '%';882memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));883form += p - strfrmt + 1;884*form = '\0';885return p;886}887888889/*890** add length modifier into formats891*/892static void addlenmod (char *form, const char *lenmod, size_t size) {893size_t l = strlen(form);894size_t lm = strlen(lenmod);895char spec = form[l - 1];896strlcpy(form + l - 1, lenmod, size - (l - 1));897form[l + lm - 1] = spec;898form[l + lm] = '\0';899}900901902static int str_format (lua_State *L) {903int top = lua_gettop(L);904int arg = 1;905size_t sfl;906const char *strfrmt = luaL_checklstring(L, arg, &sfl);907const char *strfrmt_end = strfrmt+sfl;908luaL_Buffer b;909luaL_buffinit(L, &b);910while (strfrmt < strfrmt_end) {911if (*strfrmt != L_ESC)912luaL_addchar(&b, *strfrmt++);913else if (*++strfrmt == L_ESC)914luaL_addchar(&b, *strfrmt++); /* %% */915else { /* format item */916char form[MAX_FORMAT]; /* to store the format (`%...') */917char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */918int nb = 0; /* number of bytes in added item */919if (++arg > top)920luaL_argerror(L, arg, "no value");921strfrmt = scanformat(L, strfrmt, form);922switch (*strfrmt++) {923case 'c': {924nb = str_sprintf(buff, form, luaL_checkint(L, arg));925break;926}927case 'd': case 'i': {928lua_Number n = luaL_checknumber(L, arg);929LUA_INTFRM_T ni = (LUA_INTFRM_T)n;930lua_Number diff = n - (lua_Number)ni;931luaL_argcheck(L, -1 < diff && diff < 1, arg,932"not a number in proper range");933addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);934nb = str_sprintf(buff, form, ni);935break;936}937case 'o': case 'u': case 'x': case 'X': {938lua_Number n = luaL_checknumber(L, arg);939unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;940lua_Number diff = n - (lua_Number)ni;941luaL_argcheck(L, -1 < diff && diff < 1, arg,942"not a non-negative number in proper range");943addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);944nb = str_sprintf(buff, form, ni);945break;946}947#if defined(LUA_USE_FLOAT_FORMATS)948case 'e': case 'E': case 'f':949#if defined(LUA_USE_AFORMAT)950case 'a': case 'A':951#endif952case 'g': case 'G': {953addlenmod(form, LUA_FLTFRMLEN, MAX_FORMAT);954nb = str_sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));955break;956}957#endif958case 'q': {959addquoted(L, &b, arg);960break;961}962case 's': {963size_t l;964const char *s = luaL_tolstring(L, arg, &l);965if (!strchr(form, '.') && l >= 100) {966/* no precision and string is too long to be formatted;967keep original string */968luaL_addvalue(&b);969break;970}971else {972nb = str_sprintf(buff, form, s);973lua_pop(L, 1); /* remove result from 'luaL_tolstring' */974break;975}976}977default: { /* also treat cases `pnLlh' */978return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "979LUA_QL("format"), *(strfrmt - 1));980}981}982luaL_addsize(&b, nb);983}984}985luaL_pushresult(&b);986return 1;987}988989/* }====================================================== */990991992static const luaL_Reg strlib[] = {993{"byte", str_byte},994{"char", str_char},995#if defined(LUA_USE_DUMP)996{"dump", str_dump},997#endif998{"find", str_find},999{"format", str_format},1000{"gmatch", str_gmatch},1001{"gsub", str_gsub},1002{"len", str_len},1003{"lower", str_lower},1004{"match", str_match},1005{"rep", str_rep},1006{"reverse", str_reverse},1007{"sub", str_sub},1008{"upper", str_upper},1009{NULL, NULL}1010};101110121013static void createmetatable (lua_State *L) {1014lua_createtable(L, 0, 1); /* table to be metatable for strings */1015lua_pushliteral(L, ""); /* dummy string */1016lua_pushvalue(L, -2); /* copy table */1017lua_setmetatable(L, -2); /* set table as metatable for strings */1018lua_pop(L, 1); /* pop dummy string */1019lua_pushvalue(L, -2); /* get string library */1020lua_setfield(L, -2, "__index"); /* metatable.__index = string */1021lua_pop(L, 1); /* pop metatable */1022}102310241025/*1026** Open string library1027*/1028LUAMOD_API int luaopen_string (lua_State *L) {1029luaL_newlib(L, strlib);1030createmetatable(L);1031return 1;1032}10331034#if defined(_KERNEL)10351036EXPORT_SYMBOL(luaopen_string);10371038#endif103910401041