Skip to content

Integration with the bytes crates #1444

Open
@dignifiedquire

Description

@dignifiedquire

A lot of my networking code uses bytes to handle efficient storing of incoming and outgoing packets. I would like to transition more of that code to use zerocopy, but for that some integration would be required.

The following example is for the parsing side of what I would like to do, but this fails as ByteSlice is not implemented for bytes::Bytes or bytes::BytesMut.

I can't implement this in my own crate, as both the type and the trait are in 3rd party crates.

use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeroes, Ref, Unaligned};
use bytes::Bytes;

#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct UdpHeader {
    src_port: [u8; 2],
    dst_port: [u8; 2],
    length: [u8; 2],
    checksum: [u8; 2],
}

struct UdpPacket {
    header: Ref<Bytes, UdpHeader>,
    body: Bytes,
}

impl UdpPacket {
    fn parse(bytes: Bytes) -> Option<UdpPacket> {
        let (header, body) = Ref::new_from_prefix(bytes)?;
        Some(UdpPacket { header, body })
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions