luaur_bytecode/methods/bytecode_builder_get_string_hash.rs
1use crate::records::string_ref::StringRef;
2
3pub fn bytecode_builder_get_string_hash(key: StringRef) -> u32 {
4 // Keep in sync with Lua 5.1's original hashing algorithm:
5 // https://github.com/lua/lua/blob/v5.1.5/lstrlib.c (luaS_hash for short inputs)
6 //
7 // We intentionally omit long string processing for simplicity/independence
8 // (matching the source logic).
9 let str_ptr = key.data;
10 let len = key.length;
11
12 let mut h: u32 = len as u32;
13
14 unsafe {
15 let bytes = core::slice::from_raw_parts(str_ptr as *const u8, len as usize);
16 for i in (0..len).rev() {
17 let ch = bytes[i as usize] as u32;
18 h ^= (h << 5).wrapping_add(h >> 2).wrapping_add(ch);
19 }
20 }
21
22 h
23}