#derive #macro

macro no-std derive-where

Deriving with custom trait bounds

4 releases (1 stable)

Uses new Rust 2021

1.0.0 Jul 16, 2022
1.0.0-rc.3 Mar 21, 2022
1.0.0-rc.2 Jan 25, 2022
1.0.0-rc.1 Dec 8, 2021

#102 in Rust patterns

Download history 383/week @ 2022-06-07 119/week @ 2022-06-14 522/week @ 2022-06-21 528/week @ 2022-06-28 512/week @ 2022-07-05 178/week @ 2022-07-12 1905/week @ 2022-07-19 135/week @ 2022-07-26 120/week @ 2022-08-02 355/week @ 2022-08-09 163/week @ 2022-08-16 245/week @ 2022-08-23 152/week @ 2022-08-30 234/week @ 2022-09-06 376/week @ 2022-09-13 646/week @ 2022-09-20

1,423 downloads per month
Used in 16 crates (8 directly)

MIT/Apache

180KB
5K SLoC

derive-where

Crates.io Version Live Build Status Docs.rs Documentation

Description

Derive macro to simplify deriving standard and other traits with custom generic type bounds.

Usage

The derive_where macro can be used just like std's #[derive(...)] statements:

#[derive_where(Clone, Debug)]
struct Example<T>(PhantomData<T>);

This will generate trait implementations for Example for any T, as opposed to std's derives, which would only implement these traits with T: Trait bound to the corresponding trait.

Multiple derive_where attributes can be added to an item, but only the first one must use any path qualifications.

#[derive_where::derive_where(Clone)]
#[derive_where(Debug)]
struct Example1<T>(PhantomData<T>);

If using a different package name, you must specify this:

#[derive_where(crate = "derive_where_")]
#[derive_where(Clone, Debug)]
struct Example<T>(PhantomData<T>);

In addition, the following convenience options are available:

Generic type bounds

Separated from the list of traits with a semi-colon, types to bind to can be specified. This example will restrict the implementation for Example to T: Clone:

#[derive_where(Clone; T)]
struct Example<T, U>(T, PhantomData<U>);

It is also possible to specify the bounds to be applied. This will bind implementation for Example to T: Super:

trait Super: Clone {}

#[derive_where(Clone; T: Super)]
struct Example<T>(PhantomData<T>);

But more complex trait bounds are possible as well. The example below will restrict the implementation for Example to T::Type: Clone:

trait Trait {
	type Type;
}

struct Impl;

impl Trait for Impl {
	type Type = i32;
}

#[derive_where(Clone; T::Type)]
struct Example<T: Trait>(T::Type);

Any combination of options listed here can be used to satisfy a specific constrain. It is also possible to use multiple separate constrain specifications when required:

#[derive_where(Clone; T)]
#[derive_where(Debug; U)]
struct Example<T, U>(PhantomData<T>, PhantomData<U>);

Enum default

Deriving Default on an enum is not possible in Rust at the moment. Derive-where allows this with a default attribute:

#[derive_where(Default)]
enum Example<T> {
	#[derive_where(default)]
	A(PhantomData<T>),
}

Skipping fields

With a skip or skip_inner attribute fields can be skipped for traits that allow it, which are: Debug, Hash, Ord, PartialOrd, PartialEq, Zeroize and ZeroizeOnDrop.

#[derive_where(Debug, PartialEq; T)]
struct Example<T>(#[derive_where(skip)] T);

assert_eq!(format!("{:?}", Example(42)), "Example");
assert_eq!(Example(42), Example(0));

It is also possible to skip all fields in an item or variant if desired:

#[derive_where(Debug)]
#[derive_where(skip_inner)]
struct StructExample<T>(T);

assert_eq!(format!("{:?}", StructExample(42)), "StructExample");

#[derive_where(Debug)]
enum EnumExample<T> {
	#[derive_where(skip_inner)]
	A(T),
}

assert_eq!(format!("{:?}", EnumExample::A(42)), "A");

Selective skipping of fields for certain traits is also an option, both in skip and skip_inner. To prevent breaking invariants defined for these traits, some of them can only be skipped in groups. The following groups are available:

#[derive_where(Debug, PartialEq)]
#[derive_where(skip_inner(Debug))]
struct Example<T>(i32, PhantomData<T>);

assert_eq!(format!("{:?}", Example(42, PhantomData::<()>)), "Example");
assert_ne!(
	Example(42, PhantomData::<()>),
	Example(0, PhantomData::<()>)
);

Zeroize options

Zeroize has two options:

  • crate: an item-level option which specifies a path to the zeroize crate in case of a re-export or rename.
  • fqs: a field -level option which will use fully-qualified-syntax instead of calling the zeroize method on self directly. This is to avoid ambiguity between another method also called zeroize.
#[derive_where(Zeroize(crate = "zeroize_"))]
struct Example(#[derive_where(Zeroize(fqs))] i32);

impl Example {
	// If we didn't specify the `fqs` option, this would lead to a compile
	//error because of method ambiguity.
	fn zeroize(&mut self) {
		self.0 = 1;
	}
}

let mut test = Example(42);

// Will call the struct method.
test.zeroize();
assert_eq!(test.0, 1);

// WIll call the `Zeroize::zeroize` method.
Zeroize::zeroize(&mut test);
assert_eq!(test.0, 0);

ZeroizeOnDrop options

If the zeroize-on-drop feature is enabled, it implements ZeroizeOnDrop and can be implemented without Zeroize, otherwise it only implements Drop and requires Zeroize to be implemented.

ZeroizeOnDrop has one option:

  • crate: an item-level option which specifies a path to the zeroize crate in case of a re-export or rename.
#[derive_where(ZeroizeOnDrop(crate = "zeroize_"))]
struct Example(i32);

assert!(core::mem::needs_drop::<Example>());

Supported traits

The following traits can be derived with derive-where:

Supported items

Structs, tuple structs, unions and enums are supported. Derive-where tries it's best to discourage usage that could be covered by std's derive. For example unit structs and enums only containing unit variants aren't supported.

Unions only support Clone and Copy.

no_std support

no_std support is provided by default.

Crate features

MSRV

The current MSRV is 1.57 and is being checked by the CI. A change will be accompanied by a minor version bump. If MSRV is important to you, use derive-where = "~1.x" to pin a specific minor version to your crate.

Alternatives

derivative (Crates.io) is a great alternative with many options. Notably it doesn't support no_std and requires an extra #[derive(Derivative)] to use.

Changelog

See the CHANGELOG file for details.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~225–630KB
~15K SLoC