Skip to content

Commit

Permalink
Move leb128 stuff to Rust
Browse files Browse the repository at this point in the history
  • Loading branch information
osa1 committed Dec 25, 2020
1 parent fd013f2 commit 6d214c0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 30 deletions.
32 changes: 32 additions & 0 deletions rts/motoko-rts/src/leb128.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! LEB1128 encoding. Reference: https://en.wikipedia.org/wiki/LEB128

#[no_mangle]
unsafe extern "C" fn leb128_encode(mut val: u32, mut buf: *mut u8) {
loop {
let byte = (val & 0b0111_1111) as u8;
val >>= 7;
if val == 0 {
*buf = byte;
break;
} else {
*buf = byte | 0b1000_0000;
buf = buf.add(1);
}
}
}

#[no_mangle]
unsafe extern "C" fn sleb128_encode(mut val: i32, mut buf: *mut u8) {
loop {
let byte = (val & 0b0111_1111) as u8;
val >>= 7;
if (val == 0 && byte & 0b0100_0000 == 0) || (val == -1 && byte & 0b0100_0000 == 0b0100_0000)
{
*buf = byte;
break;
} else {
*buf = byte | 0b1000_0000;
buf = buf.add(1);
}
}
}
1 change: 1 addition & 0 deletions rts/motoko-rts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod buf;
mod char;
pub mod closure_table;
mod debug;
mod leb128;
mod mem;
mod text;
mod text_iter;
Expand Down
30 changes: 0 additions & 30 deletions rts/rts.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,33 +30,3 @@ as_ptr get_version() { return text_of_cstr(RTS_VERSION); }
as_ptr (*version_getter)() = &get_version;

export as_ptr version() { return (*version_getter)(); }

/* (S)LEB128 Encoding of words */

export void leb128_encode(uint32_t n, unsigned char *buf) {
while (true) {
buf[0] = (unsigned char)n; // get low bits
if (n >>= 7) {
// more bytes to come, set high bit and continue
buf[0] |= 1<<7;
buf++;
} else {
// we are done. high bit should be cleared anyway
return;
}
}
}

export void sleb128_encode(int32_t n, unsigned char *buf) {
while (true) {
*buf = n & 0x7F; // get low bits
if (n >= -64 && n < 64) {
// last byte written, high bit is clear
return;
} else {
// more bytes to come, set high bit and continue
*buf++ |= 0x80;
n >>= 7;
}
}
}

0 comments on commit 6d214c0

Please sign in to comment.