Compile-time comparison, parsing, and other const functionality.
Features
This crate provides:
-
Many functions for comparing standard library types.
-
Macros to make it easier to do those comparisons, powered by the [polymorphism
] module.
Examples
Parsing an enum
This example demonstrates how you can parse a simple enum from an environment variable,
at compile-time.
use konst::eq_str;
use konst::{unwrap_opt_or, unwrap_res};
#[derive(Debug, PartialEq)]
enum Direction {
Forward,
Backward,
Left,
Right,
}
impl Direction {
const fn try_parse(input: &str) -> Result<Self, ParseDirectionError> {
match () {
_ if eq_str(input, "forward") => Ok(Direction::Forward),
_ if eq_str(input, "backward") => Ok(Direction::Backward),
_ if eq_str(input, "left") => Ok(Direction::Left),
_ if eq_str(input, "right") => Ok(Direction::Right),
_ => Err(ParseDirectionError),
}
}
}
const CHOICE: &str = unwrap_opt_or!(option_env!("chosen-direction"), "forward");
const DIRECTION: Direction = unwrap_res!(Direction::try_parse(CHOICE));
match DIRECTION {
Direction::Forward => assert_eq!(CHOICE, "forward"),
Direction::Backward => assert_eq!(CHOICE, "backward"),
Direction::Left => assert_eq!(CHOICE, "left"),
Direction::Right => assert_eq!(CHOICE, "right"),
}
# #[derive(Debug, PartialEq)]
# pub struct ParseDirectionError;
#
# use std::fmt::{self, Display};
#
# impl Display for Direction {
# fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
# f.write_str("Failed to parse a Direction")
# }
# }
#