/* Unpack an integer with 'size' bytes and 'islittle' endianness. If size is smaller than the size of a Lua integer and integer is signed, must do sign extension (propagating the sign to the higher bits); if size is larger than the size of a Lua integer, it must check the unread bytes to see whether they do not cause an overflow.  */
static lua_Integer unpackint(lua_State *L, const char *str, int islittle, int size, int issigned)
/* Unpack an integer with 'size' bytes and 'islittle' endianness. If size is smaller than the size of a Lua integer and integer is signed, must do sign extension (propagating the sign to the higher bits); if size is larger than the size of a Lua integer, it must check the unread bytes to see whether they do not cause an overflow.  */
static lua_Integer unpackint(lua_State *L, const char *str, int islittle, int size, int issigned)
{
  lua_Unsigned res = 0;
  int i;
  int limit = (size  <= SZINT) ? size : SZINT;
  for (i = limit - 1; i >= 0; i--) {
    res <<= NB;
    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  }
  if (size < SZINT) {
    if (issigned) {
      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
      res = ((res ^ mask) - mask);
    }
  }
  else if (size > SZINT) {
    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
    for (i = limit; i < size; i++) {
      if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
        luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
    }
  }
  return (lua_Integer)res;
}