Open joshlf opened 2 weeks ago
Unfortunately, no. "DST" in #1112 refers to types whose length is only known at runtime, and to which pointers carry extra length metadata. It wouldn't apply to your example, because Packet
's size is known at runtime, and IntoBytes
is a property of the entire type.
As the error message suggests, you can probably get your code to compile by adding an explicit padding field to Packet::DoSomething
:
#[derive(IntoBytes, KnownLayout)]
#[repr(u8)]
enum Packet {
DoSomething { _padding: [u8; 4] } = 0x10,
DoSomethingWithValue([u8; 4]) = 0x20,
}
...but calling .as_bytes
will still return all five bytes for Packet::DoSomething
.
To work around this, you'll want to define your own "as bytes" mechanism that builds atop zerocopy's. Something like:
impl Packet {
fn as_data_bytes(&self) -> &[u8] {
let len = match self {
Self::DoSomething { .. } => 1,
Self::DoSomethingWithValue { .. } => 5,
};
&self.as_bytes()[..len]
}
}
Would #1112 also apply to dynamically-sized enums? I think I have a usecase for borrowing an enum with non-uniform field sizes as a byte slice but am not 100% sure I have the correct mindset, though I can already do this the other way around and interpret an appropriately-sized byte slice as a packet enum.