Crate const_macros

Source
Expand description

Various macros for const contexts.

§Examples

Below is an example that utilizes most of the macros provided by this crate.

use const_macros::{const_assert, const_early, const_ok, const_try};

use thiserror::Error;

#[derive(Error, Debug)]
#[error("unexpected length: `{value}`")]
pub struct Error {
    pub value: usize,
}

impl Error {
    pub const fn new(value: usize) -> Self {
        Self { value }
    }
}

pub const MIN: usize = 32;
pub const MAX: usize = 96;

const_assert!(MIN <= MAX);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Length {
    value: usize,
}

impl Length {
    pub const fn new(value: usize) -> Result<Self, Error> {
        const_try!(Self::check(value));

        Ok(unsafe { Self::new_unchecked(value) })
    }

    pub const fn new_ok(value: usize) -> Option<Self> {
        const_ok!(Self::new(value))
    }

    pub const fn check(value: usize) -> Result<(), Error> {
        const_early!(value < MIN || value > MAX => Error::new(value));

        Ok(())
    }

    pub const unsafe fn new_unchecked(value: usize) -> Self {
        Self { value }
    }

    pub const MIN: Self = Self::new_ok(MIN).unwrap();
    pub const MAX: Self = Self::new_ok(MAX).unwrap();
}

Macros§

const_assert
Similar to assert! but for const contexts.
const_assert_eq
Similar to assert_eq! but for const contexts.
const_assert_ne
Similar to assert_ne! but for const contexts.
const_early
Returns early with the provided error if the condition is true.
const_err
Same as Result::err but for const contexts.
const_map
Same as Option::map but for const contexts.
const_map_err
Same as Result::map_err but for const contexts.
const_map_ok
Same as Result::map but for const contexts.
const_none
Equivalent to the ? operator used on Option but for const contexts.
const_ok
Same as Result::ok but for const contexts.
const_quick
Returns early with None if the condition is true.
const_try
Similar to the ? operator used on Result but for const contexts.