Closed lijian2233 closed 8 years ago
local str = "" for i=1, 30 do str = str .. "\x8a" end
print(type(str), #str) local str1 = sproto.pack(str)
会触发(bytes == 34 and maxsz == 32) if (bytes > maxsz) { return luaL_error(L, "packing error, return size = %d", bytes); }
应该是在463行之前把sz做下8字节对齐就行了把。
确实不能对sz
直接对齐赋值,下面的bytes = sproto_pack(buffer, sz, output, maxsz);
会用到sz
,如果赋值的话,将会出现访问越界。
对,不要修改sz, 只修改maxsz
@lvzixun 下次能不能不用tricks。。。看了好久才看出来是对齐。。。。ref:http://www.catch22.net/tuts/c-c-tricks
static int lpack(lua_State L) { size_t sz=0; const void * buffer = getbuffer(L, 1, &sz); // the worst-case space overhead of packing is 2 bytes per 2 KiB of input (256 words = 2KiB). //size_t maxsz = (sz + 2047) / 2048 * 2 + sz; //if (sz % 8) == 6 then sz = sz + 2 end if (sz%8) == 7 then sz = sz + 1 end size_t maxsz = (sz + 2047) / 2048 * 2 + ((sz + 7) & (~7)); void \ output = lua_touserdata(L, lua_upvalueindex(1)); int bytes; int osz = lua_tointeger(L, lua_upvalueindex(2)); if (osz < maxsz) { output = expand_buffer(L, osz, maxsz); } bytes = sproto_pack(buffer, sz, output, maxsz); if (bytes > maxsz) { return luaL_error(L, "packing error, return size = %d", bytes); } lua_pushlstring(L, output, bytes);
}
maxsz计算错误。 unpacked (hex): 8a (x 30 bytes) packed (hex): ff 03 8a (x 30 bytes) 00 00
没有计算padding数据的大小
// the worst-case space overhead of packing is 2 bytes per 2 KiB of input (256 words = 2KiB). 压缩格式: ff 1byte xx ... 1byte 最大值255, (255+1)*8 = 2Kib, 每2Kib需要额外的两个字节空间 ff ff。
(sz + 2047) / 2048 * 2 计算 the worst-case space overhead of packing is 2 bytes per 2 KiB of input (256 words = 2KiB)这个值, ((sz + 7) & (~7)) 8字节对齐,更精确的值是这样的 if (sz % 8) == 6 then sz = sz + 2 end if (sz%8) == 7 then sz = sz + 1 end。