Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/lua/blob/master/lobject.c # lua [Ported from github.com/lua/lua] Cast in 'rl_readline_name' Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `lua / lobject.c` 719 lines ยท 24113 bytes Raw Blame History 1 /* 2 ** $Id: lobject.c $ 3 ** Some generic functions over Lua objects 4 ** See Copyright Notice in lua.h 5 */ 6 7 #define lobject_c 8 #define LUA_CORE 9 10 #include "lprefix.h" 11 12 13 #include 14 #include 15 #include 16 #include 17 #include 18 #include 19 #include 20 21 #include "lua.h" 22 23 #include "lctype.h" 24 #include "ldebug.h" 25 #include "ldo.h" 26 #include "lmem.h" 27 #include "lobject.h" 28 #include "lstate.h" 29 #include "lstring.h" 30 #include "lvm.h" 31 32 33 /* 34 ** Computes ceil(log2(x)), which is the smallest integer n such that 35 ** x <= (1 << n). 36 */ 37 lu_byte luaO_ceillog2 (unsigned int x) { 38 static const lu_byte log_2[256] = { /* log_2[i - 1] = ceil(log2(i)) */ 39 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 40 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 41 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 42 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 43 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 44 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 45 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 46 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 47 }; 48 int l = 0; 49 x--; 50 while (x >= 256) { l += 8; x >>= 8; } 51 return cast_byte(l + log_2[x]); 52 } 53 54 /* 55 ** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx). 56 ** The exponent is represented using excess-7. Mimicking IEEE 754, the 57 ** representation normalizes the number when possible, assuming an extra 58 ** 1 before the mantissa (xxxx) and adding one to the exponent (eeee) 59 ** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if 60 ** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers). 61 */ 62 lu_byte luaO_codeparam (unsigned int p) { 63 if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u) /* overflow? */ 64 return 0xFF; /* return maximum value */ 65 else { 66 p = (cast(l_uint32, p) * 128 + 99) / 100; /* round up the division */ 67 if (p < 0x10) { /* subnormal number? */ 68 /* exponent bits are already zero; nothing else to do */ 69 return cast_byte(p); 70 } 71 else { /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */ 72 /* preserve 5 bits in 'p' */ 73 unsigned log = luaO_ceillog2(p + 1) - 5u; 74 return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4)); 75 } 76 } 77 } 78 79 80 /* 81 ** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly, 82 ** we have to multiply 'x' by the mantissa and then shift accordingly to 83 ** the exponent. If the exponent is positive, both the multiplication 84 ** and the shift increase 'x', so we have to care only about overflows. 85 ** For negative exponents, however, multiplying before the shift keeps 86 ** more significant bits, as long as the multiplication does not 87 ** overflow, so we check which order is best. 88 */ 89 l_mem luaO_applyparam (lu_byte p, l_mem x) { 90 int m = p & 0xF; /* mantissa */ 91 int e = (p >> 4); /* exponent */ 92 lua_assert(x >= 0); 93 if (e > 0) { /* normalized? */ 94 e--; /* correct exponent */ 95 m += 0x10; /* correct mantissa; maximum value is 0x1F */ 96 } 97 e -= 7; /* correct excess-7 */ 98 if (e >= 0) { 99 if (x < (MAX_LMEM / 0x1F) >> e) /* no overflow? */ 100 return (x * m) << e; /* order doesn't matter here */ 101 else /* real overflow */ 102 return MAX_LMEM; 103 } 104 else { /* negative exponent */ 105 e = -e; 106 if (x < MAX_LMEM / 0x1F) /* multiplication cannot overflow? */ 107 return (x * m) >> e; /* multiplying first gives more precision */ 108 else if ((x >> e) < MAX_LMEM / 0x1F) /* cannot overflow after shift? */ 109 return (x >> e) * m; 110 else /* real overflow */ 111 return MAX_LMEM; 112 } 113 } 114 115 116 static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, 117 lua_Integer v2) { 118 switch (op) { 119 case LUA_OPADD: return intop(+, v1, v2); 120 case LUA_OPSUB:return intop(-, v1, v2); 121 case LUA_OPMUL:return intop(*, v1, v2); 122 case LUA_OPMOD: return luaV_mod(L, v1, v2); 123 case LUA_OPIDIV: return luaV_idiv(L, v1, v2); 124 case LUA_OPBAND: return intop(&, v1, v2); 125 case LUA_OPBOR: return intop(|, v1, v2); 126 case LUA_OPBXOR: return intop(^, v1, v2); 127 case LUA_OPSHL: return luaV_shiftl(v1, v2); 128 case LUA_OPSHR: return luaV_shiftr(v1, v2); 129 case LUA_OPUNM: return intop(-, 0, v1); 130 case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1); 131 default: lua_assert(0); return 0; 132 } 133 } 134 135 136 static lua_Number numarith (lua_State *L, int op, lua_Number v1, 137 lua_Number v2) { 138 switch (op) { 139 case LUA_OPADD: return luai_numadd(L, v1, v2); 140 case LUA_OPSUB: return luai_numsub(L, v1, v2); 141 case LUA_OPMUL: return luai_nummul(L, v1, v2); 142 case LUA_OPDIV: return luai_numdiv(L, v1, v2); 143 case LUA_OPPOW: return luai_numpow(L, v1, v2); 144 case LUA_OPIDIV: return luai_numidiv(L, v1, v2); 145 case LUA_OPUNM: return luai_numunm(L, v1); 146 case LUA_OPMOD: return luaV_modf(L, v1, v2); 147 default: lua_assert(0); return 0; 148 } 149 } 150 151 152 int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2, 153 TValue *res) { 154 switch (op) { 155 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: 156 case LUA_OPSHL: case LUA_OPSHR: 157 case LUA_OPBNOT: { /* operate only on integers */ 158 lua_Integer i1; lua_Integer i2; 159 if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) { 160 setivalue(res, intarith(L, op, i1, i2)); 161 return 1; 162 } 163 else return 0; /* fail */ 164 } 165 case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */ 166 lua_Number n1; lua_Number n2; 167 if (tonumberns(p1, n1) && tonumberns(p2, n2)) { 168 setfltvalue(res, numarith(L, op, n1, n2)); 169 return 1; 170 } 171 else return 0; /* fail */ 172 } 173 default: { /* other operations */ 174 lua_Number n1; lua_Number n2; 175 if (ttisinteger(p1) && ttisinteger(p2)) { 176 setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2))); 177 return 1; 178 } 179 else if (tonumberns(p1, n1) && tonumberns(p2, n2)) { 180 setfltvalue(res, numarith(L, op, n1, n2)); 181 return 1; 182 } 183 else return 0; /* fail */ 184 } 185 } 186 } 187 188 189 void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, 190 StkId res) { 191 if (!luaO_rawarith(L, op, p1, p2, s2v(res))) { 192 /* could not perform raw operation; try metamethod */ 193 luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD)); 194 } 195 } 196 197 198 lu_byte luaO_hexavalue (int c) { 199 lua_assert(lisxdigit(c)); 200 if (lisdigit(c)) return cast_byte(c - '0'); 201 else return cast_byte((ltolower(c) - 'a') + 10); 202 } 203 204 205 static int isneg (const char **s) { 206 if (**s == '-') { (*s)++; return 1; } 207 else if (**s == '+') (*s)++; 208 return 0; 209 } 210 211 212 213 /* 214 ** {================================================================== 215 ** Lua's implementation for 'lua_strx2number' 216 ** =================================================================== 217 */ 218 219 #if !defined(lua_strx2number) 220 221 /* maximum number of significant digits to read (to avoid overflows 222 even with single floats) */ 223 #define MAXSIGDIG 30 224 225 /* 226 ** convert a hexadecimal numeric string to a number, following 227 ** C99 specification for 'strtod' 228 */ 229 static lua_Number lua_strx2number (const char *s, char **endptr) { 230 int dot = lua_getlocaledecpoint(); 231 lua_Number r = l_mathop(0.0); /* result (accumulator) */ 232 int sigdig = 0; /* number of significant digits */ 233 int nosigdig = 0; /* number of non-significant digits */ 234 int e = 0; /* exponent correction */ 235 int neg; /* 1 if number is negative */ 236 int hasdot = 0; /* true after seen a dot */ 237 *endptr = cast_charp(s); /* nothing is valid yet */ 238 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ 239 neg = isneg(&s); /* check sign */ 240 if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ 241 return l_mathop(0.0); /* invalid format (no '0x') */ 242 for (s += 2; ; s++) { /* skip '0x' and read numeral */ 243 if (*s == dot) { 244 if (hasdot) break; /* second dot? stop loop */ 245 else hasdot = 1; 246 } 247 else if (lisxdigit(cast_uchar(*s))) { 248 if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ 249 nosigdig++; 250 else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ 251 r = (r * l_mathop(16.0)) + luaO_hexavalue(*s); 252 else e++; /* too many digits; ignore, but still count for exponent */ 253 if (hasdot) e--; /* decimal digit? correct exponent */ 254 } 255 else break; /* neither a dot nor a digit */ 256 } 257 if (nosigdig + sigdig == 0) /* no digits? */ 258 return l_mathop(0.0); /* invalid format */ 259 *endptr = cast_charp(s); /* valid up to here */ 260 e *= 4; /* each digit multiplies/divides value by 2^4 */ 261 if (*s == 'p' || *s == 'P') { /* exponent part? */ 262 int exp1 = 0; /* exponent value */ 263 int neg1; /* exponent sign */ 264 s++; /* skip 'p' */ 265 neg1 = isneg(&s); /* sign */ 266 if (!lisdigit(cast_uchar(*s))) 267 return l_mathop(0.0); /* invalid; must have at least one digit */ 268 while (lisdigit(cast_uchar(*s))) /* read exponent */ 269 exp1 = exp1 * 10 + *(s++) - '0'; 270 if (neg1) exp1 = -exp1; 271 e += exp1; 272 *endptr = cast_charp(s); /* valid up to here */ 273 } 274 if (neg) r = -r; 275 return l_mathop(ldexp)(r, e); 276 } 277 278 #endif 279 /* }====================================================== */ 280 281 282 /* maximum length of a numeral to be converted to a number */ 283 #if !defined (L_MAXLENNUM) 284 #define L_MAXLENNUM 200 285 #endif 286 287 /* 288 ** Convert string 's' to a Lua number (put in 'result'). Return NULL on 289 ** fail or the address of the ending '\0' on success. ('mode' == 'x') 290 ** means a hexadecimal numeral. 291 */ 292 static const char *l_str2dloc (const char *s, lua_Number *result, int mode) { 293 char *endptr; 294 *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */ 295 : lua_str2number(s, &endptr); 296 if (endptr == s) return NULL; /* nothing recognized? */ 297 while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */ 298 return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */ 299 } 300 301 302 /* 303 ** Convert string 's' to a Lua number (put in 'result') handling the 304 ** current locale. 305 ** This function accepts both the current locale or a dot as the radix 306 ** mark. If the conversion fails, it may mean number has a dot but 307 ** locale accepts something else. In that case, the code copies 's' 308 ** to a buffer (because 's' is read-only), changes the dot to the 309 ** current locale radix mark, and tries to convert again. 310 ** The variable 'mode' checks for special characters in the string: 311 ** - 'n' means 'inf' or 'nan' (which should be rejected) 312 ** - 'x' means a hexadecimal numeral 313 ** - '.' just optimizes the search for the common case (no special chars) 314 */ 315 static const char *l_str2d (const char *s, lua_Number *result) { 316 const char *endptr; 317 const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */ 318 int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0; 319 if (mode == 'n') /* reject 'inf' and 'nan' */ 320 return NULL; 321 endptr = l_str2dloc(s, result, mode); /* try to convert */ 322 if (endptr == NULL) { /* failed? may be a different locale */ 323 char buff[L_MAXLENNUM + 1]; 324 const char *pdot = strchr(s, '.'); 325 if (pdot == NULL || strlen(s) > L_MAXLENNUM) 326 return NULL; /* string too long or no dot; fail */ 327 strcpy(buff, s); /* copy string to buffer */ 328 buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */ 329 endptr = l_str2dloc(buff, result, mode); /* try again */ 330 if (endptr != NULL) 331 endptr = s + (endptr - buff); /* make relative to 's' */ 332 } 333 return endptr; 334 } 335 336 337 #define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10) 338 #define MAXLASTD cast_int(LUA_MAXINTEGER % 10) 339 340 static const char *l_str2int (const char *s, lua_Integer *result) { 341 lua_Unsigned a = 0; 342 int empty = 1; 343 int neg; 344 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ 345 neg = isneg(&s); 346 if (s[0] == '0' && 347 (s[1] == 'x' || s[1] == 'X')) { /* hex? */ 348 s += 2; /* skip '0x' */ 349 for (; lisxdigit(cast_uchar(*s)); s++) { 350 a = a * 16 + luaO_hexavalue(*s); 351 empty = 0; 352 } 353 } 354 else { /* decimal */ 355 for (; lisdigit(cast_uchar(*s)); s++) { 356 int d = *s - '0'; 357 if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */ 358 return NULL; /* do not accept it (as integer) */ 359 a = a * 10 + cast_uint(d); 360 empty = 0; 361 } 362 } 363 while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */ 364 if (empty || *s != '\0') return NULL; /* something wrong in the numeral */ 365 else { 366 *result = l_castU2S((neg) ? 0u - a : a); 367 return s; 368 } 369 } 370 371 372 size_t luaO_str2num (const char *s, TValue *o) { 373 lua_Integer i; lua_Number n; 374 const char *e; 375 if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */ 376 setivalue(o, i); 377 } 378 else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */ 379 setfltvalue(o, n); 380 } 381 else 382 return 0; /* conversion failed */ 383 return ct_diff2sz(e - s) + 1; /* success; return string size */ 384 } 385 386 387 int luaO_utf8esc (char *buff, l_uint32 x) { 388 int n = 1; /* number of bytes put in buffer (backwards) */ 389 lua_assert(x <= 0x7FFFFFFFu); 390 if (x < 0x80) /* ASCII? */ 391 buff[UTF8BUFFSZ - 1] = cast_char(x); 392 else { /* need continuation bytes */ 393 unsigned int mfb = 0x3f; /* maximum that fits in first byte */ 394 do { /* add continuation bytes */ 395 buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f)); 396 x >>= 6; /* remove added bits */ 397 mfb >>= 1; /* now there is one less bit available in first byte */ 398 } while (x > mfb); /* still needs continuation byte? */ 399 buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */ 400 } 401 return n; 402 } 403 404 405 /* 406 ** The size of the buffer for the conversion of a number to a string 407 ** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT 408 ** and LUA_NUMBER_FMT. For a long long int, this is 19 digits plus a 409 ** sign and a final '\0', adding to 21. For a long double, it can go to 410 ** a sign, the dot, an exponent letter, an exponent sign, 4 exponent 411 ** digits, the final '\0', plus the significant digits, which are 412 ** approximately the *_DIG attribute. 413 */ 414 #if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG)) 415 #error "invalid value for LUA_N2SBUFFSZ" 416 #endif 417 418 419 /* 420 ** Convert a float to a string, adding it to a buffer. First try with 421 ** a not too large number of digits, to avoid noise (for instance, 422 ** 1.1 going to "1.`1000000000000001`"). If that lose precision, so 423 ** that reading the result back gives a different number, then do the 424 ** conversion again with extra precision. Moreover, if the numeral looks 425 ** like an integer (without a decimal point or an exponent), add ".0" to 426 ** its end. 427 */ 428 static int tostringbuffFloat (lua_Number n, char *buff) { 429 /* first conversion */ 430 int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT, 431 (LUAI_UACNUMBER)n); 432 lua_Number check = lua_str2number(buff, NULL); /* read it back */ 433 if (check != n) { /* not enough precision? */ 434 /* convert again with more precision */ 435 len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N, 436 (LUAI_UACNUMBER)n); 437 } 438 /* looks like an integer? */ 439 if (buff[strspn(buff, "-`0123456789`")] == '\0') { 440 buff[len++] = lua_getlocaledecpoint(); 441 buff[len++] = '0'; /* adds '.0' to result */ 442 } 443 return len; 444 } 445 446 447 /* 448 ** Convert a number object to a string, adding it to a buffer. 449 */ 450 unsigned luaO_tostringbuff (const TValue *obj, char *buff) { 451 int len; 452 lua_assert(ttisnumber(obj)); 453 if (ttisinteger(obj)) 454 len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj)); 455 else 456 len = tostringbuffFloat(fltvalue(obj), buff); 457 lua_assert(len < LUA_N2SBUFFSZ); 458 return cast_uint(len); 459 } 460 461 462 /* 463 ** Convert a number object to a Lua string, replacing the value at 'obj' 464 */ 465 void luaO_tostring (lua_State *L, TValue *obj) { 466 char buff[LUA_N2SBUFFSZ]; 467 unsigned len = luaO_tostringbuff(obj, buff); 468 setsvalue(L, obj, luaS_newlstr(L, buff, len)); 469 } 470 471 472 473 474 /* 475 ** {================================================================== 476 ** 'luaO_pushvfstring' 477 ** =================================================================== 478 */ 479 480 /* 481 ** Size for buffer space used by 'luaO_pushvfstring'. It should be 482 ** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages, 483 ** so that 'luaG_addinfo' can work directly on the static buffer. 484 */ 485 #define BUFVFS cast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95) 486 487 /* 488 ** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while 489 ** building result (memory error [1] or buffer overflow [2]). 490 */ 491 typedef struct BuffFS { 492 lua_State *L; 493 char *b; 494 size_t buffsize; 495 size_t blen; /* length of string in 'buff' */ 496 int err; 497 char space[BUFVFS]; /* initial buffer */ 498 } BuffFS; 499 500 501 static void initbuff (lua_State *L, BuffFS *buff) { 502 buff->L = L; 503 buff->b = buff->space; 504 buff->buffsize = sizeof(buff->space); 505 buff->blen = 0; 506 buff->err = 0; 507 } 508 509 510 /* 511 ** Push final result from 'luaO_pushvfstring'. This function may raise 512 ** errors explicitly or through memory errors, so it must run protected. 513 */ 514 static void pushbuff (lua_State *L, void *ud) { 515 BuffFS *buff = cast(BuffFS*, ud); 516 switch (buff->err) { 517 case 1: /* memory error */ 518 luaD_throw(L, LUA_ERRMEM); 519 break; 520 case 2: /* length overflow: Add "..." at the end of result */ 521 if (buff->buffsize - buff->blen < 3) 522 strcpy(buff->b + buff->blen - 3, "..."); /* 'blen' must be > 3 */ 523 else { /* there is enough space left for the "..." */ 524 strcpy(buff->b + buff->blen, "..."); 525 buff->blen += 3; 526 } 527 /* FALLTHROUGH */ 528 default: { /* no errors, but it can raise one creating the new string */ 529 TString *ts = luaS_newlstr(L, buff->b, buff->blen); 530 setsvalue2s(L, L->top.p, ts); 531 L->top.p++; 532 } 533 } 534 } 535 536 537 static const char *clearbuff (BuffFS *buff) { 538 lua_State *L = buff->L; 539 const char *res; 540 if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK) /* errors? */ 541 res = NULL; /* error message is on the top of the stack */ 542 else 543 res = getstr(tsvalue(s2v(L->top.p - 1))); 544 if (buff->b != buff->space) /* using dynamic buffer? */ 545 luaM_freearray(L, buff->b, buff->buffsize); /* free it */ 546 return res; 547 } 548 549 550 static void addstr2buff (BuffFS *buff, const char *str, size_t slen) { 551 size_t left = buff->buffsize - buff->blen; /* space left in the buffer */ 552 if (buff->err) /* do nothing else after an error */ 553 return; 554 if (slen > left) { /* new string doesn't fit into current buffer? */ 555 if (slen > ((MAX_SIZE/2) - buff->blen)) { /* overflow? */ 556 memcpy(buff->b + buff->blen, str, left); /* copy what it can */ 557 buff->blen = buff->buffsize; 558 buff->err = 2; /* doesn't add anything else */ 559 return; 560 } 561 else { 562 size_t newsize = buff->buffsize + slen; /* limited to MAX_SIZE/2 */ 563 char *newb = 564 (buff->b == buff->space) /* still using static space? */ 565 ? luaM_reallocvector(buff->L, NULL, 0, newsize, char) 566 : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize, 567 char); 568 if (newb == NULL) { /* allocation error? */ 569 buff->err = 1; /* signal a memory error */ 570 return; 571 } 572 if (buff->b == buff->space) /* new buffer (not reallocated)? */ 573 memcpy(newb, buff->b, buff->blen); /* copy previous content */ 574 buff->b = newb; /* set new (larger) buffer... */ 575 buff->buffsize = newsize; /* ...and its new size */ 576 } 577 } 578 memcpy(buff->b + buff->blen, str, slen); /* copy new content */ 579 buff->blen += slen; 580 } 581 582 583 /* 584 ** Add a numeral to the buffer. 585 */ 586 static void addnum2buff (BuffFS *buff, TValue *num) { 587 char numbuff[LUA_N2SBUFFSZ]; 588 unsigned len = luaO_tostringbuff(num, numbuff); 589 addstr2buff(buff, numbuff, len); 590 } 591 592 593 /* 594 ** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%' 595 conventional formats, plus Lua-specific '%I' and '%U' 596 */ 597 const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { 598 BuffFS buff; /* holds last part of the result */ 599 const char *e; /* points to next '%' */ 600 initbuff(L, &buff); 601 while ((e = strchr(fmt, '%')) != NULL) { 602 addstr2buff(&buff, fmt, ct_diff2sz(e - fmt)); /* add 'fmt' up to '%' */ 603 switch (*(e + 1)) { /* conversion specifier */ 604 case 's': { /* zero-terminated string */ 605 const char *s = va_arg(argp, char *); 606 if (s == NULL) s = "(null)"; 607 addstr2buff(&buff, s, strlen(s)); 608 break; 609 } 610 case 'c': { /* an 'int' as a character */ 611 char c = cast_char(va_arg(argp, int)); 612 addstr2buff(&buff, &c, sizeof(char)); 613 break; 614 } 615 case 'd': { /* an 'int' */ 616 TValue num; 617 setivalue(&num, va_arg(argp, int)); 618 addnum2buff(&buff, &num); 619 break; 620 } 621 case 'I': { /* a 'lua_Integer' */ 622 TValue num; 623 setivalue(&num, cast_Integer(va_arg(argp, l_uacInt))); 624 addnum2buff(&buff, &num); 625 break; 626 } 627 case 'f': { /* a 'lua_Number' */ 628 TValue num; 629 setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber))); 630 addnum2buff(&buff, &num); 631 break; 632 } 633 case 'p': { /* a pointer */ 634 char bf[LUA_N2SBUFFSZ]; /* enough space for '%p' */ 635 void *p = va_arg(argp, void *); 636 int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p); 637 addstr2buff(&buff, bf, cast_uint(len)); 638 break; 639 } 640 case 'U': { /* an 'unsigned long' as a UTF-8 sequence */ 641 char bf[UTF8BUFFSZ]; 642 unsigned long arg = va_arg(argp, unsigned long); 643 int len = luaO_utf8esc(bf, cast(l_uint32, arg)); 644 addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len)); 645 break; 646 } 647 case '%': { 648 addstr2buff(&buff, "%", 1); 649 break; 650 } 651 default: { 652 addstr2buff(&buff, e, 2); /* keep unknown format in the result */ 653 break; 654 } 655 } 656 fmt = e + 2; /* skip '%' and the specifier */ 657 } 658 addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */ 659 return clearbuff(&buff); /* empty buffer into a new string */ 660 } 661 662 663 const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { 664 const char *msg; 665 va_list argp; 666 va_start(argp, fmt); 667 msg = luaO_pushvfstring(L, fmt, argp); 668 va_end(argp); 669 if (msg == NULL) /* error? */ 670 luaD_throw(L, LUA_ERRMEM); 671 return msg; 672 } 673 674 /* }================================================================== */ 675 676 677 #define RETS "..." 678 #define PRE "[string \"" 679 #define POS "\"]" 680 681 #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) 682 683 void luaO_chunkid (char *out, const char *source, size_t srclen) { 684 size_t bufflen = LUA_IDSIZE; /* free space in buffer */ 685 if (*source == '=') { /* 'literal' source */ 686 if (srclen <= bufflen) /* small enough? */ 687 memcpy(out, source + 1, srclen * sizeof(char)); 688 else { /* truncate it */ 689 addstr(out, source + 1, bufflen - 1); 690 *out = '\0'; 691 } 692 } 693 else if (*source == '@') { /* file name */ 694 if (srclen <= bufflen) /* small enough? */ 695 memcpy(out, source + 1, srclen * sizeof(char)); 696 else { /* add '...' before rest of name */ 697 addstr(out, RETS, LL(RETS)); 698 bufflen -= LL(RETS); 699 memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char)); 700 } 701 } 702 else { /* string; format as [string "source"] */ 703 const char *nl = strchr(source, '\n'); /* find first new line (if any) */ 704 addstr(out, PRE, LL(PRE)); /* add prefix */ 705 bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ 706 if (srclen < bufflen && nl == NULL) { /* small one-line source? */ 707 addstr(out, source, srclen); /* keep it */ 708 } 709 else { 710 if (nl != NULL) 711 srclen = ct_diff2sz(nl - source); /* stop at first newline */ 712 if (srclen > bufflen) srclen = bufflen; 713 addstr(out, source, srclen); 714 addstr(out, RETS, LL(RETS)); 715 } 716 memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); 717 } 718 } 719