From 1d8e000f00cf6c30ec5573f16bb980b7ae753058 Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Fri, 17 Mar 2017 13:53:43 +0100 Subject: string.pack --- src/lstrlib.js | 255 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 255 insertions(+) (limited to 'src/lstrlib.js') diff --git a/src/lstrlib.js b/src/lstrlib.js index 02feff6..89d1f7f 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -12,6 +12,10 @@ const CT = lua.constant_types; const L_ESC = '%'.charCodeAt(0); +// (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX)) +const MAXSIZE = Number.MAX_SAFE_INTEGER; + + /* translate a relative string position: negative means back from end */ const posrelat = function(pos, len) { if (pos >= 0) return pos; @@ -350,6 +354,256 @@ const str_format = function(L) { return 1; }; +/* value used for padding */ +const LUAL_PACKPADBYTE = 0x00; + +/* maximum size for the binary representation of an integer */ +const MAXINTSIZE = 16; + +const SZINT = 8; // Size of lua_Integer + +/* number of bits in a character */ +const NB = 8; + +/* mask for one character (NB 1's) */ +const MC = ((1 << NB) - 1) + +/* +** information to pack/unpack stuff +*/ +class Header { + constructor(L) { + this.L = L; + this.islittle = true; + this.maxalign = 1; + } +} + +/* +** options for pack/unpack +*/ +const KOption = { + Kint: 0, /* signed integers */ + Kuint: 1, /* unsigned integers */ + Kfloat: 2, /* floating-point numbers */ + Kchar: 3, /* fixed-length strings */ + Kstring: 4, /* strings with prefixed length */ + Kzstr: 5, /* zero-terminated strings */ + Kpadding: 6, /* padding */ + Kpaddalign: 7, /* padding for alignment */ + Knop: 8 /* no-op (configuration or spaces) */ +}; + +const digit = function(c) { + return '0'.charCodeAt(0) <= c && c <= '9'.charCodeAt(0); +}; + +const getnum = function(fmt, df) { + if (!digit(fmt)) /* no number? */ + return df; /* return default value */ + else { + let a = 0; + do { + a = a * 10 + ((fmt = fmt.slice(1))[0] - '0'.charCodeAt(0)); + } while (digit(fmt[0]) && a <= (MAXSIZE - 9)/10); + return a; + } +}; + +/* +** Read an integer numeral and raises an error if it is larger +** than the maximum size for integers. +*/ +const getnumlimit = function(h, fmt, df) { + let sz = getnum(fmt, df); + if (sz > MAXINTSIZE || sz <= 0) + lauxlib.luaL_error(h.L, `integral size (${sz}) out of limits [1,${MAXINTSIZE}]`); + return sz; +}; + +/* +** Read and classify next option. 'size' is filled with option's size. +*/ +const getoption = function(h, fmt) { + let r = { + opt: NaN, + size: NaN + }; + + r.opt = (fmt = fmt.slice(1))[0]; + r.size = 0; /* default */ + switch (r.opt) { + case 'b': r.size = 1; r.opt = KOption.Kint; return r; // sizeof(char): 1 + case 'B': r.size = 1; r.opt = KOption.Kuint; return r; + case 'h': r.size = 2; r.opt = KOption.Kint; return r; // sizeof(short): 2 + case 'H': r.size = 2; r.opt = KOption.Kuint; return r; + case 'l': r.size = 8; r.opt = KOption.Kint; return r; // sizeof(long): 8 + case 'L': r.size = 8; r.opt = KOption.Kuint; return r; + case 'j': r.size = 8; r.opt = KOption.Kint; return r; // sizeof(lua_Integer): 8 + case 'J': r.size = 8; r.opt = KOption.Kuint; return r; + case 'T': r.size = 8; r.opt = KOption.Kuint; return r; // sizeof(size_t): 8 + case 'f': r.size = 4; r.opt = KOption.Kfloat; return r; // sizeof(float): 4 + case 'd': r.size = 8; r.opt = KOption.Kfloat; return r; // sizeof(double): 8 + case 'n': r.size = 8; r.opt = KOption.Kfloat; return r; // sizeof(lua_Number): 8 + case 'i': r.size = getnumlimit(h, fmt, 4); r.opt = KOption.Kint; return r; // sizeof(int): 4 + case 'I': r.size = getnumlimit(h, fmt, 4); r.opt = KOption.Kuint; return r; + case 's': r.size = getnumlimit(h, fmt, 8); r.opt = KOption.Kstring; return r; + } + + r.opt = KOption.Knop; + return r; +}; + +/* +** Read, classify, and fill other details about the next option. +** 'psize' is filled with option's size, 'notoalign' with its +** alignment requirements. +** Local variable 'size' gets the size to be aligned. (Kpadal option +** always gets its full alignment, other options are limited by +** the maximum alignment ('maxalign'). Kchar option needs no alignment +** despite its size. +*/ +const getdetails = function(h, totalsize, fmt) { + let r = { + opt: NaN, + size: NaN, + ntoalign: NaN + }; + + let opt = getoption(h, fmt); + r.size = opt.size; + r.opt = opt.opt; + let align = r.size; /* usually, alignment follows size */ + if (opt === KOption.Kpaddalign) { /* 'X' gets alignment from following option */ + if (fmt[0] === 0) + lauxlib.luaL_argerror(h.L, 1, "invalid next option for option 'X'"); + else { + let o = getoption(h, fmt); + align = o.size; + o = o.opt; + if (o === KOption.Kchar || align === 0) + lauxlib.luaL_argerror(h.L, 1, "invalid next option for option 'X'"); + } + } + if (align <= 1 || opt === KOption.Kchar) /* need no alignment? */ + r.ntoalign = 0; + else { + if (align > h.maxalign) /* enforce maximum alignment */ + align = h.maxalign; + if ((align & (align -1)) !== 0) /* is 'align' not a power of 2? */ + lauxlib.luaL_argerror(h.L, 1, "format asks for alignment not power of 2"); + r.ntoalign = (align - (totalsize & (align - 1))) & (align - 1); + } + return r; +}; + +/* +** Pack integer 'n' with 'size' bytes and 'islittle' endianness. +** The final 'if' handles the case when 'size' is larger than +** the size of a Lua integer, correcting the extra sign-extension +** bytes if necessary (by default they would be zeros). +*/ +const packint = function(b, n, islittle, size, neg) { + let buff = new Array(size); + + buff[islittle ? 0 : size - 1] = n & MC; /* first byte */ + for (let i = 1; i < size; i++) { + n >>= NB; + buff[islittle ? i : size - 1 - i] = n & MC; + } + if (neg && size > SZINT) { /* negative number need sign extension? */ + for (let i = SZINT; i < size; i++) /* correct extra bytes */ + buff[islittle ? i : size - 1 - i] = MC; + } + b.concat(buff); /* add result to buffer */ +}; + +const packnum = function(b, n, islittle, size) { + let dv = new DataView(new ArrayBuffer(size)); + dv.setFloat64(0, n, islittle); + + for (let i = 0; i < 8; i++) + b.push(dv.getUint8(i, islittle)); +}; + +const str_pack = function(L) { + let b = []; + let h = new Header(); + let fmt = lauxlib.luaL_checkstring(L, 1); /* format string */ + let arg = 1; /* current argument to pack */ + let totalsize = 0; /* accumulate total size of result */ + lapi.lua_pushnil(L); /* mark to separate arguments from string buffer */ + while (fmt.length > 0) { + let details = getdetails(h, totalsize, fmt); + let opt = details.opt; + let size = details.size; + let ntoalign = details.ntoalign; + totalsize += ntoalign + size; + while (ntoalign-- > 0) + b.push(LUAL_PACKPADBYTE); /* fill alignment */ + arg++; + switch (opt) { + case KOption.Kint: { /* signed integers */ + let n = lauxlib.luaL_checkinteger(L, arg); + if (size < SZINT) { /* need overflow check? */ + let lim = 1 << (size * 8) - 1; + lauxlib.luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); + } + packint(b, n, h.islittle, size, n < 0); + break; + } + case KOption.Kuint: { /* unsigned integers */ + let n = lauxlib.luaL_checkinteger(L, arg); + if (size < SZINT) + lauxlib.luaL_argcheck(L, n < (1 << (size * NB)), arg, "unsigned overflow"); + packint(b, n, h.islittle, size, false); + break; + } + case KOption.Kfloat: { /* floating-point options */ + let n = lauxlib.luaL_checknumber(L, arg); /* get argument */ + packnum(b, n, h.islittle, size); + break; + } + case KOption.Kchar: { /* fixed-size string */ + let s = lauxlib.luaL_checkstring(L, arg); + s = L.stack[lapi.index2addr_(L, arg)].value; + let len = s.value.length; + lauxlib.luaL_argcheck(L, len <= size, arg, "string long than given size"); + b.concat(s.value); /* add string */ + while (len++ < size) /* pad extra space */ + b.push(LUAL_PACKPADBYTE); + break; + } + case KOption.Kstring: { /* strings with length count */ + let s = lauxlib.luaL_checkstring(L, arg); + s = L.stack[lapi.index2addr_(L, arg)].value; + let len = s.value.length; + lauxlib.luaL_argcheck(L, size >= NB || len < (1 << size * NB), arg, "string length does not fit in given size"); + packint(b, len, h.islittle, size, 0); /* pack length */ + b.concat(s.value); + totalsize += len; + break; + } + case KOption.Kzstr: { /* zero-terminated string */ + let s = lauxlib.luaL_checkstring(L, arg); + s = L.stack[lapi.index2addr_(L, arg)].value; + let len = s.value.length; + lauxlib.luaL_argcheck(L, s.value.length === String.fromCharCode(...s.value).length, arg, "strings contains zeros"); + b.concat(s.value); + b.push(0); /* add zero at the end */ + totalsize += len + 1; + break; + } + case KOption.Kpadding: b.push(LUAL_PACKPADBYTE); + case KOption.Kpaddalign: case KOption.Knop: + arg--; /* undo increment */ + break; + } + } + L.stack[L.top++] = new lobject.TValue(CT.LUA_TLNGSTR, b); // We don't want lua > js > lua string conversion here + return 1; +}; + const str_reverse = function(L) { lapi.lua_pushstring(L, lauxlib.luaL_checkstring(L, 1).split("").reverse().join("")); return 1; @@ -401,6 +655,7 @@ const strlib = { "format": str_format, "len": str_len, "lower": str_lower, + "pack": str_pack, "rep": str_rep, "reverse": str_reverse, "sub": str_sub, -- cgit v1.2.3-54-g00ecf From 335621808b4343645a55682a50caa89c0b703795 Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Fri, 17 Mar 2017 15:03:11 +0100 Subject: string.unpack --- src/lstrlib.js | 101 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) (limited to 'src/lstrlib.js') diff --git a/src/lstrlib.js b/src/lstrlib.js index 89d1f7f..d6c642a 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -366,7 +366,7 @@ const SZINT = 8; // Size of lua_Integer const NB = 8; /* mask for one character (NB 1's) */ -const MC = ((1 << NB) - 1) +const MC = ((1 << NB) - 1); /* ** information to pack/unpack stuff @@ -648,6 +648,104 @@ const str_byte = function(L) { return n; }; +/* +** Unpack an integer with 'size' bytes and 'islittle' endianness. +** If size is smaller than the size of a Lua integer and integer +** is signed, must do sign extension (propagating the sign to the +** higher bits); if size is larger than the size of a Lua integer, +** it must check the unread bytes to see whether they do not cause an +** overflow. +*/ +const unpackint = function(L, str, islittle, size, issigned) { + let res = 0; + let limit = size <= SZINT ? size : SZINT; + for (let i = limit - 1; i >= 0; i--) { + res <<= NB; + res |= str[islittle ? i : size - 1 - i]; + } + if (size < SZINT) { /* real size smaller than lua_Integer? */ + if (issigned) { /* needs sign extension? */ + let mask = 1 << (size * NB - 1); + res = ((res ^ mask) - mask); /* do sign extension */ + } + } else if (size > SZINT) { /* must check unread bytes */ + let mask = issigned || res >= 0 ? 0 : MC; + for (let i = limit; i < size; i++) { + if (str[islittle ? i : size - 1 - i] !== mask) + lauxlib.luaL_error(L, `${size}-byte integer does not fit into Lua Integer`); + } + } + return res; +}; + +const unpacknum = function(L, b, islittle, size) { + assert(b.length >= size); + + let dv = new DataView(new ArrayBuffer(size)); + b.forEach((e, i) => dv.setUint8(i, e, islittle)); + + return dv.getFloat64(0, islittle); +}; + +const str_unpack = function(L) { + let h = new Header(L); + let fmt = lauxlib.luaL_checkstring(L, 1); + let data = lauxlib.luaL_checkstring(L, 2); + data = L.stack[lapi.index2addr_(L, 2)]; + let ld = data.length; + let pos = posrelat(lauxlib.luaL_optinteger(L, 3, 1), ld) - 1; + let n = 0; /* number of results */ + lauxlib.luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); + while (fmt.length > 0) { + let details = getdetails(h, pos, fmt); + let opt = details.opt; + let size = details.size; + let ntoalign = details.ntoalign; + if (ntoalign + size > ~pos || pos + ntoalign + size > ld) + lauxlib.luaL_argerror(L, 2, "data string too short"); + pos += ntoalign; /* skip alignment */ + /* stack space for item + next position */ + lauxlib.luaL_checkstack(L, 2, "too many results"); + n++; + switch (opt) { + case KOption.Kint: + case KOption.Kuint: { + let res = unpackint(L, data.slice(pos), h.islittle, size, opt === KOption.Kint); + lapi.lua_pushinteger(L, res); + break; + } + case KOption.Kfloat: { + let res = unpacknum(L, data.slice(pos), h.islittle, size); + lapi.lua_pushnumber(L, res); + break; + } + case KOption.Kchar: { + lapi.lua_pushstring(L, data.slice(pos, pos + size)); + break; + } + case KOption.Kstring: { + let len = unpackint(L, data.slice(pos), h.islittle, size, 0); + lauxlib.luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); + lapi.lua_pushstring(L, data.slice(pos + size, pos + size + len)); + pos += len; /* skip string */ + break; + } + case KOption.Kzstr: { + let len = data.slice(pos).indexOf(0); + lapi.lua_pushstring(L, data.slice(pos, pos + len)); + pos += len + 1; /* skip string plus final '\0' */ + break; + } + case KOption.Kpaddalign: case KOption.Kpadding: case KOption.Knop: + n--; /* undo increment */ + break; + } + pos += size; + } + lapi.lua_pushinteger(L, pos + 1); /* next position */ + return n + 1; +}; + const strlib = { "byte": str_byte, "char": str_char, @@ -659,6 +757,7 @@ const strlib = { "rep": str_rep, "reverse": str_reverse, "sub": str_sub, + "unpack": str_unpack, "upper": str_upper }; -- cgit v1.2.3-54-g00ecf From 54a15b81c50a56c6cecbe99d597b95094427e3c6 Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Fri, 17 Mar 2017 15:08:28 +0100 Subject: string.packsize --- src/lstrlib.js | 70 ++++++++++++++++++++++++++++++++++++++++++++------------ tests/lstrlib.js | 34 +++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 14 deletions(-) (limited to 'src/lstrlib.js') diff --git a/src/lstrlib.js b/src/lstrlib.js index d6c642a..030e063 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -368,6 +368,8 @@ const NB = 8; /* mask for one character (NB 1's) */ const MC = ((1 << NB) - 1); +const MAXALIGN = 8; + /* ** information to pack/unpack stuff */ @@ -448,6 +450,22 @@ const getoption = function(h, fmt) { case 'i': r.size = getnumlimit(h, fmt, 4); r.opt = KOption.Kint; return r; // sizeof(int): 4 case 'I': r.size = getnumlimit(h, fmt, 4); r.opt = KOption.Kuint; return r; case 's': r.size = getnumlimit(h, fmt, 8); r.opt = KOption.Kstring; return r; + case 'c': { + r.size = getnum(fmt, -1); + if (r.size === -1) + lauxlib.luaL_error(h.L, "missing size for format option 'c'"); + r.opt = KOption.Kchar; + return r; + } + case 'z': r.opt = KOption.Kzstr; return r; + case 'x': r.size = 1; r.opt = KOption.Kpadding; return r; + case 'X': r.opt = KOption.Kpaddalign; return r; + case ' ': break; + case '<': h.islittle = true; break; + case '>': h.islittle = false; break; + case '=': h.islittle = true; break; + case '!': h.maxalign = getnumlimit(h, fmt, MAXALIGN); break; + default: lauxlib.luaL_error(h.L, `invalid format option '${r.opt}'`); } r.opt = KOption.Knop; @@ -529,7 +547,7 @@ const packnum = function(b, n, islittle, size) { const str_pack = function(L) { let b = []; let h = new Header(); - let fmt = lauxlib.luaL_checkstring(L, 1); /* format string */ + let fmt = lauxlib.luaL_checkstring(L, 1).split(''); /* format string */ let arg = 1; /* current argument to pack */ let totalsize = 0; /* accumulate total size of result */ lapi.lua_pushnil(L); /* mark to separate arguments from string buffer */ @@ -648,6 +666,29 @@ const str_byte = function(L) { return n; }; +const str_packsize = function(L) { + let h = new Header(L); + let fmt = lauxlib.luaL_checkstring(L, 1).split(''); + let totalsize = 0; /* accumulate total size of result */ + while (fmt.length > 0) { + let details = getdetails(h, totalsize, fmt); + let opt = details.opt; + let size = details.size; + let ntoalign = details.ntoalign; + size += ntoalign; /* total space used by option */ + lauxlib.luaL_argcheck(L, totalsize <= MAXSIZE - size - 1, "format result too large"); + totalsize += size; + switch (opt) { + case KOption.Kstring: /* strings with length count */ + case KOption.Kzstr: /* zero-terminated string */ + lauxlib.luaL_argerror(L, 1, "variable-length format"); + default: break; + } + } + lapi.lua_pushinteger(L, totalsize); + return 1; +}; + /* ** Unpack an integer with 'size' bytes and 'islittle' endianness. ** If size is smaller than the size of a Lua integer and integer @@ -689,7 +730,7 @@ const unpacknum = function(L, b, islittle, size) { const str_unpack = function(L) { let h = new Header(L); - let fmt = lauxlib.luaL_checkstring(L, 1); + let fmt = lauxlib.luaL_checkstring(L, 1).split(''); let data = lauxlib.luaL_checkstring(L, 2); data = L.stack[lapi.index2addr_(L, 2)]; let ld = data.length; @@ -747,18 +788,19 @@ const str_unpack = function(L) { }; const strlib = { - "byte": str_byte, - "char": str_char, - "dump": str_dump, - "format": str_format, - "len": str_len, - "lower": str_lower, - "pack": str_pack, - "rep": str_rep, - "reverse": str_reverse, - "sub": str_sub, - "unpack": str_unpack, - "upper": str_upper + "byte": str_byte, + "char": str_char, + "dump": str_dump, + "format": str_format, + "len": str_len, + "lower": str_lower, + "pack": str_pack, + "packsize": str_packsize, + "rep": str_rep, + "reverse": str_reverse, + "sub": str_sub, + "unpack": str_unpack, + "upper": str_upper }; const createmetatable = function(L) { diff --git a/tests/lstrlib.js b/tests/lstrlib.js index 23cd786..4185f04 100644 --- a/tests/lstrlib.js +++ b/tests/lstrlib.js @@ -459,4 +459,38 @@ test('string.dump', function (t) { "hello1212.5", "Correct element(s) on the stack" ); +}); + + +test('string.pack/unpack/packsize', function (t) { + let luaCode = ` + local s1, n, s2 = "hello", 2, "you" + local packed = string.pack("zjz", s1, n, s2) + local us1, un, us2 = string.unpack("zjz", packed) + return s1 == us1 and n == un and s2 == us2 + `, L; + + t.plan(3); + + t.doesNotThrow(function () { + + L = lauxlib.luaL_newstate(); + + linit.luaL_openlibs(L); + + lauxlib.luaL_loadstring(L, luaCode); + + }, "Lua program loaded without error"); + + t.doesNotThrow(function () { + + lapi.lua_call(L, 0, -1); + + }, "Lua program ran without error"); + + t.strictEqual( + lapi.lua_tostring(L, -1), + "FFFFFFF", + "Correct element(s) on the stack" + ); }); \ No newline at end of file -- cgit v1.2.3-54-g00ecf From 9ac1d380dd1da894c6317845ea3234124663714b Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Fri, 17 Mar 2017 16:06:10 +0100 Subject: string.pack/unpack/packsize test --- sizes | Bin 8656 -> 0 bytes sizes.c | 9 -------- src/lstrlib.js | 64 ++++++++++++++++++++++++++++++++++++------------------- tests/lstrlib.js | 17 +++++++++------ 4 files changed, 53 insertions(+), 37 deletions(-) delete mode 100755 sizes delete mode 100644 sizes.c (limited to 'src/lstrlib.js') diff --git a/sizes b/sizes deleted file mode 100755 index eabd657..0000000 Binary files a/sizes and /dev/null differ diff --git a/sizes.c b/sizes.c deleted file mode 100644 index 647c169..0000000 --- a/sizes.c +++ /dev/null @@ -1,9 +0,0 @@ -#include - -int main(void) { - - printf("sizeof(char): %lu\nsizeof(short): %lu\nsizeof(long): %lu\nsizeof(size_t): %lu\nsizeof(float): %lu\nsizeof(double): %lu\nsizeof(int): %lu\n", - sizeof(char), sizeof(short), sizeof(long), sizeof(size_t), sizeof(float), sizeof(double), sizeof(int)); - - return 0; -} \ No newline at end of file diff --git a/src/lstrlib.js b/src/lstrlib.js index 030e063..56fcc11 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -397,17 +397,18 @@ const KOption = { }; const digit = function(c) { - return '0'.charCodeAt(0) <= c && c <= '9'.charCodeAt(0); + return '0'.charCodeAt(0) <= c.charCodeAt(0) && c.charCodeAt(0) <= '9'.charCodeAt(0); }; const getnum = function(fmt, df) { - if (!digit(fmt)) /* no number? */ + if (!digit(fmt.s[0])) /* no number? */ return df; /* return default value */ else { let a = 0; do { - a = a * 10 + ((fmt = fmt.slice(1))[0] - '0'.charCodeAt(0)); - } while (digit(fmt[0]) && a <= (MAXSIZE - 9)/10); + a = a * 10 + (fmt.s[0].charCodeAt(0) - '0'.charCodeAt(0)); + fmt.s = fmt.s.slice(1); + } while (digit(fmt.s[0]) && a <= (MAXSIZE - 9)/10); return a; } }; @@ -432,7 +433,8 @@ const getoption = function(h, fmt) { size: NaN }; - r.opt = (fmt = fmt.slice(1))[0]; + r.opt = fmt.s[0]; + fmt.s = fmt.s.slice(1); r.size = 0; /* default */ switch (r.opt) { case 'b': r.size = 1; r.opt = KOption.Kint; return r; // sizeof(char): 1 @@ -492,8 +494,8 @@ const getdetails = function(h, totalsize, fmt) { r.size = opt.size; r.opt = opt.opt; let align = r.size; /* usually, alignment follows size */ - if (opt === KOption.Kpaddalign) { /* 'X' gets alignment from following option */ - if (fmt[0] === 0) + if (r.opt === KOption.Kpaddalign) { /* 'X' gets alignment from following option */ + if (fmt.s[0] === 0) lauxlib.luaL_argerror(h.L, 1, "invalid next option for option 'X'"); else { let o = getoption(h, fmt); @@ -503,7 +505,7 @@ const getdetails = function(h, totalsize, fmt) { lauxlib.luaL_argerror(h.L, 1, "invalid next option for option 'X'"); } } - if (align <= 1 || opt === KOption.Kchar) /* need no alignment? */ + if (align <= 1 || r.opt === KOption.Kchar) /* need no alignment? */ r.ntoalign = 0; else { if (align > h.maxalign) /* enforce maximum alignment */ @@ -533,7 +535,7 @@ const packint = function(b, n, islittle, size, neg) { for (let i = SZINT; i < size; i++) /* correct extra bytes */ buff[islittle ? i : size - 1 - i] = MC; } - b.concat(buff); /* add result to buffer */ + b.push(...buff); /* add result to buffer */ }; const packnum = function(b, n, islittle, size) { @@ -546,12 +548,17 @@ const packnum = function(b, n, islittle, size) { const str_pack = function(L) { let b = []; - let h = new Header(); + let h = new Header(L); let fmt = lauxlib.luaL_checkstring(L, 1).split(''); /* format string */ + fmt.push('\0'); // Add \0 to avoid overflow + fmt = { + s: fmt, + off: 0 + }; let arg = 1; /* current argument to pack */ let totalsize = 0; /* accumulate total size of result */ lapi.lua_pushnil(L); /* mark to separate arguments from string buffer */ - while (fmt.length > 0) { + while (fmt.s.length - 1 > 0) { let details = getdetails(h, totalsize, fmt); let opt = details.opt; let size = details.size; @@ -584,10 +591,10 @@ const str_pack = function(L) { } case KOption.Kchar: { /* fixed-size string */ let s = lauxlib.luaL_checkstring(L, arg); - s = L.stack[lapi.index2addr_(L, arg)].value; + s = L.stack[lapi.index2addr_(L, arg)]; let len = s.value.length; lauxlib.luaL_argcheck(L, len <= size, arg, "string long than given size"); - b.concat(s.value); /* add string */ + b.push(...s.value); /* add string */ while (len++ < size) /* pad extra space */ b.push(LUAL_PACKPADBYTE); break; @@ -598,7 +605,7 @@ const str_pack = function(L) { let len = s.value.length; lauxlib.luaL_argcheck(L, size >= NB || len < (1 << size * NB), arg, "string length does not fit in given size"); packint(b, len, h.islittle, size, 0); /* pack length */ - b.concat(s.value); + b.push(...s.value); totalsize += len; break; } @@ -607,7 +614,7 @@ const str_pack = function(L) { s = L.stack[lapi.index2addr_(L, arg)].value; let len = s.value.length; lauxlib.luaL_argcheck(L, s.value.length === String.fromCharCode(...s.value).length, arg, "strings contains zeros"); - b.concat(s.value); + b.push(...s.value); b.push(0); /* add zero at the end */ totalsize += len + 1; break; @@ -669,8 +676,13 @@ const str_byte = function(L) { const str_packsize = function(L) { let h = new Header(L); let fmt = lauxlib.luaL_checkstring(L, 1).split(''); + fmt.push('\0'); // Add \0 to avoid overflow + fmt = { + s: fmt, + off: 0 + }; let totalsize = 0; /* accumulate total size of result */ - while (fmt.length > 0) { + while (fmt.s.length - 1 > 0) { let details = getdetails(h, totalsize, fmt); let opt = details.opt; let size = details.size; @@ -731,18 +743,23 @@ const unpacknum = function(L, b, islittle, size) { const str_unpack = function(L) { let h = new Header(L); let fmt = lauxlib.luaL_checkstring(L, 1).split(''); + fmt.push('\0'); // Add \0 to avoid overflow + fmt = { + s: fmt, + off: 0 + }; let data = lauxlib.luaL_checkstring(L, 2); - data = L.stack[lapi.index2addr_(L, 2)]; + data = L.stack[lapi.index2addr_(L, 2)].value; let ld = data.length; let pos = posrelat(lauxlib.luaL_optinteger(L, 3, 1), ld) - 1; let n = 0; /* number of results */ lauxlib.luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); - while (fmt.length > 0) { + while (fmt.s.length - 1 > 0) { let details = getdetails(h, pos, fmt); let opt = details.opt; let size = details.size; let ntoalign = details.ntoalign; - if (ntoalign + size > ~pos || pos + ntoalign + size > ld) + if (/*ntoalign + size > ~pos ||*/ pos + ntoalign + size > ld) lauxlib.luaL_argerror(L, 2, "data string too short"); pos += ntoalign; /* skip alignment */ /* stack space for item + next position */ @@ -761,19 +778,22 @@ const str_unpack = function(L) { break; } case KOption.Kchar: { - lapi.lua_pushstring(L, data.slice(pos, pos + size)); + // lapi.lua_pushstring(L, data.slice(pos, pos + size)); + L.stack[L.top++] = new lobject.TValue(CT.LUA_TLNGSTR, data.slice(pos, pos + size)); break; } case KOption.Kstring: { let len = unpackint(L, data.slice(pos), h.islittle, size, 0); lauxlib.luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); - lapi.lua_pushstring(L, data.slice(pos + size, pos + size + len)); + // lapi.lua_pushstring(L, data.slice(pos + size, pos + size + len)); + L.stack[L.top++] = new lobject.TValue(CT.LUA_TLNGSTR, data.slice(pos + size, pos + size + len)); pos += len; /* skip string */ break; } case KOption.Kzstr: { let len = data.slice(pos).indexOf(0); - lapi.lua_pushstring(L, data.slice(pos, pos + len)); + // lapi.lua_pushstring(L, data.slice(pos, pos + len)); + L.stack[L.top++] = new lobject.TValue(CT.LUA_TLNGSTR, data.slice(pos, pos + len)); pos += len + 1; /* skip string plus final '\0' */ break; } diff --git a/tests/lstrlib.js b/tests/lstrlib.js index 4185f04..6364c7f 100644 --- a/tests/lstrlib.js +++ b/tests/lstrlib.js @@ -465,12 +465,12 @@ test('string.dump', function (t) { test('string.pack/unpack/packsize', function (t) { let luaCode = ` local s1, n, s2 = "hello", 2, "you" - local packed = string.pack("zjz", s1, n, s2) - local us1, un, us2 = string.unpack("zjz", packed) - return s1 == us1 and n == un and s2 == us2 + local packed = string.pack("c5jc3", s1, n, s2) + local us1, un, us2 = string.unpack("c5jc3", packed) + return string.packsize("c5jc3"), s1 == us1 and n == un and s2 == us2 `, L; - t.plan(3); + t.plan(4); t.doesNotThrow(function () { @@ -489,8 +489,13 @@ test('string.pack/unpack/packsize', function (t) { }, "Lua program ran without error"); t.strictEqual( - lapi.lua_tostring(L, -1), - "FFFFFFF", + lapi.lua_tointeger(L, -2), + 16, + "Correct element(s) on the stack" + ); + + t.ok( + lapi.lua_toboolean(L, -1), "Correct element(s) on the stack" ); }); \ No newline at end of file -- cgit v1.2.3-54-g00ecf