Skip to main content

luaur_repl_cli/functions/
write.rs

1use core::ffi::c_char;
2
3#[repr(C)]
4pub enum luarequire_WriteResult {
5    WRITE_SUCCESS = 0,
6    WRITE_BUFFER_TOO_SMALL = 1,
7    WRITE_FAILURE = 2,
8}
9
10pub unsafe fn write(
11    contents: *const core::ffi::c_void,
12    buffer: *mut c_char,
13    buffer_size: usize,
14    size_out: *mut usize,
15) -> luarequire_WriteResult {
16    if contents.is_null() {
17        return luarequire_WriteResult::WRITE_FAILURE;
18    }
19
20    let s = contents as *const alloc::string::String;
21    let contents = &*s;
22
23    let null_terminated_size = contents.len() + 1;
24
25    if buffer_size < null_terminated_size {
26        if !size_out.is_null() {
27            *size_out = null_terminated_size;
28        }
29        return luarequire_WriteResult::WRITE_BUFFER_TOO_SMALL;
30    }
31
32    if !buffer.is_null() {
33        let src = contents.as_bytes();
34        let dst = core::slice::from_raw_parts_mut(buffer as *mut u8, null_terminated_size);
35        dst[..src.len()].copy_from_slice(src);
36        dst[src.len()] = 0;
37    }
38
39    if !size_out.is_null() {
40        *size_out = null_terminated_size;
41    }
42
43    luarequire_WriteResult::WRITE_SUCCESS
44}