Hey,
The problem while not widely popular seems common enough, but I couldn't find any satisfying answer online. Maybe I didn't search for the right stuff or couldn't understand the answer. Overall, my goal is the following. I have a bytes that I parsed in a bunch of slices, similar to the snippet under.
pub struct Parsed<'a> {
a: &'a [u8],
b: &'a [u8],
}
pub fn parse<'a>(bytes: &'a [u8]) -> Parsed<'a> {
Parsed { a: &bytes[..1], b: &bytes[1..] }
}
This is fairly typical when parsing binary format, since it allows for zero-copy parsing. Now, I want to be able to combine this Parsed
structure with the ownership of the bytes in order to store it, say in a Vec
. I looked at different possibility, and found the crate owning_ref.
I couldn't get the crate to working with my struct, but I also wanted to understand how to actually do it. So I came up with:
pub struct OwningParsed<'a> {
owner: Box<[u8]>,
reference: *const Parsed<'a>,
}
pub fn parse_owned<'a>(owner: Box<[u8]>) -> OwningParsed<'a> {
let ptr: *const [u8] = &*owner;
OwningParsed {
owner,
reference: &parse(unsafe { &*ptr }),
}
}
impl<'a> Deref for OwningParsed<'a> {
type Target = Parsed<'a>;
fn deref(&self) -> &Parsed<'a> {
return unsafe { &*self.reference };
}
}
Question 1: Do I need Pin<Box<[u8]>>
?
From my understanding it's not needed, because OwningParsed
is not self referenced (I can move it without problem since the slice is on the heap) and even if the type was Pin<Box<[u8]>>
, I could move it since it's Unpin
.
Question 2: Can I define OwningCert
without the lifetime?
The reason being that in this context, the lifetime is somewhat meaningless and it forces anybody that uses this structure to also define a lifetime. I tried setting it to 'static
which seems a bit hacky, but had issue implementing Deref
.
Thank you in advance for your replies.