Skip to content

Instantly share code, notes, and snippets.

@Robbepop
Last active June 17, 2023 20:31
Show Gist options
  • Save Robbepop/3173b3f2e3eb4632e1771cbacecec7af to your computer and use it in GitHub Desktop.
Save Robbepop/3173b3f2e3eb4632e1771cbacecec7af to your computer and use it in GitHub Desktop.
Codec that might be useful for `wasmi` register machine encoding of 64-bit values embedded in the instruction sequence consisting of 8-byte instruction words with 6-bytes parameter per instruction word optimized for WebAssembly execution.
#[derive(Copy, Clone)]
pub struct Bytes2(u16);
#[derive(Copy, Clone)]
pub struct Bytes6(u16, u32);
pub fn encode_u64(value: u64) -> (Bytes2, Bytes6) {
let lo_lo = (value >> 48 & 0xFFFF) as u16;
let lo_hi = (value >> 32 & 0xFFFF) as u16;
let hi = (value & 0xFFFF_FFFF) as u32;
(Bytes2(lo_lo), Bytes6(lo_hi, hi))
}
pub fn decode_u64(bytes2: Bytes2, bytes6: Bytes6) -> u64 {
((bytes2.0 as u64) << 48) |
((bytes6.0 as u64) << 32) |
(bytes6.1 as u64)
}
example::encode_u64:
mov rax, rdi
mov rcx, rsi
shr rcx, 48
mov word ptr [rdi], cx
mov dword ptr [rdi + 4], esi
shr rsi, 32
mov word ptr [rdi + 8], si
ret
example::decode_u64:
shl rdi, 48
movzx ecx, dx
shl rcx, 32
or rcx, rdi
mov eax, esi
or rax, rcx
ret
example::encode_u64:
local.get 0
local.get 1
i64.store32 4
local.get 0
i32.const 8
i32.add
local.get 1
i64.const 32
i64.shr_u
i64.store16 0
local.get 0
local.get 1
i64.const 48
i64.shr_u
i64.store16 0
end_function
example::decode_u64:
local.get 2
i64.extend_i32_u
i64.const 65535
i64.and
i64.const 32
i64.shl
local.get 0
i64.extend_i32_u
i64.const 48
i64.shl
i64.or
local.get 1
i64.extend_i32_u
i64.or
end_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment