google / google/zerocopy

Extend TryFromBytes to support validation context

Open
#590 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

*See also: https://github.com/google/zerocopy/issues/5#issuecomment-2120952779*

*This is an extension of the design described in #5*

TODO: Fill out details

```rust
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) -> bool;

fn try_read_from(bytes: &[u8]) -> Option where Self: Sized {
let maybe_uninit = MaybeUninit::::read_from(bytes)?;
let ptr = NonNull::from(&maybe_uninit).cast::();
let mut ctx = ::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]>`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.