derive_pod/
lib.rs

1/*!
2Auto derive the `Pod` trait.
3
4This crate should not be used directly, instead depend on the `dataview` crate with the `derive_pod` feature enabled.
5*/
6
7use proc_macro::*;
8
9/// Derive macro for the `Pod` trait.
10///
11/// The type is checked for requirements of the `Pod` trait:
12///
13/// * Must be annotated with [`#[repr(C)]`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprc)
14///   or [`#[repr(transparent)]`](https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent).
15/// * Must have every field's type implement `Pod` itself.
16/// * Must not have any padding between its fields, define dummy fields to cover the padding.
17///
18/// Note that it is legal for pod types to be a [ZST](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts).
19///
20/// # Compile errors
21///
22/// Error reporting is not very ergonomic due to how errors are detected:
23///
24/// * `error[E0277]: the trait bound $TYPE: Pod is not satisfied`
25///
26///   The struct contains a field whose type does not implement `Pod`.
27///
28/// * `error[E0512]: cannot transmute between types of different sizes, or dependently-sized types`
29///
30///   This error means your struct has padding as its size is not equal to a byte array of length equal to the sum of the size of its fields.
31///
32/// * `error: cannot implement Pod for type $TYPE`
33///
34///   Deriving `Pod` is not supported for this type.
35///
36///   This includes enums, unions and structs with generics or lifetimes.
37#[proc_macro_derive(Pod)]
38pub fn pod_derive(input: TokenStream) -> TokenStream {
39	let invoke: TokenStream = "::dataview::derive_pod!".parse().unwrap();
40	invoke.into_iter().chain(Some(TokenTree::Group(Group::new(Delimiter::Brace, input)))).collect()
41}
42
43/// Derive macro calculates field offsets.
44///
45/// The type must be a struct and must implement `Pod` or an error is raised.
46///
47/// The derive macro adds an associated constant `FIELD_OFFSETS` to the type.
48/// `FIELD_OFFSETS` is an instance of a struct with `usize` fields for every field in the type.
49/// The value of each field is the offset of that field in the type.
50#[proc_macro_derive(FieldOffsets)]
51pub fn field_offsets(input: TokenStream) -> TokenStream {
52	let invoke: TokenStream = "::dataview::__field_offsets!".parse().unwrap();
53	invoke.into_iter().chain(Some(TokenTree::Group(Group::new(Delimiter::Brace, input)))).collect()
54}