Attribute Macro zerovec::make_ule

source ·
#[make_ule]
Expand description

Generate a corresponding ULE type and the relevant AsULE implementations for this type

This can be attached to structs containing only AsULE types, or C-like enums that have #[repr(u8)] and all explicit discriminants.

The type must be Copy, PartialEq, and Eq.

#[make_ule] will automatically derive the following traits on the ULE type:

To disable one of the automatic derives, use #[zerovec::skip_derive(...)] like so: #[zerovec::skip_derive(ZeroMapKV)]. Ord and PartialOrd are implemented as a unit and can only be disabled as a group with #[zerovec::skip_derive(Ord)].

The following traits are available to derive, but not automatic:

To enable one of these additional derives, use #[zerovec::derive(...)] like so: #[zerovec::derive(Debug)].

In most cases these derives will defer to the impl of the same trait on the current type, so such impls must exist.

For enums, this attribute will generate a crate-public fn new_from_u8(value: u8) -> Option<Self> method on the main type that allows one to construct the value from a u8. If this method is desired to be more public, it should be wrapped.

§Example

use zerovec::ZeroVec;

#[zerovec::make_ule(DateULE)]
#[derive(
    Copy,
    Clone,
    PartialEq,
    Eq,
    Ord,
    PartialOrd,
    serde::Serialize,
    serde::Deserialize,
)]
struct Date {
    y: u64,
    m: u8,
    d: u8,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct Dates<'a> {
    #[serde(borrow)]
    dates: ZeroVec<'a, Date>,
}

let dates = Dates {
    dates: ZeroVec::alloc_from_slice(&[
        Date {
            y: 1985,
            m: 9,
            d: 3,
        },
        Date {
            y: 1970,
            m: 2,
            d: 20,
        },
        Date {
            y: 1990,
            m: 6,
            d: 13,
        },
    ]),
};

let bincode_bytes =
    bincode::serialize(&dates).expect("Serialization should be successful");

// Will deserialize without allocations
let deserialized: Dates = bincode::deserialize(&bincode_bytes)
    .expect("Deserialization should be successful");

assert_eq!(deserialized.dates.get(1).unwrap().y, 1970);
assert_eq!(deserialized.dates.get(2).unwrap().d, 13);

Full docs for this proc macro can be found on the zerovec crate.