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

Start work on zero copy support #35

Merged
merged 13 commits into from
Oct 9, 2023
Merged

Start work on zero copy support #35

merged 13 commits into from
Oct 9, 2023

Conversation

udoprog
Copy link
Owner

@udoprog udoprog commented Oct 9, 2023

The approach is:

Introduce a new trait called ZeroCopy, this is an unsafe trait which asserts that given a certain set of validations pass a type can be safely coerced into a referefence.

This trait can be implemented if a struct is marked repr(C) and implemented the reading, writing, and validation functions correctly. This can be done automatically through the ZeroCopy derive.

Finally (but this has not been implemented yet) a ZeroCopy type will implement Decode, so that it can be transcoded from other types.

Example of what support this adds:

use musli_zerocopy::{Error, OwnedBuf, Pair, UnsizedRef, ZeroCopy};

#[derive(ZeroCopy)]
#[repr(C)]
struct Custom {
    field: u32,
    string: UnsizedRef<str>,
}

fn main() -> Result<(), Error> {
    let mut buf = OwnedBuf::new();

    let string = buf.insert_unsized("string")?;

    let custom1 = buf.insert_sized(Custom { field: 1, string })?;
    let custom2 = buf.insert_sized(Custom { field: 2, string })?;

    let mut map = Vec::new();

    map.push(Pair::new(1, custom1));
    map.push(Pair::new(2, custom2));

    let map = buf.insert_map(&mut map)?;

    let buf = buf.as_aligned_buf();

    if let Some(custom1) = map.get(buf, &1)? {
        let custom1 = buf.load(custom1)?;
        assert_eq!(custom1.field, 1);
        assert_eq!(buf.load(custom1.string)?, "string");
    } else {
        panic!("Missing key 1")
    }

    if let Some(custom2) = map.get(buf, &2)? {
        let custom2 = buf.load(custom2)?;
        assert_eq!(custom2.field, 2);
        assert_eq!(buf.load(custom2.string)?, "string");
    } else {
        panic!("Missing key 2");
    }

    assert!(map.get(buf, &3)?.is_none());
    Ok(())
}

@udoprog udoprog added the enhancement New feature or request label Oct 9, 2023
@udoprog udoprog merged commit ddb844b into main Oct 9, 2023
14 checks passed
@udoprog udoprog deleted the zerocopy branch October 9, 2023 15:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant