aboutsummaryrefslogtreecommitdiff
path: root/lbitlib.c
blob: 3aaec22949830dfc940deb131fb0b581bde520dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
** $Id: lbitlib.c,v 1.1 2009/07/01 16:17:08 roberto Exp roberto $
** Standard library for bitwise operations
** See Copyright Notice in lua.h
*/

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"


/* number of bits considered when shifting/rotating (must be a power of 2) */
#define NBITS	32


typedef LUA_INT32 b_int;
typedef unsigned LUA_INT32 b_uint;


static b_uint getuintarg (lua_State *L, int arg) {
  b_uint r;
  lua_Number x = lua_tonumber(L, arg);
  if (x == 0) luaL_checktype(L, arg, LUA_TNUMBER);
  lua_number2uint(r, x);
  return r;
}


static b_uint andaux (lua_State *L) {
  int i, n = lua_gettop(L);
  b_uint r = ~(b_uint)0;
  for (i = 1; i <= n; i++)
    r &= getuintarg(L, i);
  return r;
}


static int b_and (lua_State *L) {
  b_uint r = andaux(L);
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static int b_test (lua_State *L) {
  b_uint r = andaux(L);
  lua_pushboolean(L, r != 0);
  return 1;
}


static int b_or (lua_State *L) {
  int i, n = lua_gettop(L);
  b_uint r = 0;
  for (i = 1; i <= n; i++)
    r |= getuintarg(L, i);
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static int b_xor (lua_State *L) {
  int i, n = lua_gettop(L);
  b_uint r = 0;
  for (i = 1; i <= n; i++)
    r ^= getuintarg(L, i);
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static int b_not (lua_State *L) {
  b_uint r = ~getuintarg(L, 1);
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static int b_shift (lua_State *L) {
  b_uint r = getuintarg(L, 1);
  lua_Integer i = luaL_checkinteger(L, 2);
  if (i < 0) {  /* shift right? */
    i = -i;
    if (i >= NBITS) r = 0;
    else r >>= i;
  }
  else {  /* shift left */
    if (i >= NBITS) r = 0;
    else r <<= i;
  }
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static int b_rotate (lua_State *L) {
  b_uint r = getuintarg(L, 1);
  lua_Integer i = luaL_checkinteger(L, 2);
  i &= (NBITS - 1);  /* i = i % NBITS */
  r = (r << i) | (r >> (NBITS - i));
  lua_pushnumber(L, lua_uint2number(r));
  return 1;
}


static const luaL_Reg bitlib[] = {
  {"band", b_and},
  {"btest", b_test},
  {"bor", b_or},
  {"bxor", b_xor},
  {"bnot", b_not},
  {"bshift", b_shift},
  {"brotate", b_rotate},
  {NULL, NULL}
};



LUAMOD_API int luaopen_bit (lua_State *L) {
  luaL_register(L, LUA_BITLIBNAME, bitlib);
  return 1;
}