Skip to main content

UninitBuilder

Derive Macro UninitBuilder 

Source
#[derive(UninitBuilder)]
{
    // Attributes available to this derive:
    #[wincode]
}
Available on crate feature derive only.
Expand description

Include placement initialization helpers for structs.

This generates an UninitBuilder for the given struct, providing convenience methods that can avoid a lot of boilerplate when implementing custom SchemaRead implementations. In particular, it provides methods that deal with projecting subfields of structs into MaybeUninits. Without this, one would have to write a litany of &mut *(&raw mut (*dst_ptr).field).cast() to access MaybeUninit struct fields. It also provides initialization helpers and drop tracking logic.

For example:

#[derive(UninitBuilder)]
struct Message {
    payload: Vec<u8>,
    bytes: [u8; 32],
}

unsafe impl<'de, C: Config> SchemaRead<'de, C> for Message {
    type Dst = Self;

    fn read(mut reader: impl Reader<'de>, dst: &mut MaybeUninit<Self::Dst>) -> ReadResult<()> {
        let msg_builder = MessageUninitBuilder::<C>::from_maybe_uninit_mut(dst);
        // Deserializes a `Vec<u8>` into the `payload` slot of `Message` and marks the field
        // as initialized. If the subsequent `read_bytes` call fails, the `payload` field will
        // be dropped.
        msg_builder.read_payload(reader.by_ref())?;
        msg_builder.read_bytes(reader)?;
        msg_builder.finish();
    }
}

We cannot do this for enums, given the lack of facilities for placement initialization.