lua_struct.c 11.1 KB
Newer Older
L
lsbardel 已提交
1 2 3
/*
** {======================================================
** Library for packing/unpacking structures.
4
** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $
L
lsbardel 已提交
5 6 7 8 9 10 11 12 13 14 15 16
** See Copyright Notice at the end of this file
** =======================================================
*/
/*
** Valid formats:
** > - big endian
** < - little endian
** ![num] - alignment
** x - pading
** b/B - signed/unsigned byte
** h/H - signed/unsigned short
** l/L - signed/unsigned long
17
** T   - size_t
18 19
** i/In - signed/unsigned integer with size 'n' (default is size of int)
** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means
L
lsbardel 已提交
20 21 22 23 24 25 26 27 28
        the whole string; when unpacking, n==0 means use the previous
        read number as the string length
** s - zero-terminated string
** f - float
** d - double
** ' ' - ignored
*/


29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>


#include "lua.h"
#include "lauxlib.h"


#if (LUA_VERSION_NUM >= 502)

#define luaL_register(L,n,f)	luaL_newlib(L,f)

#endif


/* basic integer type */
#if !defined(STRUCT_INT)
#define STRUCT_INT	long
#endif

typedef STRUCT_INT Inttype;

/* corresponding unsigned version */
typedef unsigned STRUCT_INT Uinttype;


/* maximum size (in bytes) for integral types */
#define MAXINTSIZE	32

L
lsbardel 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
/* is 'x' a power of 2? */
#define isp2(x)		((x) > 0 && ((x) & ((x) - 1)) == 0)

/* dummy structure to get alignment requirements */
struct cD {
  char c;
  double d;
};


#define PADDING		(sizeof(struct cD) - sizeof(double))
#define MAXALIGN  	(PADDING > sizeof(int) ? PADDING : sizeof(int))


/* endian options */
#define BIG	0
#define LITTLE	1


static union {
  int dummy;
  char endian;
} const native = {1};


typedef struct Header {
  int endian;
  int align;
} Header;


92
static int getnum (const char **fmt, int df) {
L
lsbardel 已提交
93 94 95
  if (!isdigit(**fmt))  /* no number? */
    return df;  /* return default value */
  else {
96
    int a = 0;
L
lsbardel 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    do {
      a = a*10 + *((*fmt)++) - '0';
    } while (isdigit(**fmt));
    return a;
  }
}


#define defaultoptions(h)	((h)->endian = native.endian, (h)->align = 1)



static size_t optsize (lua_State *L, char opt, const char **fmt) {
  switch (opt) {
    case 'B': case 'b': return sizeof(char);
    case 'H': case 'h': return sizeof(short);
    case 'L': case 'l': return sizeof(long);
114
    case 'T': return sizeof(size_t);
L
lsbardel 已提交
115 116 117
    case 'f':  return sizeof(float);
    case 'd':  return sizeof(double);
    case 'x': return 1;
118
    case 'c': return getnum(fmt, 1);
L
lsbardel 已提交
119
    case 'i': case 'I': {
120
      int sz = getnum(fmt, sizeof(int));
121 122 123
      if (sz > MAXINTSIZE)
        luaL_error(L, "integral size %d is larger than limit of %d",
                       sz, MAXINTSIZE);
L
lsbardel 已提交
124 125
      return sz;
    }
126
    default: return 0;  /* other cases do not need alignment */
L
lsbardel 已提交
127 128 129 130
  }
}


131 132 133 134
/*
** return number of bytes needed to align an element of size 'size'
** at current position 'len'
*/
L
lsbardel 已提交
135 136
static int gettoalign (size_t len, Header *h, int opt, size_t size) {
  if (size == 0 || opt == 'c') return 0;
137 138 139
  if (size > (size_t)h->align)
    size = h->align;  /* respect max. alignment */
  return (size - (len & (size - 1))) & (size - 1);
L
lsbardel 已提交
140 141 142
}


143 144 145 146 147
/*
** options to control endianess and alignment
*/
static void controloptions (lua_State *L, int opt, const char **fmt,
                            Header *h) {
L
lsbardel 已提交
148 149 150 151 152
  switch (opt) {
    case  ' ': return;  /* ignore white spaces */
    case '>': h->endian = BIG; return;
    case '<': h->endian = LITTLE; return;
    case '!': {
153
      int a = getnum(fmt, MAXALIGN);
L
lsbardel 已提交
154 155 156 157 158
      if (!isp2(a))
        luaL_error(L, "alignment %d is not a power of 2", a);
      h->align = a;
      return;
    }
159 160 161 162
    default: {
      const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt);
      luaL_argerror(L, 1, msg);
    }
L
lsbardel 已提交
163 164 165 166 167 168 169
  }
}


