PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/deps/lua/src/lua_cmsgpack.c

https://gitlab.com/unofficial-mirrors/redis
C | 967 lines | 719 code | 107 blank | 141 comment | 106 complexity | fa571c8da45200602343d04d823eb7d9 MD5 | raw file
  1. #include <math.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include "lua.h"
  7. #include "lauxlib.h"
  8. #define LUACMSGPACK_NAME "cmsgpack"
  9. #define LUACMSGPACK_SAFE_NAME "cmsgpack_safe"
  10. #define LUACMSGPACK_VERSION "lua-cmsgpack 0.4.0"
  11. #define LUACMSGPACK_COPYRIGHT "Copyright (C) 2012, Salvatore Sanfilippo"
  12. #define LUACMSGPACK_DESCRIPTION "MessagePack C implementation for Lua"
  13. /* Allows a preprocessor directive to override MAX_NESTING */
  14. #ifndef LUACMSGPACK_MAX_NESTING
  15. #define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
  16. #endif
  17. /* Check if float or double can be an integer without loss of precision */
  18. #define IS_INT_TYPE_EQUIVALENT(x, T) (!isinf(x) && (T)(x) == (x))
  19. #define IS_INT64_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int64_t)
  20. #define IS_INT_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int)
  21. /* If size of pointer is equal to a 4 byte integer, we're on 32 bits. */
  22. #if UINTPTR_MAX == UINT_MAX
  23. #define BITS_32 1
  24. #else
  25. #define BITS_32 0
  26. #endif
  27. #if BITS_32
  28. #define lua_pushunsigned(L, n) lua_pushnumber(L, n)
  29. #else
  30. #define lua_pushunsigned(L, n) lua_pushinteger(L, n)
  31. #endif
  32. /* =============================================================================
  33. * MessagePack implementation and bindings for Lua 5.1/5.2.
  34. * Copyright(C) 2012 Salvatore Sanfilippo <antirez@gmail.com>
  35. *
  36. * http://github.com/antirez/lua-cmsgpack
  37. *
  38. * For MessagePack specification check the following web site:
  39. * http://wiki.msgpack.org/display/MSGPACK/Format+specification
  40. *
  41. * See Copyright Notice at the end of this file.
  42. *
  43. * CHANGELOG:
  44. * 19-Feb-2012 (ver 0.1.0): Initial release.
  45. * 20-Feb-2012 (ver 0.2.0): Tables encoding improved.
  46. * 20-Feb-2012 (ver 0.2.1): Minor bug fixing.
  47. * 20-Feb-2012 (ver 0.3.0): Module renamed lua-cmsgpack (was lua-msgpack).
  48. * 04-Apr-2014 (ver 0.3.1): Lua 5.2 support and minor bug fix.
  49. * 07-Apr-2014 (ver 0.4.0): Multiple pack/unpack, lua allocator, efficiency.
  50. * ========================================================================== */
  51. /* -------------------------- Endian conversion --------------------------------
  52. * We use it only for floats and doubles, all the other conversions performed
  53. * in an endian independent fashion. So the only thing we need is a function
  54. * that swaps a binary string if arch is little endian (and left it untouched
  55. * otherwise). */
  56. /* Reverse memory bytes if arch is little endian. Given the conceptual
  57. * simplicity of the Lua build system we prefer check for endianess at runtime.
  58. * The performance difference should be acceptable. */
  59. void memrevifle(void *ptr, size_t len) {
  60. unsigned char *p = (unsigned char *)ptr,
  61. *e = (unsigned char *)p+len-1,
  62. aux;
  63. int test = 1;
  64. unsigned char *testp = (unsigned char*) &test;
  65. if (testp[0] == 0) return; /* Big endian, nothing to do. */
  66. len /= 2;
  67. while(len--) {
  68. aux = *p;
  69. *p = *e;
  70. *e = aux;
  71. p++;
  72. e--;
  73. }
  74. }
  75. /* ---------------------------- String buffer ----------------------------------
  76. * This is a simple implementation of string buffers. The only operation
  77. * supported is creating empty buffers and appending bytes to it.
  78. * The string buffer uses 2x preallocation on every realloc for O(N) append
  79. * behavior. */
  80. typedef struct mp_buf {
  81. unsigned char *b;
  82. size_t len, free;
  83. } mp_buf;
  84. void *mp_realloc(lua_State *L, void *target, size_t osize,size_t nsize) {
  85. void *(*local_realloc) (void *, void *, size_t osize, size_t nsize) = NULL;
  86. void *ud;
  87. local_realloc = lua_getallocf(L, &ud);
  88. return local_realloc(ud, target, osize, nsize);
  89. }
  90. mp_buf *mp_buf_new(lua_State *L) {
  91. mp_buf *buf = NULL;
  92. /* Old size = 0; new size = sizeof(*buf) */
  93. buf = (mp_buf*)mp_realloc(L, NULL, 0, sizeof(*buf));
  94. buf->b = NULL;
  95. buf->len = buf->free = 0;
  96. return buf;
  97. }
  98. void mp_buf_append(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
  99. if (buf->free < len) {
  100. size_t newsize = (buf->len+len)*2;
  101. buf->b = (unsigned char*)mp_realloc(L, buf->b, buf->len + buf->free, newsize);
  102. buf->free = newsize - buf->len;
  103. }
  104. memcpy(buf->b+buf->len,s,len);
  105. buf->len += len;
  106. buf->free -= len;
  107. }
  108. void mp_buf_free(lua_State *L, mp_buf *buf) {
  109. mp_realloc(L, buf->b, buf->len + buf->free, 0); /* realloc to 0 = free */
  110. mp_realloc(L, buf, sizeof(*buf), 0);
  111. }
  112. /* ---------------------------- String cursor ----------------------------------
  113. * This simple data structure is used for parsing. Basically you create a cursor
  114. * using a string pointer and a length, then it is possible to access the
  115. * current string position with cursor->p, check the remaining length
  116. * in cursor->left, and finally consume more string using
  117. * mp_cur_consume(cursor,len), to advance 'p' and subtract 'left'.
  118. * An additional field cursor->error is set to zero on initialization and can
  119. * be used to report errors. */
  120. #define MP_CUR_ERROR_NONE 0
  121. #define MP_CUR_ERROR_EOF 1 /* Not enough data to complete operation. */
  122. #define MP_CUR_ERROR_BADFMT 2 /* Bad data format */
  123. typedef struct mp_cur {
  124. const unsigned char *p;
  125. size_t left;
  126. int err;
  127. } mp_cur;
  128. void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
  129. cursor->p = s;
  130. cursor->left = len;
  131. cursor->err = MP_CUR_ERROR_NONE;
  132. }
  133. #define mp_cur_consume(_c,_len) do { _c->p += _len; _c->left -= _len; } while(0)
  134. /* When there is not enough room we set an error in the cursor and return. This
  135. * is very common across the code so we have a macro to make the code look
  136. * a bit simpler. */
  137. #define mp_cur_need(_c,_len) do { \
  138. if (_c->left < _len) { \
  139. _c->err = MP_CUR_ERROR_EOF; \
  140. return; \
  141. } \
  142. } while(0)
  143. /* ------------------------- Low level MP encoding -------------------------- */
  144. void mp_encode_bytes(lua_State *L, mp_buf *buf, const unsigned char *s, size_t len) {
  145. unsigned char hdr[5];
  146. int hdrlen;
  147. if (len < 32) {
  148. hdr[0] = 0xa0 | (len&0xff); /* fix raw */
  149. hdrlen = 1;
  150. } else if (len <= 0xff) {
  151. hdr[0] = 0xd9;
  152. hdr[1] = len;
  153. hdrlen = 2;
  154. } else if (len <= 0xffff) {
  155. hdr[0] = 0xda;
  156. hdr[1] = (len&0xff00)>>8;
  157. hdr[2] = len&0xff;
  158. hdrlen = 3;
  159. } else {
  160. hdr[0] = 0xdb;
  161. hdr[1] = (len&0xff000000)>>24;
  162. hdr[2] = (len&0xff0000)>>16;
  163. hdr[3] = (len&0xff00)>>8;
  164. hdr[4] = len&0xff;
  165. hdrlen = 5;
  166. }
  167. mp_buf_append(L,buf,hdr,hdrlen);
  168. mp_buf_append(L,buf,s,len);
  169. }
  170. /* we assume IEEE 754 internal format for single and double precision floats. */
  171. void mp_encode_double(lua_State *L, mp_buf *buf, double d) {
  172. unsigned char b[9];
  173. float f = d;
  174. assert(sizeof(f) == 4 && sizeof(d) == 8);
  175. if (d == (double)f) {
  176. b[0] = 0xca; /* float IEEE 754 */
  177. memcpy(b+1,&f,4);
  178. memrevifle(b+1,4);
  179. mp_buf_append(L,buf,b,5);
  180. } else if (sizeof(d) == 8) {
  181. b[0] = 0xcb; /* double IEEE 754 */
  182. memcpy(b+1,&d,8);
  183. memrevifle(b+1,8);
  184. mp_buf_append(L,buf,b,9);
  185. }
  186. }
  187. void mp_encode_int(lua_State *L, mp_buf *buf, int64_t n) {
  188. unsigned char b[9];
  189. int enclen;
  190. if (n >= 0) {
  191. if (n <= 127) {
  192. b[0] = n & 0x7f; /* positive fixnum */
  193. enclen = 1;
  194. } else if (n <= 0xff) {
  195. b[0] = 0xcc; /* uint 8 */
  196. b[1] = n & 0xff;
  197. enclen = 2;
  198. } else if (n <= 0xffff) {
  199. b[0] = 0xcd; /* uint 16 */
  200. b[1] = (n & 0xff00) >> 8;
  201. b[2] = n & 0xff;
  202. enclen = 3;
  203. } else if (n <= 0xffffffffLL) {
  204. b[0] = 0xce; /* uint 32 */
  205. b[1] = (n & 0xff000000) >> 24;
  206. b[2] = (n & 0xff0000) >> 16;
  207. b[3] = (n & 0xff00) >> 8;
  208. b[4] = n & 0xff;
  209. enclen = 5;
  210. } else {
  211. b[0] = 0xcf; /* uint 64 */
  212. b[1] = (n & 0xff00000000000000LL) >> 56;
  213. b[2] = (n & 0xff000000000000LL) >> 48;
  214. b[3] = (n & 0xff0000000000LL) >> 40;
  215. b[4] = (n & 0xff00000000LL) >> 32;
  216. b[5] = (n & 0xff000000) >> 24;
  217. b[6] = (n & 0xff0000) >> 16;
  218. b[7] = (n & 0xff00) >> 8;
  219. b[8] = n & 0xff;
  220. enclen = 9;
  221. }
  222. } else {
  223. if (n >= -32) {
  224. b[0] = ((signed char)n); /* negative fixnum */
  225. enclen = 1;
  226. } else if (n >= -128) {
  227. b[0] = 0xd0; /* int 8 */
  228. b[1] = n & 0xff;
  229. enclen = 2;
  230. } else if (n >= -32768) {
  231. b[0] = 0xd1; /* int 16 */
  232. b[1] = (n & 0xff00) >> 8;
  233. b[2] = n & 0xff;
  234. enclen = 3;
  235. } else if (n >= -2147483648LL) {
  236. b[0] = 0xd2; /* int 32 */
  237. b[1] = (n & 0xff000000) >> 24;
  238. b[2] = (n & 0xff0000) >> 16;
  239. b[3] = (n & 0xff00) >> 8;
  240. b[4] = n & 0xff;
  241. enclen = 5;
  242. } else {
  243. b[0] = 0xd3; /* int 64 */
  244. b[1] = (n & 0xff00000000000000LL) >> 56;
  245. b[2] = (n & 0xff000000000000LL) >> 48;
  246. b[3] = (n & 0xff0000000000LL) >> 40;
  247. b[4] = (n & 0xff00000000LL) >> 32;
  248. b[5] = (n & 0xff000000) >> 24;
  249. b[6] = (n & 0xff0000) >> 16;
  250. b[7] = (n & 0xff00) >> 8;
  251. b[8] = n & 0xff;
  252. enclen = 9;
  253. }
  254. }
  255. mp_buf_append(L,buf,b,enclen);
  256. }
  257. void mp_encode_array(lua_State *L, mp_buf *buf, int64_t n) {
  258. unsigned char b[5];
  259. int enclen;
  260. if (n <= 15) {
  261. b[0] = 0x90 | (n & 0xf); /* fix array */
  262. enclen = 1;
  263. } else if (n <= 65535) {
  264. b[0] = 0xdc; /* array 16 */
  265. b[1] = (n & 0xff00) >> 8;
  266. b[2] = n & 0xff;
  267. enclen = 3;
  268. } else {
  269. b[0] = 0xdd; /* array 32 */
  270. b[1] = (n & 0xff000000) >> 24;
  271. b[2] = (n & 0xff0000) >> 16;
  272. b[3] = (n & 0xff00) >> 8;
  273. b[4] = n & 0xff;
  274. enclen = 5;
  275. }
  276. mp_buf_append(L,buf,b,enclen);
  277. }
  278. void mp_encode_map(lua_State *L, mp_buf *buf, int64_t n) {
  279. unsigned char b[5];
  280. int enclen;
  281. if (n <= 15) {
  282. b[0] = 0x80 | (n & 0xf); /* fix map */
  283. enclen = 1;
  284. } else if (n <= 65535) {
  285. b[0] = 0xde; /* map 16 */
  286. b[1] = (n & 0xff00) >> 8;
  287. b[2] = n & 0xff;
  288. enclen = 3;
  289. } else {
  290. b[0] = 0xdf; /* map 32 */
  291. b[1] = (n & 0xff000000) >> 24;
  292. b[2] = (n & 0xff0000) >> 16;
  293. b[3] = (n & 0xff00) >> 8;
  294. b[4] = n & 0xff;
  295. enclen = 5;
  296. }
  297. mp_buf_append(L,buf,b,enclen);
  298. }
  299. /* --------------------------- Lua types encoding --------------------------- */
  300. void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
  301. size_t len;
  302. const char *s;
  303. s = lua_tolstring(L,-1,&len);
  304. mp_encode_bytes(L,buf,(const unsigned char*)s,len);
  305. }
  306. void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
  307. unsigned char b = lua_toboolean(L,-1) ? 0xc3 : 0xc2;
  308. mp_buf_append(L,buf,&b,1);
  309. }
  310. /* Lua 5.3 has a built in 64-bit integer type */
  311. void mp_encode_lua_integer(lua_State *L, mp_buf *buf) {
  312. #if (LUA_VERSION_NUM < 503) && BITS_32
  313. lua_Number i = lua_tonumber(L,-1);
  314. #else
  315. lua_Integer i = lua_tointeger(L,-1);
  316. #endif
  317. mp_encode_int(L, buf, (int64_t)i);
  318. }
  319. /* Lua 5.2 and lower only has 64-bit doubles, so we need to
  320. * detect if the double may be representable as an int
  321. * for Lua < 5.3 */
  322. void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
  323. lua_Number n = lua_tonumber(L,-1);
  324. if (IS_INT64_EQUIVALENT(n)) {
  325. mp_encode_lua_integer(L, buf);
  326. } else {
  327. mp_encode_double(L,buf,(double)n);
  328. }
  329. }
  330. void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
  331. /* Convert a lua table into a message pack list. */
  332. void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
  333. #if LUA_VERSION_NUM < 502
  334. size_t len = lua_objlen(L,-1), j;
  335. #else
  336. size_t len = lua_rawlen(L,-1), j;
  337. #endif
  338. mp_encode_array(L,buf,len);
  339. for (j = 1; j <= len; j++) {
  340. lua_pushnumber(L,j);
  341. lua_gettable(L,-2);
  342. mp_encode_lua_type(L,buf,level+1);
  343. }
  344. }
  345. /* Convert a lua table into a message pack key-value map. */
  346. void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
  347. size_t len = 0;
  348. /* First step: count keys into table. No other way to do it with the
  349. * Lua API, we need to iterate a first time. Note that an alternative
  350. * would be to do a single run, and then hack the buffer to insert the
  351. * map opcodes for message pack. Too hackish for this lib. */
  352. lua_pushnil(L);
  353. while(lua_next(L,-2)) {
  354. lua_pop(L,1); /* remove value, keep key for next iteration. */
  355. len++;
  356. }
  357. /* Step two: actually encoding of the map. */
  358. mp_encode_map(L,buf,len);
  359. lua_pushnil(L);
  360. while(lua_next(L,-2)) {
  361. /* Stack: ... key value */
  362. lua_pushvalue(L,-2); /* Stack: ... key value key */
  363. mp_encode_lua_type(L,buf,level+1); /* encode key */
  364. mp_encode_lua_type(L,buf,level+1); /* encode val */
  365. }
  366. }
  367. /* Returns true if the Lua table on top of the stack is exclusively composed
  368. * of keys from numerical keys from 1 up to N, with N being the total number
  369. * of elements, without any hole in the middle. */
  370. int table_is_an_array(lua_State *L) {
  371. int count = 0, max = 0;
  372. #if LUA_VERSION_NUM < 503
  373. lua_Number n;
  374. #else
  375. lua_Integer n;
  376. #endif
  377. /* Stack top on function entry */
  378. int stacktop;
  379. stacktop = lua_gettop(L);
  380. lua_pushnil(L);
  381. while(lua_next(L,-2)) {
  382. /* Stack: ... key value */
  383. lua_pop(L,1); /* Stack: ... key */
  384. /* The <= 0 check is valid here because we're comparing indexes. */
  385. #if LUA_VERSION_NUM < 503
  386. if ((LUA_TNUMBER != lua_type(L,-1)) || (n = lua_tonumber(L, -1)) <= 0 ||
  387. !IS_INT_EQUIVALENT(n))
  388. #else
  389. if (!lua_isinteger(L,-1) || (n = lua_tointeger(L, -1)) <= 0)
  390. #endif
  391. {
  392. lua_settop(L, stacktop);
  393. return 0;
  394. }
  395. max = (n > max ? n : max);
  396. count++;
  397. }
  398. /* We have the total number of elements in "count". Also we have
  399. * the max index encountered in "max". We can't reach this code
  400. * if there are indexes <= 0. If you also note that there can not be
  401. * repeated keys into a table, you have that if max==count you are sure
  402. * that there are all the keys form 1 to count (both included). */
  403. lua_settop(L, stacktop);
  404. return max == count;
  405. }
  406. /* If the length operator returns non-zero, that is, there is at least
  407. * an object at key '1', we serialize to message pack list. Otherwise
  408. * we use a map. */
  409. void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
  410. if (table_is_an_array(L))
  411. mp_encode_lua_table_as_array(L,buf,level);
  412. else
  413. mp_encode_lua_table_as_map(L,buf,level);
  414. }
  415. void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
  416. unsigned char b[1];
  417. b[0] = 0xc0;
  418. mp_buf_append(L,buf,b,1);
  419. }
  420. void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
  421. int t = lua_type(L,-1);
  422. /* Limit the encoding of nested tables to a specified maximum depth, so that
  423. * we survive when called against circular references in tables. */
  424. if (t == LUA_TTABLE && level == LUACMSGPACK_MAX_NESTING) t = LUA_TNIL;
  425. switch(t) {
  426. case LUA_TSTRING: mp_encode_lua_string(L,buf); break;
  427. case LUA_TBOOLEAN: mp_encode_lua_bool(L,buf); break;
  428. case LUA_TNUMBER:
  429. #if LUA_VERSION_NUM < 503
  430. mp_encode_lua_number(L,buf); break;
  431. #else
  432. if (lua_isinteger(L, -1)) {
  433. mp_encode_lua_integer(L, buf);
  434. } else {
  435. mp_encode_lua_number(L, buf);
  436. }
  437. break;
  438. #endif
  439. case LUA_TTABLE: mp_encode_lua_table(L,buf,level); break;
  440. default: mp_encode_lua_null(L,buf); break;
  441. }
  442. lua_pop(L,1);
  443. }
  444. /*
  445. * Packs all arguments as a stream for multiple upacking later.
  446. * Returns error if no arguments provided.
  447. */
  448. int mp_pack(lua_State *L) {
  449. int nargs = lua_gettop(L);
  450. int i;
  451. mp_buf *buf;
  452. if (nargs == 0)
  453. return luaL_argerror(L, 0, "MessagePack pack needs input.");
  454. buf = mp_buf_new(L);
  455. for(i = 1; i <= nargs; i++) {
  456. /* Copy argument i to top of stack for _encode processing;
  457. * the encode function pops it from the stack when complete. */
  458. lua_pushvalue(L, i);
  459. mp_encode_lua_type(L,buf,0);
  460. lua_pushlstring(L,(char*)buf->b,buf->len);
  461. /* Reuse the buffer for the next operation by
  462. * setting its free count to the total buffer size
  463. * and the current position to zero. */
  464. buf->free += buf->len;
  465. buf->len = 0;
  466. }
  467. mp_buf_free(L, buf);
  468. /* Concatenate all nargs buffers together */
  469. lua_concat(L, nargs);
  470. return 1;
  471. }
  472. /* ------------------------------- Decoding --------------------------------- */
  473. void mp_decode_to_lua_type(lua_State *L, mp_cur *c);
  474. void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
  475. assert(len <= UINT_MAX);
  476. int index = 1;
  477. lua_newtable(L);
  478. while(len--) {
  479. lua_pushnumber(L,index++);
  480. mp_decode_to_lua_type(L,c);
  481. if (c->err) return;
  482. lua_settable(L,-3);
  483. }
  484. }
  485. void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
  486. assert(len <= UINT_MAX);
  487. lua_newtable(L);
  488. while(len--) {
  489. mp_decode_to_lua_type(L,c); /* key */
  490. if (c->err) return;
  491. mp_decode_to_lua_type(L,c); /* value */
  492. if (c->err) return;
  493. lua_settable(L,-3);
  494. }
  495. }
  496. /* Decode a Message Pack raw object pointed by the string cursor 'c' to
  497. * a Lua type, that is left as the only result on the stack. */
  498. void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
  499. mp_cur_need(c,1);
  500. /* If we return more than 18 elements, we must resize the stack to
  501. * fit all our return values. But, there is no way to
  502. * determine how many objects a msgpack will unpack to up front, so
  503. * we request a +1 larger stack on each iteration (noop if stack is
  504. * big enough, and when stack does require resize it doubles in size) */
  505. luaL_checkstack(L, 1,
  506. "too many return values at once; "
  507. "use unpack_one or unpack_limit instead.");
  508. switch(c->p[0]) {
  509. case 0xcc: /* uint 8 */
  510. mp_cur_need(c,2);
  511. lua_pushunsigned(L,c->p[1]);
  512. mp_cur_consume(c,2);
  513. break;
  514. case 0xd0: /* int 8 */
  515. mp_cur_need(c,2);
  516. lua_pushinteger(L,(signed char)c->p[1]);
  517. mp_cur_consume(c,2);
  518. break;
  519. case 0xcd: /* uint 16 */
  520. mp_cur_need(c,3);
  521. lua_pushunsigned(L,
  522. (c->p[1] << 8) |
  523. c->p[2]);
  524. mp_cur_consume(c,3);
  525. break;
  526. case 0xd1: /* int 16 */
  527. mp_cur_need(c,3);
  528. lua_pushinteger(L,(int16_t)
  529. (c->p[1] << 8) |
  530. c->p[2]);
  531. mp_cur_consume(c,3);
  532. break;
  533. case 0xce: /* uint 32 */
  534. mp_cur_need(c,5);
  535. lua_pushunsigned(L,
  536. ((uint32_t)c->p[1] << 24) |
  537. ((uint32_t)c->p[2] << 16) |
  538. ((uint32_t)c->p[3] << 8) |
  539. (uint32_t)c->p[4]);
  540. mp_cur_consume(c,5);
  541. break;
  542. case 0xd2: /* int 32 */
  543. mp_cur_need(c,5);
  544. lua_pushinteger(L,
  545. ((int32_t)c->p[1] << 24) |
  546. ((int32_t)c->p[2] << 16) |
  547. ((int32_t)c->p[3] << 8) |
  548. (int32_t)c->p[4]);
  549. mp_cur_consume(c,5);
  550. break;
  551. case 0xcf: /* uint 64 */
  552. mp_cur_need(c,9);
  553. lua_pushunsigned(L,
  554. ((uint64_t)c->p[1] << 56) |
  555. ((uint64_t)c->p[2] << 48) |
  556. ((uint64_t)c->p[3] << 40) |
  557. ((uint64_t)c->p[4] << 32) |
  558. ((uint64_t)c->p[5] << 24) |
  559. ((uint64_t)c->p[6] << 16) |
  560. ((uint64_t)c->p[7] << 8) |
  561. (uint64_t)c->p[8]);
  562. mp_cur_consume(c,9);
  563. break;
  564. case 0xd3: /* int 64 */
  565. mp_cur_need(c,9);
  566. #if LUA_VERSION_NUM < 503
  567. lua_pushnumber(L,
  568. #else
  569. lua_pushinteger(L,
  570. #endif
  571. ((int64_t)c->p[1] << 56) |
  572. ((int64_t)c->p[2] << 48) |
  573. ((int64_t)c->p[3] << 40) |
  574. ((int64_t)c->p[4] << 32) |
  575. ((int64_t)c->p[5] << 24) |
  576. ((int64_t)c->p[6] << 16) |
  577. ((int64_t)c->p[7] << 8) |
  578. (int64_t)c->p[8]);
  579. mp_cur_consume(c,9);
  580. break;
  581. case 0xc0: /* nil */
  582. lua_pushnil(L);
  583. mp_cur_consume(c,1);
  584. break;
  585. case 0xc3: /* true */
  586. lua_pushboolean(L,1);
  587. mp_cur_consume(c,1);
  588. break;
  589. case 0xc2: /* false */
  590. lua_pushboolean(L,0);
  591. mp_cur_consume(c,1);
  592. break;
  593. case 0xca: /* float */
  594. mp_cur_need(c,5);
  595. assert(sizeof(float) == 4);
  596. {
  597. float f;
  598. memcpy(&f,c->p+1,4);
  599. memrevifle(&f,4);
  600. lua_pushnumber(L,f);
  601. mp_cur_consume(c,5);
  602. }
  603. break;
  604. case 0xcb: /* double */
  605. mp_cur_need(c,9);
  606. assert(sizeof(double) == 8);
  607. {
  608. double d;
  609. memcpy(&d,c->p+1,8);
  610. memrevifle(&d,8);
  611. lua_pushnumber(L,d);
  612. mp_cur_consume(c,9);
  613. }
  614. break;
  615. case 0xd9: /* raw 8 */
  616. mp_cur_need(c,2);
  617. {
  618. size_t l = c->p[1];
  619. mp_cur_need(c,2+l);
  620. lua_pushlstring(L,(char*)c->p+2,l);
  621. mp_cur_consume(c,2+l);
  622. }
  623. break;
  624. case 0xda: /* raw 16 */
  625. mp_cur_need(c,3);
  626. {
  627. size_t l = (c->p[1] << 8) | c->p[2];
  628. mp_cur_need(c,3+l);
  629. lua_pushlstring(L,(char*)c->p+3,l);
  630. mp_cur_consume(c,3+l);
  631. }
  632. break;
  633. case 0xdb: /* raw 32 */
  634. mp_cur_need(c,5);
  635. {
  636. size_t l = ((size_t)c->p[1] << 24) |
  637. ((size_t)c->p[2] << 16) |
  638. ((size_t)c->p[3] << 8) |
  639. (size_t)c->p[4];
  640. mp_cur_consume(c,5);
  641. mp_cur_need(c,l);
  642. lua_pushlstring(L,(char*)c->p,l);
  643. mp_cur_consume(c,l);
  644. }
  645. break;
  646. case 0xdc: /* array 16 */
  647. mp_cur_need(c,3);
  648. {
  649. size_t l = (c->p[1] << 8) | c->p[2];
  650. mp_cur_consume(c,3);
  651. mp_decode_to_lua_array(L,c,l);
  652. }
  653. break;
  654. case 0xdd: /* array 32 */
  655. mp_cur_need(c,5);
  656. {
  657. size_t l = ((size_t)c->p[1] << 24) |
  658. ((size_t)c->p[2] << 16) |
  659. ((size_t)c->p[3] << 8) |
  660. (size_t)c->p[4];
  661. mp_cur_consume(c,5);
  662. mp_decode_to_lua_array(L,c,l);
  663. }
  664. break;
  665. case 0xde: /* map 16 */
  666. mp_cur_need(c,3);
  667. {
  668. size_t l = (c->p[1] << 8) | c->p[2];
  669. mp_cur_consume(c,3);
  670. mp_decode_to_lua_hash(L,c,l);
  671. }
  672. break;
  673. case 0xdf: /* map 32 */
  674. mp_cur_need(c,5);
  675. {
  676. size_t l = ((size_t)c->p[1] << 24) |
  677. ((size_t)c->p[2] << 16) |
  678. ((size_t)c->p[3] << 8) |
  679. (size_t)c->p[4];
  680. mp_cur_consume(c,5);
  681. mp_decode_to_lua_hash(L,c,l);
  682. }
  683. break;
  684. default: /* types that can't be idenitified by first byte value. */
  685. if ((c->p[0] & 0x80) == 0) { /* positive fixnum */
  686. lua_pushunsigned(L,c->p[0]);
  687. mp_cur_consume(c,1);
  688. } else if ((c->p[0] & 0xe0) == 0xe0) { /* negative fixnum */
  689. lua_pushinteger(L,(signed char)c->p[0]);
  690. mp_cur_consume(c,1);
  691. } else if ((c->p[0] & 0xe0) == 0xa0) { /* fix raw */
  692. size_t l = c->p[0] & 0x1f;
  693. mp_cur_need(c,1+l);
  694. lua_pushlstring(L,(char*)c->p+1,l);
  695. mp_cur_consume(c,1+l);
  696. } else if ((c->p[0] & 0xf0) == 0x90) { /* fix map */
  697. size_t l = c->p[0] & 0xf;
  698. mp_cur_consume(c,1);
  699. mp_decode_to_lua_array(L,c,l);
  700. } else if ((c->p[0] & 0xf0) == 0x80) { /* fix map */
  701. size_t l = c->p[0] & 0xf;
  702. mp_cur_consume(c,1);
  703. mp_decode_to_lua_hash(L,c,l);
  704. } else {
  705. c->err = MP_CUR_ERROR_BADFMT;
  706. }
  707. }
  708. }
  709. int mp_unpack_full(lua_State *L, int limit, int offset) {
  710. size_t len;
  711. const char *s;
  712. mp_cur c;
  713. int cnt; /* Number of objects unpacked */
  714. int decode_all = (!limit && !offset);
  715. s = luaL_checklstring(L,1,&len); /* if no match, exits */
  716. if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
  717. return luaL_error(L,
  718. "Invalid request to unpack with offset of %d and limit of %d.",
  719. offset, len);
  720. else if (offset > len)
  721. return luaL_error(L,
  722. "Start offset %d greater than input length %d.", offset, len);
  723. if (decode_all) limit = INT_MAX;
  724. mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
  725. /* We loop over the decode because this could be a stream
  726. * of multiple top-level values serialized together */
  727. for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
  728. mp_decode_to_lua_type(L,&c);
  729. if (c.err == MP_CUR_ERROR_EOF) {
  730. return luaL_error(L,"Missing bytes in input.");
  731. } else if (c.err == MP_CUR_ERROR_BADFMT) {
  732. return luaL_error(L,"Bad data format in input.");
  733. }
  734. }
  735. if (!decode_all) {
  736. /* c->left is the remaining size of the input buffer.
  737. * subtract the entire buffer size from the unprocessed size
  738. * to get our next start offset */
  739. int offset = len - c.left;
  740. /* Return offset -1 when we have have processed the entire buffer. */
  741. lua_pushinteger(L, c.left == 0 ? -1 : offset);
  742. /* Results are returned with the arg elements still
  743. * in place. Lua takes care of only returning
  744. * elements above the args for us.
  745. * In this case, we have one arg on the stack
  746. * for this function, so we insert our first return
  747. * value at position 2. */
  748. lua_insert(L, 2);
  749. cnt += 1; /* increase return count by one to make room for offset */
  750. }
  751. return cnt;
  752. }
  753. int mp_unpack(lua_State *L) {
  754. return mp_unpack_full(L, 0, 0);
  755. }
  756. int mp_unpack_one(lua_State *L) {
  757. int offset = luaL_optinteger(L, 2, 0);
  758. /* Variable pop because offset may not exist */
  759. lua_pop(L, lua_gettop(L)-1);
  760. return mp_unpack_full(L, 1, offset);
  761. }
  762. int mp_unpack_limit(lua_State *L) {
  763. int limit = luaL_checkinteger(L, 2);
  764. int offset = luaL_optinteger(L, 3, 0);
  765. /* Variable pop because offset may not exist */
  766. lua_pop(L, lua_gettop(L)-1);
  767. return mp_unpack_full(L, limit, offset);
  768. }
  769. int mp_safe(lua_State *L) {
  770. int argc, err, total_results;
  771. argc = lua_gettop(L);
  772. /* This adds our function to the bottom of the stack
  773. * (the "call this function" position) */
  774. lua_pushvalue(L, lua_upvalueindex(1));
  775. lua_insert(L, 1);
  776. err = lua_pcall(L, argc, LUA_MULTRET, 0);
  777. total_results = lua_gettop(L);
  778. if (!err) {
  779. return total_results;
  780. } else {
  781. lua_pushnil(L);
  782. lua_insert(L,-2);
  783. return 2;
  784. }
  785. }
  786. /* -------------------------------------------------------------------------- */
  787. const struct luaL_Reg cmds[] = {
  788. {"pack", mp_pack},
  789. {"unpack", mp_unpack},
  790. {"unpack_one", mp_unpack_one},
  791. {"unpack_limit", mp_unpack_limit},
  792. {0}
  793. };
  794. int luaopen_create(lua_State *L) {
  795. int i;
  796. /* Manually construct our module table instead of
  797. * relying on _register or _newlib */
  798. lua_newtable(L);
  799. for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
  800. lua_pushcfunction(L, cmds[i].func);
  801. lua_setfield(L, -2, cmds[i].name);
  802. }
  803. /* Add metadata */
  804. lua_pushliteral(L, LUACMSGPACK_NAME);
  805. lua_setfield(L, -2, "_NAME");
  806. lua_pushliteral(L, LUACMSGPACK_VERSION);
  807. lua_setfield(L, -2, "_VERSION");
  808. lua_pushliteral(L, LUACMSGPACK_COPYRIGHT);
  809. lua_setfield(L, -2, "_COPYRIGHT");
  810. lua_pushliteral(L, LUACMSGPACK_DESCRIPTION);
  811. lua_setfield(L, -2, "_DESCRIPTION");
  812. return 1;
  813. }
  814. LUALIB_API int luaopen_cmsgpack(lua_State *L) {
  815. luaopen_create(L);
  816. #if LUA_VERSION_NUM < 502
  817. /* Register name globally for 5.1 */
  818. lua_pushvalue(L, -1);
  819. lua_setglobal(L, LUACMSGPACK_NAME);
  820. #endif
  821. return 1;
  822. }
  823. LUALIB_API int luaopen_cmsgpack_safe(lua_State *L) {
  824. int i;
  825. luaopen_cmsgpack(L);
  826. /* Wrap all functions in the safe handler */
  827. for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
  828. lua_getfield(L, -1, cmds[i].name);
  829. lua_pushcclosure(L, mp_safe, 1);
  830. lua_setfield(L, -2, cmds[i].name);
  831. }
  832. #if LUA_VERSION_NUM < 502
  833. /* Register name globally for 5.1 */
  834. lua_pushvalue(L, -1);
  835. lua_setglobal(L, LUACMSGPACK_SAFE_NAME);
  836. #endif
  837. return 1;
  838. }
  839. /******************************************************************************
  840. * Copyright (C) 2012 Salvatore Sanfilippo. All rights reserved.
  841. *
  842. * Permission is hereby granted, free of charge, to any person obtaining
  843. * a copy of this software and associated documentation files (the
  844. * "Software"), to deal in the Software without restriction, including
  845. * without limitation the rights to use, copy, modify, merge, publish,
  846. * distribute, sublicense, and/or sell copies of the Software, and to
  847. * permit persons to whom the Software is furnished to do so, subject to
  848. * the following conditions:
  849. *
  850. * The above copyright notice and this permission notice shall be
  851. * included in all copies or substantial portions of the Software.
  852. *
  853. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  854. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  855. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  856. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  857. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  858. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  859. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  860. ******************************************************************************/