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 forconst
contexts. - const_
assert_ eq - Similar to
assert_eq!
but forconst
contexts. - const_
assert_ ne - Similar to
assert_ne!
but forconst
contexts. - const_
early - Returns early with the provided error if the condition is true.
- const_
err - Same as
Result::err
but forconst
contexts. - const_
map - Same as
Option::map
but forconst
contexts. - const_
map_ err - Same as
Result::map_err
but forconst
contexts. - const_
map_ ok - Same as
Result::map
but forconst
contexts. - const_
none - Equivalent to the
?
operator used onOption
but forconst
contexts. - const_
ok - Same as
Result::ok
but forconst
contexts. - const_
quick - Returns early with
None
if the condition is true. - const_
try - Similar to the
?
operator used onResult
but forconst
contexts.