Const equivalents of std functions and const parsing.
This crate provides:
Const fn equivalents of standard library functions and methods.
Compile-time parsing through the [Parser
] type, and [parser_method
] macro.
This example demonstrates how you can parse a simple enum from an environment variable, at compile-time.
```rust use konst::{ eqstr, option, result::unwrapctx, };
enum Direction { Forward, Backward, Left, Right, }
impl Direction {
const fn tryparse(input: &str) -> Result
const CHOICE: &str = option::unwrapor!(optionenv!("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"), } }
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 { const fn panic(&self) -> ! { panic!("failed to parse a Direction") } }
```
This example demonstrates how CSV can be parsed into integers.
This example requires the "parsing"
and "iter"
features
(both are enabled by default).
```rust use konst::{ primitive::parseu64, result::unwrapctx, iter, string, };
const CSV: &str = "3, 8, 13, 21, 34";
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]);
```
This example demonstrates how a key-value pair format can be parsed into a struct.
This requires the "parsing"
feature (enabled by default).
```rust use konst::{ parsing::{Parser, ParseValueResult}, eqstr, forrange, parsermethod, try, unwrap_ctx, };
const PARSED: Struct = {
// You can also parse strings from environment variables, or from an include_str!(....)
let input = "\
colors = red, blue, green, blue
amount = 1000
repeating = circle
name = bob smith
";
unwrap_ctx!(parse_struct(Parser::new(input))).0
};
fn main(){ assert_eq!( PARSED, Struct{ name: "bob smith", amount: 1000, repeating: Shape::Circle, colors: [Color::Red, Color::Blue, Color::Green, Color::Blue], } ); }
pub struct Struct<'a> { pub name: &'a str, pub amount: usize, pub repeating: Shape, pub colors: [Color; 4], }
pub enum Shape { Circle, Square, Line, }
pub enum Color { Red, Blue, Green, }
pub const fn parsestruct(mut parser: Parser<'>) -> ParseValueResult<', Struct<'>> {
let mut name = "
parser = parser.trim_end();
if !parser.is_empty() {
loop {
let mut prev_parser = parser.trim_start();
parser = try_!(parser.find_skip('='));
parser_method!{prev_parser, strip_prefix;
"name" => (name, parser) = try_!(parser.trim_start().split_keep('\n')),
"amount" => (amount, parser) = try_!(parser.trim_start().parse_usize()),
"repeating" => (repeating, parser) = try_!(parse_shape(parser.trim_start())),
"colors" => (colors, parser) = try_!(parse_colors(parser.trim_start())),
_ => {
let err = &"could not parse Struct field name";
return Err(prev_parser.into_other_error(err));
}
}
if parser.is_empty() {
break
}
parser = try_!(parser.strip_prefix("\n"));
}
}
Ok((Struct{name, amount, repeating, colors}, parser))
}
pub const fn parseshape(mut parser: Parser<'>) -> ParseValueResult<', Shape> { let shape = parsermethod!{parser, stripprefix; "circle" => Shape::Circle, "square" => Shape::Square, "line" => Shape::Line, _ => return Err(parser.intoother_error(&"could not parse Shape")) }; Ok((shape, parser)) }
pub const fn parsecolors
for_range!{i in 0..LEN =>
(colors[i], parser) = try_!(parse_color(parser.trim_start()));
match parser.strip_prefix(",") {
Ok(next) => parser = next,
Err(_) if i == LEN - 1 => {}
Err(e) => return Err(e),
}
}
Ok((colors, parser))
}
pub const fn parsecolor(mut parser: Parser<'>) -> ParseValueResult<', Color> { let color = parsermethod!{parser, stripprefix; "red" => Color::Red, "blue" => Color::Blue, "green" => Color::Green, _ => return Err(parser.intoother_error(&"could not parse Color")) }; Ok((color, parser)) }
```
These are the features of these crates:
"iter"
(enabled by default):
Enables all iteration items, including macros/functions that take/return iterators,
"cmp"
(enabled by default):
Enables all comparison functions and macros,
the string equality and ordering comparison functions don't require this feature.
"parsing_proc"
(enabled by default):
Enables the "parsing"
feature, compiles the konst_proc_macros
dependency,
and enables the [parser_method
] macro.
You can use this feature instead of "parsing"
if the slightly longer
compile times aren't a problem.
"parsing"
(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
.
None of thse features are enabled by default.
"rust_latest_stable"
: enables the latest "rust_1_*"
feature(there's currently none).
Only recommendable if you can update the Rust compiler every stable release.
"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 "rust_latest_stable"
feature.
"nightly_mut_refs"
(disabled by default):
Enables the "mut_refs"
feature. Requires Rust nightly.
konst
is #![no_std]
, it can be used anywhere Rust can be used.
konst
requires Rust 1.65.0.
Features that require newer versions of Rust, or the nightly compiler, need to be explicitly enabled with crate features.