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

Extend TryFromBytes to support validation context #590

Open
joshlf opened this issue Nov 2, 2023 · 0 comments
Open

Extend TryFromBytes to support validation context #590

joshlf opened this issue Nov 2, 2023 · 0 comments

Comments

@joshlf
Copy link
Member

joshlf commented Nov 2, 2023

See also: #5 (comment)

This is an extension of the design described in #5

TODO: Fill out details

pub unsafe trait TryFromBytes {
    // This can either default to `()` by dint of the custom derive emitting that,
    // or we can use associated type defaults once they're stable.
    #[doc(hidden)]
    type Context: Default;

    #[doc(hidden)]
    fn is_bit_valid(ctx: &mut Self::Context, ptr: NonNull<Self>) -> bool;

    fn try_read_from(bytes: &[u8]) -> Option<Self> where Self: Sized {
        let maybe_uninit = MaybeUninit::<Self>::read_from(bytes)?;
        let ptr = NonNull::from(&maybe_uninit).cast::<Self>();
        let mut ctx = <Self::Context as Default>::default();
        if Self::is_bit_valid(&mut ctx, ptr) {
            unsafe { maybe_uninit.assume_init() }
        }
    }
}

Per @djkoloski, for rkyv's use case, the Context type might actually need to be constructible from the byte slice that's being parsed from, ie type Context: for<'a> From<&'a [u8]>.

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