[][src]Crate structural

This library provides field accessor traits,and emulation of structural types.

Features

These are some of the features this library provides:

Clarifications

The way that this library emulates structural types is by using traits as bounds or trait objects.

All the structural traits are dyn-compatible(also known as object-safe), and no change will be made to make them not dyn-compatible.

By default all structural types are open, structs and enums can have more variants and or fields than are required.
The only exception to this is exhaustive enums, in which the variant count and names must match exactly, this is useful for exhaustive matching of variants (in the switch macro).

Every trait with the _SI/_ESI/_VSI suffixes in the examples are traits generated by the Structural derive macro. These traits alias the accessor traits implemented by the type they're named after.

Required macros

The only macros that are required to use this crate are the ones for TStr, every other macro expands to code that can be written manually (except for the __TS type, that is an implementation detail that only macros from this crate should use by name).

Examples

Structural Derive for structs

This demonstrates how you can use any type with a superset of the fields of another one in a function.

Structural derive macro docs for more details on derivation.

use structural::{fp, Structural, StructuralExt};

fn reads_point3<S>(point: &S)
where
    // The `Point3D_SI` trait was generated by the `Structural` derive for `Point3D`,
    // aliasing the accessor traits implemented by `Point3D`.
    S: Point3D_SI<u32>,
{
    let (a, b, c) = point.fields(fp!(x, y, z));

    assert_eq!(a, &0);
    assert_eq!(b, &11);
    assert_eq!(c, &33);
}

fn main() {
    reads_point3(&Point3D { x: 0, y: 11, z: 33 });

    reads_point3(&Point4D {
        x: 0,
        y: 11,
        z: 33,
        a: 0xDEAD,
    });

    reads_point3(&Point5D {
        x: 0,
        y: 11,
        z: 33,
        a: 0xDEAD,
        b: 0xBEEF,
    });
}

#[derive(Structural)]
// Using the `#[struc(public)]` attribute tells the derive macro to
// generate the accessor trait impls for non-`pub` fields.
#[struc(public)]
struct Point3D<T> {
    x: T,
    y: T,
    z: T,
}

#[derive(Structural)]
// By default only public fields get accessor trait impls,
// using `#[struc(public)]` you can have impls to access private fields.
#[struc(public)]
struct Point4D<T> {
    x: T,
    y: T,
    z: T,
    a: T,
}

#[derive(Structural)]
struct Point5D<T> {
    pub x: T,
    pub y: T,
    pub z: T,
    pub a: T,
    pub b: T,
}

Structural Derive for enums

This demonstrates how you can use structural enums.

For details on enums look here.

use structural::{fp, switch, Structural, StructuralExt};

fn main() {
    {
        // Command

        run_command(Command::SendEmail(SendEmail {
            to: "ferris@lib.rs".to_string(),
            content: "Hello".to_string(),
        }));
        run_command(Command::RemoveAddress("gopher".to_string()));
    }
    {
        // ExtraCommand
        //
        // ExtraCommand can't be passed to `run_command` because that function requires
        // an enum with exactly the `SendEmail` and `RemoveAddress` variants.

        // The `SendEmail` variant can have more fields than the one in the `Command` enum,
        // they're just ignored.
        run_command_nonexhaustive(ExtraCommand::SendEmail {
            to: "squatter@crates.io".to_string(),
            content: "Can you stop squatting crate names?".to_string(),
            topic: "squatting".to_string(),
        })
        .unwrap();

        let ra_cmd = ExtraCommand::RemoveAddress("smart_person".to_string());
        run_command_nonexhaustive(ra_cmd).unwrap();

        let ca_cmd = ExtraCommand::CreateAddress("honest_person".to_string());
        let res = run_command_nonexhaustive(ca_cmd.clone());
        assert_eq!(res, Err(UnsupportedCommand(ca_cmd)));
    }
}

// Runs the passed in command.
//
// The `Command_ESI` trait allows only enums with the same variants as
// `Command` to be passed in(they can have a superset of the fields in `Command`).
fn run_command<S>(cmd: S)
where
    S: Command_ESI,
{
    run_command_nonexhaustive(cmd)
        .ok()
        .expect("`run_command_nonexhaustive` must match all `Command` variants")
}

// Runs the passed in command.
//
// The `Command_SI` trait allows enums with a superset of the variants in `Command`
// to be passed in,
// requiring the a `_=>` branch when it's matched on with the `switch` macro.
fn run_command_nonexhaustive<S>(cmd: S) -> Result<(), UnsupportedCommand<S>>
where
    S: Command_SI,
{
    switch! {cmd;
        // This matches the SendEmail variant and destructures the
        // `to` and `content` fields  by value.
        SendEmail{to,content}=>{
            println!("Sending message to the '{}' email address.",to);
            println!("Content:{:?}",content);
            Ok(())
        }
        // This matches the RemoveAddress variant and destructures it into
        // the 0th field (by reference,because of the `ref`).
        ref RemoveAddress(address)=>{
            println!("removing the '{}' email address",address);
            Ok(())
        }
        _=>Err(UnsupportedCommand(cmd))
    }
}

#[derive(Structural)]
enum Command {
    // The `newtype(bounds="...")` attribute marks the variant as being a newtype variant,
    // delegating field accessors of the variant to `SendEmail`(its one field),
    // as well as replacing the bounds for the variant in the
    // trait aliases generated by the `Structural` derive (`Command_SI` and `Command_ESI`)
    // with `SendEmail_VSI<TS!(SendEmail)>`.
    //
    // `SendEmail_VSI` was generated by the `Structural` derive on `SendEmail`,
    // with accessor trait bounds for accessing the struct's fields
    // in a variant (it takes the name of the variant as a generic parameter).
    #[struc(newtype(bounds = "SendEmail_VSI<@variant>"))]
    SendEmail(SendEmail),
    RemoveAddress(String),
}

#[derive(Structural)]
pub struct SendEmail {
    pub to: String,
    pub content: String,
}

#[derive(Debug, Structural, Clone, PartialEq)]
// This attribute stops the generation of the
// `ExtraCommands_SI` and `ExtraCommands_ESI` traits
#[struc(no_trait)]
pub enum ExtraCommand {
    SendEmail {
        to: String,
        content: String,
        topic: String,
    },
    RemoveAddress(String),
    CreateAddress(String),
}

#[derive(Debug, PartialEq)]
pub struct UnsupportedCommand<T>(pub T);

Structural alias for struct

This demonstrates how you can define a trait aliasing field accessors, using a fields-in-traits syntax.

For more details you can look at the docs for the structural_alias macro.


use structural::{fp, structural_alias, FP, IntoFieldMut, Structural, StructuralExt};

use std::borrow::Borrow;

structural_alias! {
    trait Person<H: House>{
        name: String,
        house: H,
    }

    trait House{
        dim: Dimension3D,
    }
}

fn print_name<T, H>(this: &T)
where
    T: ?Sized + Person<H>,

    // This is the one trait that `House` requires in its blanket implementation.
    // `H: House,` is equivalent to this
    H: IntoFieldMut<FP!(dim), Ty = Dimension3D>,
{
    let (name, house_dim) = this.fields(fp!(name, house.dim));
    println!("Hello, {}!", name);

    let (w, h, d) = house_dim.fields(fp!(width, height, depth));

    if w * h * d >= 1_000_000 {
        println!("Your house is enormous.");
    } else {
        println!("Your house is normal sized.");
    }
}

// most structural aliases are object safe
fn print_name_dyn<H>(this: &dyn Person<H>)
where
    // This is the one trait that `House` requires in its blanket implementation.
    // `H: House,` is equivalent to this
    H: IntoFieldMut<FP!(dim), Ty = Dimension3D>,
{
    print_name(this)
}

