Crate konst[][src]

Expand description

Const equivalents of std functions, compile-time comparison, and parsing.


This crate provides:


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_ctx};

#[derive(Debug, PartialEq)]
enum Direction {

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_ctx!(Direction::try_parse(CHOICE));

fn main() {
    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"),

Parsing integers

You can parse integers using the parse_* functions in primitive, returning an Err(ParseIntError{...}) if the string as a whole isn’t a valid integer.

use konst::{
    primitive::{ParseIntResult, parse_i128},

const N_100: ParseIntResult<i128> = parse_i128("100");
assert_eq!(N_100, Ok(100));

const N_N3: ParseIntResult<i128> = parse_i128("-3");
assert_eq!(N_N3, Ok(-3));

// This is how you can unwrap integers parsed from strings, at compile-time.
const N_100_UNW: i128 = unwrap_ctx!(parse_i128("1337"));
assert_eq!(N_100_UNW, 1337);

const NONE: ParseIntResult<i128> = parse_i128("-");

const PAIR: ParseIntResult<i128> = parse_i128("1,2");

For parsing an integer inside a larger string, you can use Parser::parse_u128 method and the other parse_* methods

use konst::{Parser, unwrap_ctx};

const PAIR: (i64, u128) = {;
    let parser = Parser::from_str("1365;6789");

    // Parsing "1365"
    let (l, parser) = unwrap_ctx!(parser.parse_i64());

    // Skipping the ";"
    let parser = unwrap_ctx!(parser.strip_prefix(";"));

    // Parsing "6789"
    let (r, parser) = unwrap_ctx!(parser.parse_u128());
    (l, r)
assert_eq!(PAIR.0, 1365);
assert_eq!(PAIR.1, 6789);

Parsing a struct

This example demonstrates how you can use Parser to parse a struct at compile-time.

use konst::{
    parsing::{Parser, ParseValueResult},
    for_range, parse_any, try_rebind, unwrap_ctx,

const PARSED: Struct = {
    // You can also parse strings from environment variables, or from an `include_str!(....)`
    let input = "\
        red, blue, green, blue,

fn main(){
            amount: 1000,
            repeating: Shape::Circle,
            colors: [Color::Red, Color::Blue, Color::Green, Color::Blue],

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Struct {
    pub amount: usize,
    pub repeating: Shape,
    pub colors: [Color; 4],

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Shape {

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Color {

pub const fn parse_struct(mut parser: Parser<'_>) -> ParseValueResult<'_, Struct> {
    try_rebind!{(let amount, parser) = parser.trim_start().parse_usize()}
    try_rebind!{parser = parser.strip_prefix(",")}

    try_rebind!{(let repeating, parser) = parse_shape(parser.trim_start())}
    try_rebind!{parser = parser.strip_prefix(",")}

    try_rebind!{(let colors, parser) = parse_colors(parser.trim_start())}

    Ok((Struct{amount, repeating, colors}, parser))

pub const fn parse_shape(mut parser: Parser<'_>) -> ParseValueResult<'_, Shape> {
    let shape = parse_any!{parser, strip_prefix;
        "circle" => Shape::Circle,
        "square" => Shape::Square,
        "line" => Shape::Line,
        _ => return Err(parser.into_other_error())
    Ok((shape, parser))

pub const fn parse_colors(mut parser: Parser<'_>) -> ParseValueResult<'_, [Color; 4]> {
    let mut colors = [Color::Red; 4];

    for_range!{i in 0..4 =>
        try_rebind!{(colors[i], parser) = parse_color(parser.trim_start())}
        try_rebind!{parser = parser.strip_prefix(",")}

    Ok((colors, parser))

pub const fn parse_color(mut parser: Parser<'_>) -> ParseValueResult<'_, Color> {
    let color = parse_any!{parser, strip_prefix;
        "red" => Color::Red,
        "blue" => Color::Blue,
        "green" => Color::Green,
        _ => return Err(parser.into_other_error())
    Ok((color, parser))

Cargo features

These are the features of these crates:

  • "cmp"(enabled by default): Enables all comparison functions and macros, the string equality and ordering comparison functions don’t require this feature.

  • "parsing"(enabled by default): Enables the "parsing_no_proc" feature, compiles the konst_proc_macros dependency, and enables the parse_any macro. You can use this feature instead of "parsing_no_proc" if the slightly longer compile times aren’t a problem.

  • "parsing_no_proc"(enabled by default): Enables the parsing module (for parsing from &str and &[u8]), the primitive::parse_* functions, try_rebind, and rebind_if_ok macros.

  • alloc": Enables items that use types from the alloc crate, including Vec and String.

  • "const_generics" (disabled by default): Requires Rust 1.51.0. Enables items that require const generics, and impls for arrays to use const generics instead of only supporting small arrays.

  • "rust_1_55": Enables the string::from_utf8 function (the macro works in all versions), str indexing functions, and the "const_generics" feature.

  • "rust_1_56": Enables functions that internally use raw pointer dereferences or transmutes, and the "rust_1_55" feature.
    Because this crate feature was added before Rust 1.56.0 is released, those unsafe operations might be unstabilized, in which case you’ll need to use Rust nightly and the "deref_raw_in_fn" crate feature.

  • "deref_raw_in_fn" (disabled by default): Requires Rust nightly. Fallback for the case where the "rust_1_56" feature causes compilation errors because Rust features were unstabilized before the release.

  • "constant_time_slice"(disabled by default):
    Requires Rust nightly. Improves the performance of slice functions that split slices, from taking linear time to taking constant time.
    Note that only functions which mention this feature in their documentation are affected.

  • "mut_refs"(disabled by default): Enables const functions that take mutable references. Use this whenever mutable references in const contexts are stabilized. Also enables the "deref_raw_in_fn" and "rust_1_56" features.

  • "nightly_mut_refs"(disabled by default): Enables the "mut_refs" feature. Requires Rust nightly.

No-std support

konst is #![no_std], it can be used anywhere Rust can be used.

Minimum Supported Rust Version

konst requires Rust 1.46.0, because it uses looping an branching in const contexts.

Features that require newer versions of Rust, or the nightly compiler, need to be explicitly enabled with cargo features.


pub use crate::parsing::Parser;
pub use crate::string::cmp_str;
pub use crate::string::eq_str;
pub use crate::result::unwrap_ctx;
pub use crate::string::cmp_option_str;
pub use crate::string::eq_option_str;


Generic constants for types from the alloc crate, including String and Vec.

Const equivalents of array functions.


Const fn equivalents of ManuallyDrop<T> methods.

Const fn equivalents of MaybeUninit<T> methods.

const fn equivalents of NonZero* methods.

const equivalents of Option methods.

const fn equivalents of methods from miscelaneous standard library types.


Parsing using const fn methods.

Machinery for making the comparison macros work with both standard and user-defined types.

const fn equivalents of primitive type methods.

Const equivalents of raw pointer and NonNull methods.

const fn equivalents of range methods.

const equivalents of Result methods.

const fn equivalents of slice methods.

const fn equivalents of str methods.


Coerces reference to a type that has a const_eq or const_cmp method.

Compares two values for ordering.

Compares two standard library types for ordering, that can’t be compared with const_cmp.

Compares two values for equality.

Compares two standard library types for equality, that can’t be compared with const_eq.

For loop over a range

For implementing const comparison semi-manually.

Emulates the inline const feature, eg: const{ foo() },


Calls a Parser method with many alternative string literals.

Parses a type that impls ParserFor with the passed in Parser.


Like an if let Ok, but also reassigns variables with the value in the Ok variant.

?-like macro, which allows optionally mapping errors.

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

?-like macro for Options.


Like the ? operator, but also reassigns variables with the value in the Ok variant.


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


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