Crate konst[][src]

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> {
        // As of Rust 1.51.0, string patterns don't work in const contexts
        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"),
}

Modules

nonzero
other
polymorphism
primitive
range
slice

Functions for comparing slices

Macros

coerce_to_cmp

Coerces reference to a type that has a cosnt_eq method.

const_eq
const_eq_for

Compares two generic standard library types for equality.

impl_cmp
konst
konst_for

Compares two slices for ordering, evaluating to a cmp::Ordering

try_equal

Evaluates to $ord if it is Ordering::Equal, otherwise returns it from the enclosing function.

unwrap_opt

For unwrapping Options in const contexts

unwrap_opt_or

For unwrapping Options in const contexts, with a default value when it’s a None.

unwrap_res

For unwrapping Results in const contexts

unwrap_res_or

For unwrapping Results in const contexts, with a default value when it’s an error.

Functions

cmp_option_str

Compares two Option<&'a str>, returning the ordering of left relative to right.

cmp_str

A const equivalent of str::cmp.

eq_option_str

Compares two Option<&'a str> for equality.

eq_str

A const equivalent of &str equality comparison.