#[derive(Structural)]
#[struc(public)]
struct Dimension3D {
    width: u32,
    height: u32,
    depth: u32,
}

//////////////////////////////////////////////////////////////////////////
////          The stuff here could be defined in a separate crate

fn main() {
    let worker = Worker {
        name: "John Doe".into(),
        salary: Cents(1_000_000_000_000_000),
        house: Mansion {
            dim: Dimension3D {
                width: 300,
                height: 300,
                depth: 300,
            },
            money_vault_location: "In the basement".into(),
        },
    };

    let student = Student {
        name: "Jake English".into(),
        birth_year: 1995,
        house: SmallHouse {
            dim: Dimension3D {
                width: 30,
                height: 30,
                depth: 30,
            },
            residents: 10,
        },
    };

    print_name(&worker);
    print_name(&student);

    print_name_dyn(&worker);
    print_name_dyn(&student);
}

#[derive(Structural)]
// Using the `#[struc(public)]` attribute tells the derive macro to
// generate the accessor trait impls for non-`pub` fields.
#[struc(public)]
struct Worker {
    name: String,
    salary: Cents,
    house: Mansion,
}

#[derive(Structural)]
#[struc(public)]
struct Student {
    name: String,
    birth_year: u32,
    house: SmallHouse,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct Cents(u64);

#[derive(Structural)]
#[struc(public)]
struct Mansion {
    dim: Dimension3D,
    money_vault_location: String,
}

#[derive(Structural)]
#[struc(public)]
struct SmallHouse {
    dim: Dimension3D,
    residents: u32,
}

Structural alias for enums

This demonstrates how you can use structural aliases for enums.

This shows both exhaustive and nonexhaustive enum structural aliases.

For more details you can look at the docs for the structural_alias macro.

use std::fmt::Debug;
use structural::{fp, structural_alias, switch, Structural, StructuralExt};

fn main() {
    pet_animal_ex(&SomeMammals::Dog {
        years: 1,
        volume_cm3: 1,
    });
    pet_animal_ex(&SomeMammals::Horse);

    // `MoreAnimals` cannot be passed to `pet_animal_ex`
    // since that function requires an enum with only `Dog` and `Horse` variants.
    assert_eq!(
        pet_animal(&MoreAnimals::Dog {
            years: 10,
            volume_cm3: 100
        }),
        Ok(())
    );
    assert_eq!(pet_animal(&MoreAnimals::Horse), Ok(()));
    assert_eq!(pet_animal(&MoreAnimals::Cat { lives: 9 }), Err(CouldNotPet));
    assert_eq!(pet_animal(&MoreAnimals::Seal), Err(CouldNotPet));
}

// For an equivalent function that's ergonomic to write, look below for `pet_animal_switch`
fn pet_animal(animal: &dyn Animal) -> Result<(), CouldNotPet> {
    // `::Dog` accesses the `Dog` variant
    // (without the `::` it'd be interpreted as a field access),
    // The `=>` allows getting multiple fields from inside a nested field
    // (this includes enum variants).
    // `years,volume_cm3` are the field accessed from inside `::Dog`
    let dog_fields = fp!(::Dog=>years,volume_cm3);

    // The `is_horse` method comes from the `Animal` trait.
    if animal.is_horse() {
        println!("You are petting the horse");
    } else if let Some((years, volume_cm3)) = animal.fields(dog_fields) {
        println!(
            "You are petting the {} year old,{} cm³ dog",
            years, volume_cm3
        );
    } else {
        return Err(CouldNotPet);
    }
    Ok(())
}

// This can't take a `&dyn Animal_Ex` because traits objects don't
// automatically support upcasting into other trait objects
// (except for auto traits like Send and Sync ).
fn pet_animal_ex(animal: &impl Animal_Ex) {
    pet_animal(animal).expect("`pet_animal` must match on all variants from the `Animal` trait");
}

// The same as `pet_animal` ,except that this uses the `switch` macro
fn pet_animal_switch(animal: &dyn Animal) -> Result<(), CouldNotPet> {
    switch! {animal;
        Horse=>{
            println!("You are petting the horse");
        }
        // This matches the Dog variant,
        // and destructures it into its `years` and `volume_cm3` fields
        // as references(because of the `ref`)
        ref Dog{years,volume_cm3}=>{
            println!("You are petting the {} year old,{} cm³ dog",years,volume_cm3);
        }
        _=>return Err(CouldNotPet)
    }
    Ok(())
}

#[derive(Debug, PartialEq)]
struct CouldNotPet;

structural_alias! {
    // The `#[struc(and_exhaustive_enum(suffix = "_Ex"))]` attribute
    // generates the `Animal_Ex` trait with this trait as a supertrait,
    // and with the additional requirement that the enum
    // only has the `Horse` and `Dog` variants
    // (Those variants can still have more fields than required).
    //
    // structural aliases can have supertraits,here it's `Debug`
    #[struc(and_exhaustive_enum(suffix = "_Ex"))]
    trait Animal: Debug{
        Horse,
        Dog{years: u16, volume_cm3: u64},

        // Structural aliases can define extension methods,
        fn is_horse(&self) -> bool {
            self.is_variant(fp!(Horse))
        }
    }
}

#[derive(Debug, Structural)]
#[struc(no_trait)]
enum SomeMammals {
    Horse,
    Dog { years: u16, volume_cm3: u64 },
}

#[derive(Debug, Structural)]
#[struc(no_trait)]
enum MoreAnimals {
    Cat { lives: u8 },
    Dog { years: u16, volume_cm3: u64 },
    Horse,
    Seal,
}

Anonymous structs (make_struct macro)

This demonstrates how you can construct an anonymous struct.

For more details you can look at the docs for the make_struct macro.

Docs for the impl_struct macro.

use structural::{fp, impl_struct, make_struct, structural_alias, StructuralExt};

structural_alias! {
    trait Person<T>{
        // We only have shared access (`&String`) to the field.
        ref name: String,

        // We have shared,mutable,and by value access to the field.
        // Not specifying any of `mut`/`ref`/`move` is equivalent to `mut move value: T,`
        value: T,
    }
}

fn make_person(name: String) -> impl_struct! { name: String, value: () } {
    make_struct! {
        name,
        value: (),
    }
}

fn print_name(mut this: impl_struct! { ref name: String, value: Vec<String> }) {
    println!("Hello, {}!", this.field_(fp!(name)));

    let list = vec!["what".into()];
    *this.field_mut(fp!(value)) = list.clone();
    assert_eq!(this.field_(fp!(value)), &list);
    assert_eq!(this.into_field(fp!(value)), list);
}

// most structural aliases are object safe
//
// This has to use the Person trait,
// since `impl_struct!{....}` expands to `impl Trait0 + Trait1 + etc`.
fn print_name_dyn(this: &mut dyn Person<Vec<String>>) {
    println!("Hello, {}!", this.field_(fp!(name)));

    let list = vec!["what".into()];
    *this.field_mut(fp!(value)) = list.clone();
    assert_eq!(this.field_(fp!(value)), &list);
}

//////////////////////////////////////////////////////////////////////////
////          The stuff here could be defined in a separate crate

fn main() {
    let worker = make_struct! {
        // This derives clone for the anonymous struct
        #![derive(Clone)]
        name: "John Doe".into(),
        salary: Cents(1_000_000_000_000_000),
        value: vec![],
    };

    let student = make_struct! {
        // This derives clone for the anonymous struct
        #![derive(Clone)]
        name: "Jake English".into(),
        birth_year: 1995,
        value: vec![],
    };

    print_name(worker.clone());
    print_name(student.clone());

    print_name_dyn(&mut worker.clone());
    print_name_dyn(&mut student.clone());

    let person = make_person("Louis".into());

    assert_eq!(person.field_(fp!(name)), "Louis");
    assert_eq!(person.field_(fp!(value)), &());

    // Destructuring the anonymous struct by value.
    // The type annotation here is just to demonstrate that it returns a `String` by value.
    let (name, value): (String, ()) = person.into_fields(fp!(name, value));
    assert_eq!(name, "Louis");
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct Cents(u64);

Re-exports

pub use crate::field::FieldType;
pub use crate::field::GetField;
pub use crate::field::GetFieldMut;
pub use crate::field::GetFieldType;
pub use crate::field::GetFieldType2;
pub use crate::field::GetFieldType3;
pub use crate::field::GetFieldType4;
pub use crate::field::GetVariantField;
pub use crate::field::GetVariantFieldMut;
pub use crate::field::GetVariantFieldType;
pub use crate::field::IntoField;
pub use crate::field::IntoFieldMut;
pub use crate::field::IntoVariantField;
pub use crate::field::IntoVariantFieldMut;

Modules

convert

Traits for converting between structural types.

docs

Documentation for proc-macros and guides.

enums

Enum related traits and types.

field

Accessor and extension traits for fields.

for_examples

Structural-deriving types used in examples,

path

Types used to refer to the field(s) that one is accessing.

reexports

Reexports from other crates.

structural_aliases

Structural aliases for standard library types.

type_level

types that represent values.

utils

Some helper functions.

Macros

FP

Constructs a field path type for use as a generic parameter.

TS

For getting the type of a TStr<_> (type-level string).

field_pat

Macro to destructure the tuple returned by StructuralExt methods that access multiple fields.

field_path_aliases

Declares aliases for field paths,used to access fields.

fp

Constructs a field path value, which determines the field(s) accessed in StructuralExt methods.

impl_struct

For declaring an anonymous structural type,this expands to an impl Trait.

make_struct

Constructs an anonymous struct, which implements all the accessor traits for its fields.

path_tuple

For manually constructing a FieldPathSet to access up to 64 fields.

structural_alias

The structural_alias macro defines a trait alias for multiple field accessors.

switch

Provides basic pattern matching for structural enums.

ts

Constructs a TStr value,a type-level string used for identifiers in field paths.

tstr_aliases

Declares type aliases for TStr<_>(type-level string).

unsafe_delegate_structural_with

This macro allows delegating the implementation of the accessor traits.

z_impl_from_structural

For implementing FromStructural, and delegating the implementation of TryFromStructural to it.

z_impl_try_from_structural_for_enum

For implementing TryFromStructural, and delegating the implementation of FromStructural to it.

z_raw_borrow_enum_field

For creating a raw pointer of an enum field,as either Some(NonNull<_>) or None.

z_unsafe_impl_get_field_raw_mut

For semi-manual implementors of the GetFieldMut trait for structs.

z_unsafe_impl_get_vfield_raw_mut_fn

Implements the get_vfield_raw_mut_fn and get_vfield_raw_mut_unchecked_fn methods from the GetVariantFieldMut trait.

Structs

FieldCloner

Wrapper that emulates by-value access to fields by cloning them.

FieldPathSet

A list of field paths to access multiple fields, whose uniqueness is determined by the U type parameter.

NestedFieldPath

A type-level representation of a chain of field accesses,like .a.b.c.d.

NestedFieldPathSet

Allows accessing multiple fields inside of some nested field.

StrucWrapper

A wrapper type alternative to StructuralExt, with methods for accessing fields in structural types.

TStr

Type-level string,used for identifiers in field paths.

VariantField

This allows accessing the F field inside the V enum variant.

VariantName

This allows accessing the V enum variant (by constructing a VariantProxy representing that variant).

Traits

Structural

Marker trait for types that implement some field accessor traits.

StructuralExt

A trait defining the primary way to call methods from structural traits.

Derive Macros

Structural

This macro is documented in structural::docs::structural_macro