From 7f748556a2e4bc189bc994707138d129af2100a4 Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Fri, 23 Feb 2024 12:08:37 +0000 Subject: util.strbitop: Add common_prefix_bits() method This returns the number of bits that two strings have in common. It is significantly more efficient than similar calculations in Lua. --- util-src/strbitop.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'util-src') diff --git a/util-src/strbitop.c b/util-src/strbitop.c index 75cfea81..2f6bf6e6 100644 --- a/util-src/strbitop.c +++ b/util-src/strbitop.c @@ -8,6 +8,8 @@ #include #include +#include +#include /* TODO Deduplicate code somehow */ @@ -74,11 +76,46 @@ static int strop_xor(lua_State *L) { return 1; } +unsigned int clz(unsigned char c) { +#if __GNUC__ + return __builtin_clz((unsigned int) c) - ((sizeof(int)-1)*CHAR_BIT); +#else + if(c & 0x80) return 0; + if(c & 0x40) return 1; + if(c & 0x20) return 2; + if(c & 0x10) return 3; + if(c & 0x08) return 4; + if(c & 0x04) return 5; + if(c & 0x02) return 6; + if(c & 0x01) return 7; + return 8; +#endif +} + +LUA_API int strop_common_prefix_bits(lua_State *L) { + size_t a, b, i; + const char *str_a = luaL_checklstring(L, 1, &a); + const char *str_b = luaL_checklstring(L, 2, &b); + + size_t min_len = MIN(a, b); + + for(i=0; i