trait_guard 0.1.0

A Rust library for disallowing usage of certain trait implementations with custom messages.
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented2 out of 2 items with examples
  • Size
  • Source code size: 7.55 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.09 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 13s Average build duration of successful builds.
  • all releases: 13s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • DavidHancu/trait_guard
    1 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • DavidHancu

trait_guard

trait_guard is a macro used to protect a trait implementation from usage with a custom message, note, and label.

It abuses the on_unimplemented attribute to provide a custom error message when the trait is not implemented. It requires the negative_impls and trivial_bounds nightly features to be enabled.

You can use any trait (even if it's an STD trait or from another crate)!

Installation

To use trait_guard, run the following command in your terminal:

cargo add trait_guard

Example usage:

trait_guard!(
    MyType, // the type that will be guarded
    MyTrait, // the trait that is being guarded

    trait_guard = MyGuardTrait, // optional: custom name for the guard trait, shown in the diagnostic message
    guard_struct = MyGuardStruct, // optional: custom name for the guard struct, shown in the diagnostic message

    {
        // this is the body of the trait implementation
        fn my_method(&self) {
            // implementation
        }
    },

    message = "MyType does not implement MyTrait",
//  note = "This is a custom note",
//  label = "MyType needs to implement MyTrait"
);

The example above will refuse to compile if the MyTrait implementation of MyType is used anywhere in the user's code.

If you want to guard multiple traits/types, you can change the name of trait_guard and guard_struct to avoid conflicts.

Example for [std::fmt::Display]

use trait_guard::trait_guard;

#[derive(Debug)]
struct A;

trait_guard!(
    A, // the type that will be guarded
    std::fmt::Display, // the trait that is being guarded

    {
       // this is the body of the trait implementation
       fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
           unreachable!("It will never be called because A does not implement Display");
       }
    },

    message = "A does not implement std::fmt::Display",
);