Const equivalents of std functions, compile-time comparison, and parsing.
This crate provides:
Const fn equivalents of standard library functions and methods.
Compile-time parsing through the [Parser
] type, and [parse_any
] macro.
Functions for comparing many standard library types,
with the [const_eq
]/[const_eq_for
]/[const_cmp
]/[const_cmp_for
] macros
for more conveniently calling them, powered by the [polymorphism
] module.
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};
enum Direction { Forward, Backward, Left, Right, }
impl Direction {
const fn tryparse(input: &str) -> Result
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"), } }
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) -> ! { [/failed to parse a Direction/][0] } }
```
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.
```rust use konst::{ primitive::{ParseIntResult, parsei128}, result::unwrapctx, };
const N100: ParseIntResult
const NN3: ParseIntResult
// This is how you can unwrap integers parsed from strings, at compile-time. const N100UNW: i128 = unwrapctx!(parsei128("1337")); asserteq!(N100_UNW, 1337);
const NONE: ParseIntResult
const PAIR: ParseIntResult
```
For parsing an integer inside a larger string,
you can use [Parser::parse_u128
] method and the other parse_*
methods
```rust 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)
}; asserteq!(PAIR.0, 1365); asserteq!(PAIR.1, 6789);
```
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], } ); }
pub struct Struct { 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> { 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)) }
```
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.
konst
is #![no_std]
, it can be used anywhere Rust can be used.
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.