Skip to main content

luaur_bytecode/methods/
bytecode_builder_write_string_table.rs

1use crate::functions::write_var_int::writeVarInt;
2use crate::records::bytecode_builder::BytecodeBuilder;
3use crate::records::string_ref::StringRef;
4use alloc::string::String;
5use alloc::vec::Vec;
6use luaur_common::macros::luau_assert::LUAU_ASSERT;
7
8impl BytecodeBuilder {
9    pub(crate) fn write_string_table(&self, ss: &mut String) {
10        let count = self.string_table.size();
11        let mut strings: Vec<StringRef> = Vec::with_capacity(count);
12        unsafe {
13            strings.set_len(count);
14        }
15
16        for (string_ref, &index) in self.string_table.iter() {
17            LUAU_ASSERT!(index > 0 && (index as usize) <= strings.len());
18            strings[index as usize - 1] = *string_ref;
19        }
20
21        writeVarInt(ss, strings.len() as u64);
22
23        for s in strings {
24            writeVarInt(ss, s.length as u64);
25            let data = unsafe { core::slice::from_raw_parts(s.data as *const u8, s.length) };
26            // Safety: ss is an alloc::string::String, which is a wrapper around Vec<u8> that guarantees UTF-8.
27            // However, Luau bytecode strings are raw byte buffers. In the Rust port, BytecodeBuilder::bytecode
28            // and the ss parameter are Strings, but they are treated as byte buffers (binary data).
29            unsafe {
30                ss.as_mut_vec().extend_from_slice(data);
31            }
32        }
33    }
34}