static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian,
                        int size) {
  lua_Number n = luaL_checknumber(L, arg);
170 171 172 173
  Uinttype value;
  char buff[MAXINTSIZE];
  if (n < 0)
    value = (Uinttype)(Inttype)n;
L
lsbardel 已提交
174
  else
175
    value = (Uinttype)n;
L
lsbardel 已提交
176 177
  if (endian == LITTLE) {
    int i;
178 179 180 181
    for (i = 0; i < size; i++) {
      buff[i] = (value & 0xff);
      value >>= 8;
    }
L
lsbardel 已提交
182 183 184
  }
  else {
    int i;
185 186 187 188
    for (i = size - 1; i >= 0; i--) {
      buff[i] = (value & 0xff);
      value >>= 8;
    }
L
lsbardel 已提交
189
  }
190
  luaL_addlstring(b, buff, size);
L
lsbardel 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
}


static void correctbytes (char *b, int size, int endian) {
  if (endian != native.endian) {
    int i = 0;
    while (i < --size) {
      char temp = b[i];
      b[i++] = b[size];
      b[size] = temp;
    }
  }
}


static int b_pack (lua_State *L) {
  luaL_Buffer b;
  const char *fmt = luaL_checkstring(L, 1);
  Header h;
  int arg = 2;
  size_t totalsize = 0;
  defaultoptions(&h);
  lua_pushnil(L);  /* mark to separate arguments from string buffer */
  luaL_buffinit(L, &b);
  while (*fmt != '\0') {
    int opt = *fmt++;
    size_t size = optsize(L, opt, &fmt);
    int toalign = gettoalign(totalsize, &h, opt, size);
    totalsize += toalign;
220
    while (toalign-- > 0) luaL_addchar(&b, '\0');
L
lsbardel 已提交
221 222
    switch (opt) {
      case 'b': case 'B': case 'h': case 'H':
223
      case 'l': case 'L': case 'T': case 'i': case 'I': {  /* integer types */
L
lsbardel 已提交
224 225 226 227
        putinteger(L, &b, arg++, h.endian, size);
        break;
      }
      case 'x': {
228
        luaL_addchar(&b, '\0');
L
lsbardel 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        break;
      }
      case 'f': {
        float f = (float)luaL_checknumber(L, arg++);
        correctbytes((char *)&f, size, h.endian);
        luaL_addlstring(&b, (char *)&f, size);
        break;
      }
      case 'd': {
        double d = luaL_checknumber(L, arg++);
        correctbytes((char *)&d, size, h.endian);
        luaL_addlstring(&b, (char *)&d, size);
        break;
      }
      case 'c': case 's': {
        size_t l;
        const char *s = luaL_checklstring(L, arg++, &l);
        if (size == 0) size = l;
        luaL_argcheck(L, l >= (size_t)size, arg, "string too short");
        luaL_addlstring(&b, s, size);
        if (opt == 's') {
250
          luaL_addchar(&b, '\0');  /* add zero at the end */
L
lsbardel 已提交
251 252 253 254
          size++;
        }
        break;
      }
255
      default: controloptions(L, opt, &fmt, &h);
L
lsbardel 已提交
256 257 258 259 260 261 262 263 264 265
    }
    totalsize += size;
  }
  luaL_pushresult(&b);
  return 1;
}


static lua_Number getinteger (const char *buff, int endian,
                        int issigned, int size) {
266 267
  Uinttype l = 0;
  int i;
L
lsbardel 已提交
268
  if (endian == BIG) {
269 270 271 272
    for (i = 0; i < size; i++) {
      l <<= 8;
      l |= (Uinttype)(unsigned char)buff[i];
    }
L
lsbardel 已提交
273 274
  }
  else {
275 276 277 278
    for (i = size - 1; i >= 0; i--) {
      l <<= 8;
      l |= (Uinttype)(unsigned char)buff[i];
    }
L
lsbardel 已提交
279 280 281 282
  }
  if (!issigned)
    return (lua_Number)l;
  else {  /* signed format */
283
    Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1);
L
lsbardel 已提交
284 285
    if (l & mask)  /* negative value? */
      l |= mask;  /* signal extension */
286
    return (lua_Number)(Inttype)l;
L
lsbardel 已提交
287 288 289 290 291 292 293 294 295
  }
}


