struct.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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(**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(**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. static void correctbytes (char *b, int size, int endian) {
  166. if (endian != native.endian) {
  167. int i = 0;
  168. while (i < --size) {
  169. char temp = b[i];
  170. b[i++] = b[size];
  171. b[size] = temp;
  172. }
  173. }
  174. }
  175. static int b_pack (lua_State *L) {
  176. luaL_Buffer b;
  177. const char *fmt = luaL_checkstring(L, 1);
  178. Header h;
  179. int arg = 2;
  180. size_t totalsize = 0;
  181. defaultoptions(&h);
  182. lua_pushnil(L); /* mark to separate arguments from string buffer */
  183. luaL_buffinit(L, &b);
  184. while (*fmt != '\0') {
  185. int opt = *fmt++;
  186. size_t size = optsize(L, opt, &fmt);
  187. int toalign = gettoalign(totalsize, &h, opt, size);
  188. totalsize += toalign;
  189. while (toalign-- > 0) luaL_addchar(&b, '\0');
  190. switch (opt) {
  191. case 'b': case 'B': case 'h': case 'H':
  192. case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
  193. putinteger(L, &b, arg++, h.endian, size);
  194. break;
  195. }
  196. case 'x': {
  197. luaL_addchar(&b, '\0');
  198. break;
  199. }
  200. #ifndef LUA_NUMBER_INTEGRAL
  201. case 'f': {
  202. float f = (float)luaL_checknumber(L, arg++);
  203. correctbytes((char *)&f, size, h.endian);
  204. luaL_addlstring(&b, (char *)&f, size);
  205. break;
  206. }
  207. case 'd': {
  208. double d = luaL_checknumber(L, arg++);
  209. correctbytes((char *)&d, size, h.endian);
  210. luaL_addlstring(&b, (char *)&d, size);
  211. break;
  212. }
  213. #endif
  214. case 'c': case 's': {
  215. size_t l;
  216. const char *s = luaL_checklstring(L, arg++, &l);
  217. if (size == 0) size = l;
  218. luaL_argcheck(L, l >= (size_t)size, arg, "string too short");
  219. luaL_addlstring(&b, s, size);
  220. if (opt == 's') {
  221. luaL_addchar(&b, '\0'); /* add zero at the end */
  222. size++;
  223. }
  224. break;
  225. }
  226. default: controloptions(L, opt, &fmt, &h);
  227. }
  228. totalsize += size;
  229. }
  230. luaL_pushresult(&b);
  231. return 1;
  232. }
  233. static lua_Number getinteger (const char *buff, int endian,
  234. int issigned, int size) {
  235. Uinttype l = 0;
  236. int i;
  237. if (endian == BIG) {
  238. for (i = 0; i < size; i++) {
  239. l <<= 8;
  240. l |= (Uinttype)(unsigned char)buff[i];
  241. }
  242. }
  243. else {
  244. for (i = size - 1; i >= 0; i--) {
  245. l <<= 8;
  246. l |= (Uinttype)(unsigned char)buff[i];
  247. }
  248. }
  249. if (!issigned)
  250. return (lua_Number)l;
  251. else { /* signed format */
  252. Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1);
  253. if (l & mask) /* negative value? */
  254. l |= mask; /* signal extension */
  255. return (lua_Number)(Inttype)l;
  256. }
  257. }
  258. static int b_unpack (lua_State *L) {
  259. Header h;
  260. const char *fmt = luaL_checkstring(L, 1);
  261. size_t ld;
  262. const char *data = luaL_checklstring(L, 2, &ld);
  263. size_t pos = luaL_optinteger(L, 3, 1) - 1;
  264. defaultoptions(&h);
  265. lua_settop(L, 2);
  266. while (*fmt) {
  267. int opt = *fmt++;
  268. size_t size = optsize(L, opt, &fmt);
  269. pos += gettoalign(pos, &h, opt, size);
  270. luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
  271. luaL_checkstack(L, 2, "too many results");
  272. switch (opt) {
  273. case 'b': case 'B': case 'h': case 'H':
  274. case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
  275. int issigned = islower(opt);
  276. lua_Number res = getinteger(data+pos, h.endian, issigned, size);
  277. lua_pushnumber(L, res);
  278. break;
  279. }
  280. case 'x': {
  281. break;
  282. }
  283. #ifndef LUA_NUMBER_INTEGRAL
  284. case 'f': {
  285. float f;
  286. memcpy(&f, data+pos, size);
  287. correctbytes((char *)&f, sizeof(f), h.endian);
  288. lua_pushnumber(L, f);
  289. break;
  290. }
  291. case 'd': {
  292. double d;
  293. memcpy(&d, data+pos, size);
  294. correctbytes((char *)&d, sizeof(d), h.endian);
  295. lua_pushnumber(L, d);
  296. break;
  297. }
  298. #endif
  299. case 'c': {
  300. if (size == 0) {
  301. if (!lua_isnumber(L, -1))
  302. luaL_error(L, "format `c0' needs a previous size");
  303. size = lua_tonumber(L, -1);
  304. lua_pop(L, 1);
  305. luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
  306. }
  307. lua_pushlstring(L, data+pos, size);
  308. break;
  309. }
  310. case 's': {
  311. const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
  312. if (e == NULL)
  313. luaL_error(L, "unfinished string in data");
  314. size = (e - (data+pos)) + 1;
  315. lua_pushlstring(L, data+pos, size - 1);
  316. break;
  317. }
  318. default: controloptions(L, opt, &fmt, &h);
  319. }
  320. pos += size;
  321. }
  322. lua_pushinteger(L, pos + 1);
  323. return lua_gettop(L) - 2;
  324. }
  325. static int b_size (lua_State *L) {
  326. Header h;
  327. const char *fmt = luaL_checkstring(L, 1);
  328. size_t pos = 0;
  329. defaultoptions(&h);
  330. while (*fmt) {
  331. int opt = *fmt++;
  332. size_t size = optsize(L, opt, &fmt);
  333. pos += gettoalign(pos, &h, opt, size);
  334. if (opt == 's')
  335. luaL_argerror(L, 1, "option 's' has no fixed size");
  336. else if (opt == 'c' && size == 0)
  337. luaL_argerror(L, 1, "option 'c0' has no fixed size");
  338. if (!isalnum(opt))
  339. controloptions(L, opt, &fmt, &h);
  340. pos += size;
  341. }
  342. lua_pushinteger(L, pos);
  343. return 1;
  344. }
  345. /* }====================================================== */
  346. static const LUA_REG_TYPE thislib[] = {
  347. {LSTRKEY("pack"), LFUNCVAL(b_pack)},
  348. {LSTRKEY("unpack"), LFUNCVAL(b_unpack)},
  349. {LSTRKEY("size"), LFUNCVAL(b_size)},
  350. {LNILKEY, LNILVAL}
  351. };
  352. NODEMCU_MODULE(STRUCT, "struct", thislib, NULL);
  353. /******************************************************************************
  354. * Copyright (C) 2010-2012 Lua.org, PUC-Rio. All rights reserved.
  355. *
  356. * Permission is hereby granted, free of charge, to any person obtaining
  357. * a copy of this software and associated documentation files (the
  358. * "Software"), to deal in the Software without restriction, including
  359. * without limitation the rights to use, copy, modify, merge, publish,
  360. * distribute, sublicense, and/or sell copies of the Software, and to
  361. * permit persons to whom the Software is furnished to do so, subject to
  362. * the following conditions:
  363. *
  364. * The above copyright notice and this permission notice shall be
  365. * included in all copies or substantial portions of the Software.
  366. *
  367. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  368. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  369. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  370. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  371. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  372. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  373. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  374. ******************************************************************************/