I have a block of variable-width data in a page that I'm processing with Rust.
This block represents a heap of null terminated C strings. I have offsets into this heap the represent the starting character, reads are supposed to happen until the null is encountered.
let heap = *b"foobar\0baz\0quuz\0"; // Assume [u8;16] or Vec<u8>
let offset = 0;
let myCstring = something(heap, offset);
assert!( myCstring, "foobar\0" );
Looking at the documentation for ffi::CString
, I don't see anything that address the needs of something(heap, starting_char_index)
above.
Since this is part of a binary file format written in another language and these are C-Strings should I be trying to do this with ffi
? Should I be just roll my own thing and ignore ffi?
You could use std::ffi::CStr
to get the nul-terminated region of memory. If you are in Rust-land then CStr::from_bytes_until_nul(&heap[offset..])
would be appropriate, but if you're coming from C-land where you just have a pointer and offset, then CStr::from_ptr
would be appropriate (with heap.add(offset)
).
That would give you a &CStr
, which is similar to &str
just with a nul-terminator and potentially not UTF-8. If you need to claim ownership of that string, you would use .to_owned()
to get a CString
(similar to String
respectively). There are further methods if you need a &str
or String
from that.
But since you mention its from a file, then I might skip ffi
and just do slice manipulations to find the section bounded by nul.