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::CStrto get the nul-terminated region of memory. If you are in Rust-land thenCStr::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, thenCStr::from_ptrwould be appropriate (withheap.add(offset)).That would give you a
&CStr, which is similar to&strjust 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 aCString(similar toStringrespectively). There are further methods if you need a&strorStringfrom that.But since you mention its from a file, then I might skip
ffiand just do slice manipulations to find the section bounded by nul.