Skip to content

Clarify when TryFromBytes and IntoBytes aren't symmetrical #2722

@mkeeter

Description

@mkeeter

The docs for TryFromBytes say

Code should not generally assume that values produced by IntoBytes will necessarily be accepted as valid by TryFromBytes.

It would be helpful to explain cases where these traits are asymmetrical, so that people could use TryFromBytes with confidence. As written, it seems like even trivial code is of unknown correctness, e.g.

use zerocopy::{IntoBytes, TryFromBytes, Immutable, KnownLayout};

#[derive(Debug, PartialEq, TryFromBytes, IntoBytes, Immutable, KnownLayout)]
struct Foo {
    hello: u32,
    world: u32,
}

fn main() {
    let f = Foo {
        hello: 0x1234,
        world: 0x5678,
    };
    let bytes = f.as_bytes();
    let f_ = Foo::try_ref_from_bytes(bytes).expect("is this okay to do?");
    assert_eq!(&f, f_);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions