Rust crates-io api-docs

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

Features

This crate provides:

Examples

Parsing an enum

This example demonstrates how you can parse a simple enum from an environment variable, at compile-time.

```rust use konst::eqstr; use konst::{unwrapoptor, unwrapctx};

[derive(Debug, PartialEq)]

enum Direction { Forward, Backward, Left, Right, }

impl Direction { const fn tryparse(input: &str) -> Result { // As of Rust 1.51.0, string patterns don't work in const contexts match () { _ if eqstr(input, "forward") => Ok(Direction::Forward), _ if eqstr(input, "backward") => Ok(Direction::Backward), _ if eqstr(input, "left") => Ok(Direction::Left), _ if eq_str(input, "right") => Ok(Direction::Right), _ => Err(ParseDirectionError), } } }

const CHOICE: &str = unwrapoptor!(option_env!("chosen-direction"), "forward");

const DIRECTION: Direction = unwrapctx!(Direction::tryparse(CHOICE));

fn main() { match DIRECTION { Direction::Forward => asserteq!(CHOICE, "forward"), Direction::Backward => asserteq!(CHOICE, "backward"), Direction::Left => asserteq!(CHOICE, "left"), Direction::Right => asserteq!(CHOICE, "right"), } }

[derive(Debug, PartialEq)]

pub struct ParseDirectionError;

use std::fmt::{self, Display};

impl Display for ParseDirectionError { fn fmt(&self, f: &mut fmt::Formatter<'>) -> fmt::Result { f.writestr("Failed to parse a Direction") } }

impl ParseDirectionError { #[allow(unconditional_panic)] const fn panic(&self) -> ! { [/failed to parse a Direction/][0] } }

```

Parsing CSV

This example demonstrates how an CSV environment variable can be parsed into integers.

This requires the "rust_1_64" and ""parsing_no_proc"" features (the latter is enabled by default).

```rust use konst::{ primitive::parseu64, result::unwrapctx, iter, string, };

const CSV: &str = env!("NUMBERS");

static PARSED: [u64; 5] = iter::collectconst!(u64 => string::split(CSV, ","), map(string::trim), map(|s| unwrapctx!(parse_u64(s))), );

assert_eq!(PARSED, [3, 8, 13, 21, 34]);

```

Parsing a struct

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

```rust use konst::{ parsing::{Parser, ParseValueResult}, forrange, parseany, tryrebind, unwrapctx, };

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

unwrap_ctx!(parse_struct(Parser::from_str(input))).0

};

fn main(){ assert_eq!( PARSED, Struct{ 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 { Circle, Square, Line, }

[derive(Debug, Copy, Clone, PartialEq, Eq)]

pub enum Color { Red, Blue, Green, }

pub const fn parsestruct(mut parser: Parser<'>) -> ParseValueResult<', Struct> { tryrebind!{(let amount, parser) = parser.trimstart().parseusize()} tryrebind!{parser = parser.stripprefix(",")}

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 parseshape(mut parser: Parser<'>) -> ParseValueResult<', Shape> { let shape = parseany!{parser, stripprefix; "circle" => Shape::Circle, "square" => Shape::Square, "line" => Shape::Line, _ => return Err(parser.intoother_error()) }; Ok((shape, parser)) }

pub const fn parsecolors(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 parsecolor(mut parser: Parser<'>) -> ParseValueResult<', Color> { let color = parseany!{parser, stripprefix; "red" => Color::Red, "blue" => Color::Blue, "green" => Color::Green, _ => return Err(parser.intoother_error()) }; Ok((color, parser)) }

```

Cargo features

These are the features of these crates:

Rust release related

None of thse features are enabled by default.

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.