Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Returning Archived struct instance with lifetime tied to Vec<u8> #501

Open
namse opened this issue May 14, 2024 · 1 comment
Open

Returning Archived struct instance with lifetime tied to Vec<u8> #501

namse opened this issue May 14, 2024 · 1 comment

Comments

@namse
Copy link

namse commented May 14, 2024

I want to return the result of archived_root outside. However, since archived_root receives &[], it doesn't seem to have a sufficient lifetime to be returned outside.
If bytes is in Vec, can I create an Archived with the same lifetime as that Vec and return it outside?

@namse
Copy link
Author

namse commented May 14, 2024

Is it right approach?

struct HeapArchive<T> {
    buffer: Vec<u8>,
    _phantom: std::marker::PhantomData<T>,
}

impl<T> HeapArchive<T> {
    fn new(buffer: Vec<u8>) -> Self {
        Self {
            buffer,
            _phantom: std::marker::PhantomData,
        }
    }
    fn deserialize(&self) -> T
    where
        T: rkyv::Archive,
        T::Archived: Deserialize<T, SharedDeserializeMap>,
    {
        unsafe { rkyv::from_bytes_unchecked(&self.buffer).unwrap() }
    }
}

impl<T: rkyv::Archive> Deref for HeapArchive<T> {
    type Target = Archived<T>;

    fn deref(&self) -> &Self::Target {
        unsafe { rkyv::archived_root::<T>(&self.buffer) }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant