Commit 5b6e2902 authored by Jaromil's avatar Jaromil
Browse files

import octet from binary string sequence

parent 83597e51
......@@ -4,7 +4,7 @@ function hex(data) return octet.hex(data) end
function str(data) return octet.string(data) end
function base64(data) return octet.base64(data) end
function base58(data) return octet.base58(data) end
function bin(data) return octet.bin(data) end
function zero(len) return octet.new(len):zero(len) end
return octet
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -17,6 +17,7 @@ void *zalloc(lua_State *L, size_t size);
#define HEREs(s) func(0, "-> %s(%s)",__func__,s)
#define HEREp(p) func(0, "-> %s(%p)",__func__,p)
#define HEREn(n) func(0, "-> %s(%i)",__func__,n)
#define HEREc(c) func(0, "-> %s(%c)",__func__,c)
#define HEREoct(o) \
func(0, "-> %s - octet %p (%i/%i)",__func__,o->val,o->len,o->max)
#define HEREecdh(e) \
......
......@@ -108,6 +108,16 @@ int is_hex(const char *in) {
return c;
}
int is_bin(const char *in) {
if(!in) { ERROR(); return 0; }
int c;
for(c=0; in[c]!='\0'; c++) {
if (in[c]!='0' && in[c]!='1') {
ERROR(); return 0; }
}
return c;
}
// REMEMBER: newuserdata already pushes the object in lua's stack
octet* o_new(lua_State *L, const int size) {
if(size<=0) return NULL;
......@@ -276,6 +286,30 @@ static int from_hex(lua_State *L) {
return 1;
}
static int from_bin(lua_State *L) {
const char *s = lua_tostring(L, 1);
luaL_argcheck(L, s != NULL, 1, "binary string sequence expected");
int len = is_bin(s);
int bytes = len/8; // TODO: check that len is mult of 8 (no carry)
if(!len || bytes>MAX_STRING) {
lerror(L, "invalid binary sequence size: %u", bytes);
return 0; }
octet *o = o_new(L, bytes+1);
int i,j;
uint8_t b;
for(i=0; i<len; i+=8) {
b = 0x0;
for(j=0;j<8;++j) {
if(s[i+j]=='1') b = b | 0x1;
b <<= 1;
}
o->val[i/8] = b>>1;
}
o->val[bytes] = 0x0;
o->len = bytes;
return 1;
}
/***
Concatenate two octets, returns a new octet. This is also executed
when using the '<b>..</b>' operator btween two octets. It results in a
......@@ -473,7 +507,7 @@ static int to_hex(lua_State *L) {
static int to_bin(lua_State *L) {
octet *o = o_arg(L,1); SAFE(o);
char *s = zen_memory_alloc(o->len*8+2);
int i, j;
int i;
char oo;
char *is = s;
for(i=0;i<o->len;i++) {
......@@ -488,6 +522,7 @@ static int to_bin(lua_State *L) {
is[1] = oo>>6 & 0x1 ? '1':'0';
is[0] = oo>>7 & 0x1 ? '1':'0';
}
s[o->len*8] = 0x0;
lua_pushstring(L,s);
zen_memory_free(s);
return(1);
......@@ -572,6 +607,7 @@ int luaopen_octet(lua_State *L) {
{"base58",from_base58},
{"string",from_string},
{"hex",from_hex},
{"bin",from_bin},
{NULL,NULL}
};
const struct luaL_Reg octet_methods[] = {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment