Hi All,
sorry for the late reply.
Let me recap the issue.
Redis provides data (string) that I need to read, Redis is completely responsible for them and I do not have to do anything to them except reading. So no allocation, no free, no manipulation.
Anyhow, in some way I need them to be available to my code, ideally using references and without copy them.
We are provide with an handy method: RedisModule_StringPtrLen
that returns to me the beginning of the string and its length.
My first approach was something like this:
pub fn string_ptr_len(str: *mut rm::ffi::RedisModuleString)
-> String {
unsafe {
CStr::from_ptr(rm::ffi::RedisModule_StringPtrLen
.unwrap()(str, std::ptr::null_mut()))
.to_string_lossy()
.into_owned()
}
}
And this worked great. However here I am copying the whole string.
Another attempt was something like this:
pub fn string_ptr_len(str: *mut rm::ffi::RedisModuleString)
-> &str {
unsafe {
let mut len = 0;
let base = rm::ffi::RedisModule_StringPtrLen
.unwrap()(str, &mut len) as *mut u8;
let mut slice = slice::from_raw_parts(base, len);
str::from_utf8_unchecked(slice);
}
}
This would be ideal, I got a reference to the string, I can only read them and it is zero copy, wonderful.
However, it is required a lifetime for these references, and I don’t know what lifetime I should provide. (Here should I try to wrap everything into some type and use a PhatomType?)
Finally another approach that I tried is something like:
pub fn string_ptr_len(str: *mut rm::ffi::RedisModuleString)
-> String {
unsafe {
let mut len = 0;
let base = rm::ffi::RedisModule_StringPtrLen
.unwrap()(str, &mut len) as *mut u8;
String::from_raw_parts(base, len, len)
}
}
Here the problem is that I should forget the String to avoid double free (rust will try to free it somewhere) maybe I can work around this but it doesn’t seems very nice.
I would try something like a custom type that wrap the string and that inside the Drop
simply forget about the string.
What I would really like is the second method that seems the most affine of what is happening down to the memory.
Do you guys have suggestions?