Crate negate

Source
Expand description

githubcrates-iodocs-rs


negate is a simple attribute macro that negates a given function.

  • [negate]

    Given a function of the form is_* that returns a boolean value, the macro will create a is_not_* that negates the given function.

    use negate::negate;
    #[negate]
    pub fn is_even(x: i32) -> bool {
      x % 2 == 0
    }
    
    // The `is_not_even` function was generated!
    assert!(is_not_even(5));

    For reference, this is how the generated function looks like:

    /// This is an automatically generated function that denies [`is_even`].
    /// Consult the original function for more information.
    pub fn is_not_even(x: i32) -> bool {
      !is_even(x)
    }
  • [negate(name = "...")]

    Using the name attribute allows you to set the name of the generated function. This also allows the usage of the negate macro with functions that do not start with is_.

use negate::negate;
use std::collections::HashMap;

pub enum TaskState {
    Ready,
    Finished,
}

pub struct Reactor {
    tasks: HashMap<usize, TaskState>,
}

impl Reactor {
    // Generates the `is_finished` function
    #[negate(name = "is_finished")]
    pub fn is_ready(&self, id: usize) -> bool {
        self.tasks.get(&id).map(|state| match state {
            TaskState::Ready => true,
            _ => false,
        }).unwrap_or(false)
    }
}
  • [negate(docs = "...")]

    Using the docs attribute allows you to customize the doc-string of the generated function

use negate::negate;
#[negate(name = "is_odd", docs = "returns true if the given number is odd")]
fn is_even(x: i32) -> bool {
   x % 2 == 0
}
assert!(is_odd(5));

Attribute Macros§

negate
The negate attribute macro creates a new function that negates the function it was given. For example, if applied to a function titled is_student, the macro will create a new function named is_not_student, which simply negates the previous function.