Revising code for Varint encoding in dumps

- Usign lua_Unsigned to count strings.
- Varint uses a type large enough both for size_t and lua_Unsigned.
- Most-Significant Bit 0 means last byte, to conform to common usage.
- (unrelated) Change in macro 'getaddr' so that multiplication is
  by constants.
This commit is contained in:
Roberto Ierusalimschy
2024-02-12 15:16:11 -03:00
parent 7360f8d0fd
commit c8121ce34b
3 changed files with 45 additions and 29 deletions

View File

@@ -37,7 +37,7 @@ typedef struct {
const char *name;
Table *h; /* list for string reuse */
size_t offset; /* current position relative to beginning of dump */
lua_Integer nstr; /* number of strings in the list */
lua_Unsigned nstr; /* number of strings in the list */
lu_byte fixed; /* dump is fixed in memory */
} LoadState;
@@ -71,10 +71,9 @@ static void loadAlign (LoadState *S, int align) {
}
#define getaddr(S,n,t) cast(t *, getaddr_(S,n,sizeof(t)))
#define getaddr(S,n,t) cast(t *, getaddr_(S,(n) * sizeof(t)))
static const void *getaddr_ (LoadState *S, int n, size_t sz) {
size_t size = n * sz;
static const void *getaddr_ (LoadState *S, size_t size) {
const void *block = luaZ_getaddr(S->Z, size);
S->offset += size;
if (block == NULL)
@@ -95,8 +94,8 @@ static lu_byte loadByte (LoadState *S) {
}
static size_t loadUnsigned (LoadState *S, size_t limit) {
size_t x = 0;
static varint_t loadVarint (LoadState *S, varint_t limit) {
varint_t x = 0;
int b;
limit >>= 7;
do {
@@ -104,18 +103,18 @@ static size_t loadUnsigned (LoadState *S, size_t limit) {
if (x >= limit)
error(S, "integer overflow");
x = (x << 7) | (b & 0x7f);
} while ((b & 0x80) == 0);
} while ((b & 0x80) != 0);
return x;
}
static size_t loadSize (LoadState *S) {
return loadUnsigned(S, MAX_SIZET);
return cast_sizet(loadVarint(S, MAX_SIZET));
}
static int loadInt (LoadState *S) {
return cast_int(loadUnsigned(S, INT_MAX));
return cast_int(loadVarint(S, INT_MAX));
}
@@ -149,9 +148,10 @@ static void loadString (LoadState *S, Proto *p, TString **sl) {
return;
}
else if (size == 1) { /* previously saved string? */
int idx = loadInt(S); /* get its index */
/* get its index */
lua_Unsigned idx = cast(lua_Unsigned, loadVarint(S, LUA_MAXUNSIGNED));
TValue stv;
luaH_getint(S->h, idx, &stv);
luaH_getint(S->h, l_castU2S(idx), &stv); /* get its value */
*sl = ts = tsvalue(&stv);
luaC_objbarrier(L, p, ts);
return; /* do not save it again */
@@ -175,7 +175,7 @@ static void loadString (LoadState *S, Proto *p, TString **sl) {
/* add string to list of saved strings */
S->nstr++;
setsvalue(L, &sv, ts);
luaH_setint(L, S->h, S->nstr, &sv);
luaH_setint(L, S->h, l_castU2S(S->nstr), &sv);
luaC_objbarrierback(L, obj2gco(S->h), ts);
}