1
Fork 0
turbonss/src/bdz.zig

31 lines
1.2 KiB
Zig

const std = @import("std");
extern fn bdz_search_packed(packed_mphf: [*]const u8, key: [*]const u8, len: c_uint) u32;
pub fn search(packed_mphf: []const u8, key: []const u8) u32 {
const len = std.math.cast(c_uint, key.len).?;
return @as(u32, bdz_search_packed(packed_mphf[4..].ptr, key.ptr, len));
}
const u32len = 5;
pub fn search_u32(packed_mphf: []const u8, key: u32) u32 {
return @as(u32, bdz_search_packed(packed_mphf[4..].ptr, &unzero(key), u32len));
}
// encode a u32 to 5 bytes so no bytes is a '\0'.
//
// TODO(motiejus) figure out how to use cmph_io_byte_vector_adapter, so cmph
// packing would accept zero bytes. For now we will be doing a dance of not
// passing zero bytes.
pub fn unzero(x: u32) [5]u8 {
const bit: u8 = 0b10000000;
var buf: [u32len]u8 = undefined;
buf[0] = @truncate(u8, (x & 0b11111110_00000000_00000000_00000000) >> 25) | bit;
buf[1] = @truncate(u8, (x & 0b00000001_11111100_00000000_00000000) >> 18) | bit;
buf[2] = @truncate(u8, (x & 0b00000000_00000011_11110000_00000000) >> 12) | bit;
buf[3] = @truncate(u8, (x & 0b00000000_00000000_00001111_11000000) >> 6) | bit;
buf[4] = @truncate(u8, (x & 0b00000000_00000000_00000000_00111111) >> 0) | bit;
return buf;
}