konst/macros/
control_flow.rs

1/// For loop over a range
2///
3/// # Example
4///
5/// ```
6/// use konst::for_range;    
7///     
8/// const LEN: usize = 10;
9/// const ARR: [u32; LEN] = {
10///     let mut ret = [1; LEN];
11///     for_range!{i in 2..LEN =>
12///         ret[i] = ret[i - 1] + ret[i - 2];
13///     }
14///     ret
15/// };
16///
17/// assert_eq!(ARR, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);
18///
19/// ```
20#[macro_export]
21macro_rules! for_range {
22    ($pat:pat in $range:expr => $($code:tt)*) => {
23        let $crate::__::Range{mut start, end} = $range;
24
25        while start < end {
26            let $pat = start;
27
28            $($code)*
29
30            start+=1;
31        }
32    };
33}
34
35/// Emulates the [inline const feature], eg: `const{ foo() }`,
36///
37/// As opposed to inline const, you must pass the type that the expression evaluates to.
38///
39/// # Limitations
40///
41/// This can't be used with expressions that reference generic parameters.
42///
43/// # Example
44///
45/// ```rust
46/// use konst::{konst, eq_str};
47///
48/// const FOO: &str = "hello";
49///
50/// # const _: bool = konst!{bool, eq_str(FOO, "hi")};
51/// #
52/// // By using `konst` here, the function is unconditionally evaluated at compile-time.
53/// if konst!{bool, eq_str(FOO, "hi")} {
54///     panic!("The constants are equal, this wasn't supposed to happen!!");
55/// }
56///
57/// ```
58///
59///
60/// [inline const feature]:
61/// https://doc.rust-lang.org/1.50.0/unstable-book/language-features/inline-const.html
62#[macro_export]
63macro_rules! konst {
64    ($type:ty, $expr:expr $(,)*) => {{
65        const __KONST__: $type = $expr;
66        __KONST__
67    }};
68}