1/*
2** Bit manipulation library.
3** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#define lib_bit_c
7#define LUA_LIB
8
9#include "lua.h"
10#include "lauxlib.h"
11#include "lualib.h"
12
13#include "lj_obj.h"
14#include "lj_err.h"
15#include "lj_str.h"
16#include "lj_lib.h"
17
18/* ------------------------------------------------------------------------ */
19
20#define LJLIB_MODULE_bit
21
22LJLIB_ASM(bit_tobit) LJLIB_REC(bit_unary IR_TOBIT)
23{
24 lj_lib_checknumber(L, 1);
25 return FFH_RETRY;
26}
27LJLIB_ASM_(bit_bnot) LJLIB_REC(bit_unary IR_BNOT)
28LJLIB_ASM_(bit_bswap) LJLIB_REC(bit_unary IR_BSWAP)
29
30LJLIB_ASM(bit_lshift) LJLIB_REC(bit_shift IR_BSHL)
31{
32 lj_lib_checknumber(L, 1);
33 lj_lib_checkbit(L, 2);
34 return FFH_RETRY;
35}
36LJLIB_ASM_(bit_rshift) LJLIB_REC(bit_shift IR_BSHR)
37LJLIB_ASM_(bit_arshift) LJLIB_REC(bit_shift IR_BSAR)
38LJLIB_ASM_(bit_rol) LJLIB_REC(bit_shift IR_BROL)
39LJLIB_ASM_(bit_ror) LJLIB_REC(bit_shift IR_BROR)
40
41LJLIB_ASM(bit_band) LJLIB_REC(bit_nary IR_BAND)
42{
43 int i = 0;
44 do { lj_lib_checknumber(L, ++i); } while (L->base+i < L->top);
45 return FFH_RETRY;
46}
47LJLIB_ASM_(bit_bor) LJLIB_REC(bit_nary IR_BOR)
48LJLIB_ASM_(bit_bxor) LJLIB_REC(bit_nary IR_BXOR)
49
50/* ------------------------------------------------------------------------ */
51
52LJLIB_CF(bit_tohex)
53{
54 uint32_t b = (uint32_t)lj_lib_checkbit(L, 1);
55 int32_t i, n = L->base+1 >= L->top ? 8 : lj_lib_checkbit(L, 2);
56 const char *hexdigits = "0123456789abcdef";
57 char buf[8];
58 if (n < 0) { n = -n; hexdigits = "0123456789ABCDEF"; }
59 if (n > 8) n = 8;
60 for (i = n; --i >= 0; ) { buf[i] = hexdigits[b & 15]; b >>= 4; }
61 lua_pushlstring(L, buf, (size_t)n);
62 return 1;
63}
64
65/* ------------------------------------------------------------------------ */
66
67#include "lj_libdef.h"
68
69LUALIB_API int luaopen_bit(lua_State *L)
70{
71 LJ_LIB_REG(L, LUA_BITLIBNAME, bit);
72 return 1;
73}
74
75