struct.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /*
  2. ** {======================================================
  3. ** Library for packing/unpacking structures.
  4. ** $Id: struct.c,v 1.4 2012/07/04 18:54:29 roberto Exp $
  5. ** See Copyright Notice at the end of this file
  6. ** =======================================================
  7. */
  8. // Original: http://www.inf.puc-rio.br/~roberto/struct/
  9. // This was ported to NodeMCU by Philip Gladstone, N1DQ
  10. /*
  11. ** Valid formats:
  12. ** > - big endian
  13. ** < - little endian
  14. ** ![num] - alignment
  15. ** x - pading
  16. ** b/B - signed/unsigned byte
  17. ** h/H - signed/unsigned short
  18. ** l/L - signed/unsigned long
  19. ** T - size_t
  20. ** i/In - signed/unsigned integer with size `n' (default is size of int)
  21. ** cn - sequence of `n' chars (from/to a string); when packing, n==0 means
  22. the whole string; when unpacking, n==0 means use the previous
  23. read number as the string length
  24. ** s - zero-terminated string
  25. ** f - float
  26. ** d - double
  27. ** ' ' - ignored
  28. */
  29. #include <assert.h>
  30. #include <ctype.h>
  31. #include <limits.h>
  32. #include <stddef.h>
  33. #include <string.h>
  34. #include "module.h"
  35. #include "lua.h"
  36. #include "lauxlib.h"
  37. /* basic integer type */
  38. #if !defined(STRUCT_INT)
  39. #define STRUCT_INT long
  40. #endif
  41. typedef STRUCT_INT Inttype;
  42. /* corresponding unsigned version */
  43. typedef unsigned STRUCT_INT Uinttype;
  44. /* maximum size (in bytes) for integral types */
  45. #ifdef LUA_NUMBER_INTEGRAL
  46. #ifdef LUA_INTEGRAL_LONGLONG
  47. #define MAXINTSIZE 8
  48. #else
  49. #define MAXINTSIZE 4
  50. #endif
  51. #else
  52. #define MAXINTSIZE 32
  53. #endif
  54. /* is 'x' a power of 2? */
  55. #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0)
  56. /* dummy structure to get alignment requirements */
  57. struct cD {
  58. char c;
  59. double d;
  60. };
  61. #define PADDING (sizeof(struct cD) - sizeof(double))
  62. #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int))
  63. /* endian options */
  64. #define BIG 0
  65. #define LITTLE 1
  66. static union {
  67. int dummy;
  68. char endian;
  69. } const native = {1};
  70. typedef struct Header {
  71. int endian;
  72. int align;
  73. } Header;
  74. static int getnum (const char **fmt, int df) {
  75. if (!isdigit((unsigned char)**fmt)) /* no number? */
  76. return df; /* return default value */
  77. else {
  78. int a = 0;
  79. do {
  80. a = a*10 + *((*fmt)++) - '0';
  81. } while (isdigit((unsigned char)**fmt));
  82. return a;
  83. }
  84. }
  85. #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1)
  86. static size_t optsize (lua_State *L, char opt, const char **fmt) {
  87. switch (opt) {
  88. case 'B': case 'b': return sizeof(char);
  89. case 'H': case 'h': return sizeof(short);
  90. case 'L': case 'l': return sizeof(long);
  91. case 'T': return sizeof(size_t);
  92. #ifndef LUA_NUMBER_INTEGRAL
  93. case 'f': return sizeof(float);
  94. case 'd': return sizeof(double);
  95. #endif
  96. case 'x': return 1;
  97. case 'c': return getnum(fmt, 1);
  98. case 'i': case 'I': {
  99. int sz = getnum(fmt, sizeof(int));
  100. if (sz > MAXINTSIZE)
  101. luaL_error(L, "integral size %d is larger than limit of %d",
  102. sz, MAXINTSIZE);
  103. return sz;
  104. }
  105. default: return 0; /* other cases do not need alignment */
  106. }
  107. }
  108. /*
  109. ** return number of bytes needed to align an element of size 'size'
  110. ** at current position 'len'
  111. */
  112. static int gettoalign (size_t len, Header *h, int opt, size_t size) {
  113. if (size == 0 || opt == 'c') return 0;
  114. if (size > (size_t)h->align)
  115. size = h->align; /* respect max. alignment */
  116. return (size - (len & (size - 1))) & (size - 1);
  117. }
  118. /*
  119. ** options to control endianess and alignment
  120. */
  121. static void controloptions (lua_State *L, int opt, const char **fmt,
  122. Header *h) {
  123. switch (opt) {
  124. case ' ': return; /* ignore white spaces */
  125. case '>': h->endian = BIG; return;
  126. case '<': h->endian = LITTLE; return;
  127. case '!': {
  128. int a = getnum(fmt, MAXALIGN);
  129. if (!isp2(a))
  130. luaL_error(L, "alignment %d is not a power of 2", a);
  131. h->align = a;
  132. return;
  133. }
  134. default: {
  135. const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt);
  136. luaL_argerror(L, 1, msg);
  137. }
  138. }
  139. }
  140. static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian,
  141. int size) {
  142. lua_Number n = luaL_checknumber(L, arg);
  143. Uinttype value;
  144. char buff[MAXINTSIZE];
  145. if (n < 0)
  146. value = (Uinttype)(Inttype)n;
  147. else
  148. value = (Uinttype)n;
  149. if (endian == LITTLE) {
  150. int i;
  151. for (i = 0; i < size; i++) {
  152. buff[i] = (value & 0xff);
  153. value >>= 8;
  154. }
  155. }
  156. else {
  157. int i;
  158. for (i = size - 1; i >= 0; i--) {
  159. buff[i] = (value & 0xff);
  160. value >>= 8;
  161. }
  162. }
  163. luaL_addlstring(b, buff, size);
  164. }
  165. #ifndef LUA_NUMBER_INTEGRAL
  166. static void correctbytes (char *b, int size, int endian) {
  167. if (endian != native.endian) {
  168. int i = 0;
  169. while (i < --size) {
  170. char temp = b[i];
  171. b[i++] = b[size];
  172. b[size] = temp;
  173. }
  174. }
  175. }
  176. #endif
  177. static int b_pack (lua_State *L) {
  178. luaL_Buffer b;
  179. const char *fmt = luaL_checkstring(L, 1);
  180. Header h;
  181. int arg = 2;
  182. size_t totalsize = 0;
  183. defaultoptions(&h);
  184. lua_pushnil(L); /* mark to separate arguments from string buffer */
  185. luaL_buffinit(L, &b);
  186. while (*fmt != '\0') {
  187. int opt = *fmt++;
  188. size_t size = optsize(L, opt, &fmt);
  189. int toalign = gettoalign(totalsize, &h, opt, size);
  190. totalsize += toalign;
  191. while (toalign-- > 0) luaL_addchar(&b, '\0');
  192. switch (opt) {
  193. case 'b': case 'B': case 'h': case 'H':
  194. case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
  195. putinteger(L, &b, arg++, h.endian, size);
  196. break;
  197. }
  198. case 'x': {
  199. luaL_addchar(&b, '\0');
  200. break;
  201. }
  202. #ifndef LUA_NUMBER_INTEGRAL
  203. case 'f': {
  204. float f = (float)luaL_checknumber(L, arg++);
  205. correctbytes((char *)&f, size, h.endian);
  206. luaL_addlstring(&b, (char *)&f, size);
  207. break;
  208. }
  209. case 'd': {
  210. double d = luaL_checknumber(L, arg++);
  211. correctbytes((char *)&d, size, h.endian);
  212. luaL_addlstring(&b, (char *)&d, size);
  213. break;
  214. }
  215. #endif
  216. case 'c': case 's': {
  217. size_t l;
  218. const char *s = luaL_checklstring(L, arg++, &l);
  219. if (size == 0) size = l;
  220. luaL_argcheck(L, l >= (size_t)size, arg, "string too short");
  221. luaL_addlstring(&b, s, size);
  222. if (opt == 's') {
  223. luaL_addchar(&b, '\0'); /* add zero at the end */
  224. size++;
  225. }
  226. break;
  227. }
  228. default: controloptions(L, opt, &fmt, &h);
  229. }
  230. totalsize += size;
  231. }
  232. luaL_pushresult(&b);
  233. return 1;
  234. }
  235. static lua_Number getinteger (const char *buff, int endian,
  236. int issigned, int size) {
  237. Uinttype l = 0;
  238. int i;
  239. if (endian == BIG) {
  240. for (i = 0; i < size; i++) {
  241. l <<= 8;
  242. l |= (Uinttype)(unsigned char)buff[i];
  243. }
  244. }
  245. else {
  246. for (i = size - 1; i >= 0; i--) {
  247. l <<= 8;
  248. l |= (Uinttype)(unsigned char)buff[i];
  249. }
  250. }
  251. if (!issigned)
  252. return (lua_Number)l;
  253. else { /* signed format */
  254. Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1);
  255. if (l & mask) /* negative value? */
  256. l |= mask; /* signal extension */
  257. return (lua_Number)(Inttype)l;
  258. }
  259. }
  260. static int b_unpack (lua_State *L) {
  261. Header h;
  262. const char *fmt = luaL_checkstring(L, 1);
  263. size_t ld;
  264. const char *data = luaL_checklstring(L, 2, &ld);
  265. size_t pos = luaL_optinteger(L, 3, 1) - 1;
  266. defaultoptions(&h);
  267. lua_settop(L, 2);
  268. while (*fmt) {
  269. int opt = *fmt++;
  270. size_t size = optsize(L, opt, &fmt);
  271. pos += gettoalign(pos, &h, opt, size);
  272. luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
  273. luaL_checkstack(L, 2, "too many results");
  274. switch (opt) {
  275. case 'b': case 'B': case 'h': case 'H':
  276. case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
  277. int issigned = islower(opt);
  278. lua_Number res = getinteger(data+pos, h.endian, issigned, size);
  279. lua_pushnumber(L, res);
  280. break;
  281. }
  282. case 'x': {
  283. break;
  284. }
  285. #ifndef LUA_NUMBER_INTEGRAL
  286. case 'f': {
  287. float f;
  288. memcpy(&f, data+pos, size);
  289. correctbytes((char *)&f, sizeof(f), h.endian);
  290. lua_pushnumber(L, f);
  291. break;
  292. }
  293. case 'd': {
  294. double d;
  295. memcpy(&d, data+pos, size);
  296. correctbytes((char *)&d, sizeof(d), h.endian);
  297. lua_pushnumber(L, d);
  298. break;
  299. }
  300. #endif
  301. case 'c': {
  302. if (size == 0) {
  303. if (!lua_isnumber(L, -1))
  304. luaL_error(L, "format `c0' needs a previous size");
  305. size = lua_tonumber(L, -1);
  306. lua_pop(L, 1);
  307. luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
  308. }
  309. lua_pushlstring(L, data+pos, size);
  310. break;
  311. }
  312. case 's': {
  313. const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
  314. if (e == NULL)
  315. luaL_error(L, "unfinished string in data");
  316. size = (e - (data+pos)) + 1;
  317. lua_pushlstring(L, data+pos, size - 1);
  318. break;
  319. }
  320. default: controloptions(L, opt, &fmt, &h);
  321. }
  322. pos += size;
  323. }
  324. lua_pushinteger(L, pos + 1);
  325. return lua_gettop(L) - 2;
  326. }
  327. static int b_size (lua_State *L) {
  328. Header h;
  329. const char *fmt = luaL_checkstring(L, 1);
  330. size_t pos = 0;
  331. defaultoptions(&h);
  332. while (*fmt) {
  333. int opt = *fmt++;
  334. size_t size = optsize(L, opt, &fmt);
  335. pos += gettoalign(pos, &h, opt, size);
  336. if (opt == 's')
  337. luaL_argerror(L, 1, "option 's' has no fixed size");
  338. else if (opt == 'c' && size == 0)
  339. luaL_argerror(L, 1, "option 'c0' has no fixed size");
  340. if (!isalnum(opt))
  341. controloptions(L, opt, &fmt, &h);
  342. pos += size;
  343. }
  344. lua_pushinteger(L, pos);
  345. return 1;
  346. }
  347. /* }====================================================== */
  348. static const LUA_REG_TYPE thislib[] = {
  349. {LSTRKEY("pack"), LFUNCVAL(b_pack)},
  350. {LSTRKEY("unpack"), LFUNCVAL(b_unpack)},
  351. {LSTRKEY("size"), LFUNCVAL(b_size)},
  352. {LNILKEY, LNILVAL}
  353. };
  354. NODEMCU_MODULE(STRUCT, "struct", thislib, NULL);
  355. /******************************************************************************
  356. * Copyright (C) 2010-2012 Lua.org, PUC-Rio. All rights reserved.
  357. *
  358. * Permission is hereby granted, free of charge, to any person obtaining
  359. * a copy of this software and associated documentation files (the
  360. * "Software"), to deal in the Software without restriction, including
  361. * without limitation the rights to use, copy, modify, merge, publish,
  362. * distribute, sublicense, and/or sell copies of the Software, and to
  363. * permit persons to whom the Software is furnished to do so, subject to
  364. * the following conditions:
  365. *
  366. * The above copyright notice and this permission notice shall be
  367. * included in all copies or substantial portions of the Software.
  368. *
  369. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  370. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  371. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  372. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  373. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  374. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  375. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  376. ******************************************************************************/