static int b_unpack (lua_State *L) {
  Header h;
  const char *fmt = luaL_checkstring(L, 1);
  size_t ld;
  const char *data = luaL_checklstring(L, 2, &ld);
296 297 298 299
  size_t pos = luaL_optinteger(L, 3, 1);
  luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater");
  pos--; /* Lua indexes are 1-based, but here we want 0-based for C
          * pointer math. */
300
  int n = 0;  /* number of results */
L
lsbardel 已提交
301 302 303 304 305
  defaultoptions(&h);
  while (*fmt) {
    int opt = *fmt++;
    size_t size = optsize(L, opt, &fmt);
    pos += gettoalign(pos, &h, opt, size);
306 307
    luaL_argcheck(L, size <= ld && pos <= ld - size,
                   2, "data string too short");
308 309
    /* stack space for item + next position */
    luaL_checkstack(L, 2, "too many results");
L
lsbardel 已提交
310 311
    switch (opt) {
      case 'b': case 'B': case 'h': case 'H':
312
      case 'l': case 'L': case 'T': case 'i':  case 'I': {  /* integer types */
L
lsbardel 已提交
313 314
        int issigned = islower(opt);
        lua_Number res = getinteger(data+pos, h.endian, issigned, size);
315
        lua_pushnumber(L, res); n++;
L
lsbardel 已提交
316 317 318 319 320 321 322 323 324
        break;
      }
      case 'x': {
        break;
      }
      case 'f': {
        float f;
        memcpy(&f, data+pos, size);
        correctbytes((char *)&f, sizeof(f), h.endian);
325
        lua_pushnumber(L, f); n++;
L
lsbardel 已提交
326 327 328 329 330 331
        break;
      }
      case 'd': {
        double d;
        memcpy(&d, data+pos, size);
        correctbytes((char *)&d, sizeof(d), h.endian);
332
        lua_pushnumber(L, d); n++;
L
lsbardel 已提交
333 334 335 336
        break;
      }
      case 'c': {
        if (size == 0) {
337 338
          if (n == 0 || !lua_isnumber(L, -1))
            luaL_error(L, "format 'c0' needs a previous size");
L
lsbardel 已提交
339
          size = lua_tonumber(L, -1);
340 341 342
          lua_pop(L, 1); n--;
          luaL_argcheck(L, size <= ld && pos <= ld - size,
                           2, "data string too short");
L
lsbardel 已提交
343
        }
344
        lua_pushlstring(L, data+pos, size); n++;
L
lsbardel 已提交
345 346 347 348 349 350 351
        break;
      }
      case 's': {
        const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
        if (e == NULL)
          luaL_error(L, "unfinished string in data");
        size = (e - (data+pos)) + 1;
352
        lua_pushlstring(L, data+pos, size - 1); n++;
L
lsbardel 已提交
353 354
        break;
      }
355
      default: controloptions(L, opt, &fmt, &h);
L
lsbardel 已提交
356 357 358
    }
    pos += size;
  }
359 360
  lua_pushinteger(L, pos + 1);  /* next position */
  return n + 1;
L
lsbardel 已提交
361 362
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

static int b_size (lua_State *L) {
  Header h;
  const char *fmt = luaL_checkstring(L, 1);
  size_t pos = 0;
  defaultoptions(&h);
  while (*fmt) {
    int opt = *fmt++;
    size_t size = optsize(L, opt, &fmt);
    pos += gettoalign(pos, &h, opt, size);
    if (opt == 's')
      luaL_argerror(L, 1, "option 's' has no fixed size");
    else if (opt == 'c' && size == 0)
      luaL_argerror(L, 1, "option 'c0' has no fixed size");
    if (!isalnum(opt))
      controloptions(L, opt, &fmt, &h);
    pos += size;
  }
  lua_pushinteger(L, pos);
  return 1;
}

L
lsbardel 已提交
385 386 387 388
/* }====================================================== */



389
static const struct luaL_Reg thislib[] = {
L
lsbardel 已提交
390 391
  {"pack", b_pack},
  {"unpack", b_unpack},
392
  {"size", b_size},
L
lsbardel 已提交
393 394 395 396
  {NULL, NULL}
};


397 398
LUALIB_API int luaopen_struct (lua_State *L);

L
lsbardel 已提交
399 400 401 402 403 404 405
LUALIB_API int luaopen_struct (lua_State *L) {
  luaL_register(L, "struct", thislib);
  return 1;
}


/******************************************************************************
406
* Copyright (C) 2010-2018 Lua.org, PUC-Rio.  All rights reserved.
L
lsbardel 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
427