Derive Macro SizeOf

Source
#[derive(SizeOf)]
{
    // Attributes available to this derive:
    #[size_of]
}
Expand description

Derives the SizeOf trait for the given item

Works on structs and enums, SizeOf must be implemented manually for unions unless the #[size_of(skip_all)] top-level attribute is used

Accepted attributes:

  • #[size_of(crate = "<crate_path>")] allows setting the path to the size_of crate, this is only allowed at the top level
  • #[size_of(skip_all)] allows skipping all fields or variants of the item, this is only allowed at the top level
  • #[size_of(skip)] skips the current variant or field
  • #[size_of(skip_bounds)] skips emitting trait bounds for the current variant/field, allows compiling things like struct Foo { bar: Box<Self> }

§Examples

Normal derive usage

#[derive(SizeOf)]
struct Foo {
    bar: Vec<u8>,
    baz: String,
}

Skips collecting the sizes of all children

#[derive(SizeOf)]
#[size_of(skip_all)]
struct Foo {
    bar: Vec<u8>,
    baz: String,
}

Skip collecting the size of a specific field/variant

#[derive(SizeOf)]
struct Foo {
    bar: Vec<u8>,
    #[size_of(skip)]
    baz: String,
}

#[derive(SizeOf)]
enum Bar {
    #[size_of(skip)]
    Baz,
    #[size_of(skip)]
    Bing(u8),
    Bong {
        #[size_of(skip)]
        boo: String,
    },
}

Skip the bounds of a specific field/variant. The size of the field and all of its children will still be collected, however a FieldType: SizeOf bound will not be emitted. This will cause compile errors if FieldType doesn’t implement SizeOf, but it’s necessary for recursive types.

#[derive(SizeOf)]
struct Foo {
    #[size_of(skip_bounds)]
    baz: Vec<Self>,
}