File: unsafe-vars.rs

package info (click to toggle)
rust-fasteval 0.2.4-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 952 kB
  • sloc: python: 14; makefile: 8
file content (42 lines) | stat: -rw-r--r-- 1,845 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// usage:  cargo run --release --features unsafe-vars --example unsafe-vars

fn main() -> Result<(), fasteval::Error> {
    #[cfg(not(feature="unsafe-vars"))]
    {
        panic!("You must enable the `unsafe-vars` feature to run this example:  cargo run --release --features unsafe-vars --example unsafe-vars");
    }

    // Allow compilation even when the `unsafe-vars` feature is not enabled.
    // This is important so that `cargo test` can succeed.
    #[cfg(feature="unsafe-vars")]
    {
        use fasteval::Evaler;    // use this trait so we can call eval().
        use fasteval::Compiler;  // use this trait so we can call compile().

        let parser = fasteval::Parser::new();
        let mut slab = fasteval::Slab::new();

        // The Unsafe Variable will use a pointer to read this memory location:
        // You must make sure that this variable stays in-scope as long as the
        // expression is in-use.
        let mut deg : f64 = 0.0;

        // Unsafe Variables must be registered before 'parse()'.
        // (Normal Variables only need definitions during the 'eval' phase.)
        unsafe { slab.ps.add_unsafe_var("deg".to_string(), &deg); } // `add_unsafe_var()` only exists if the `unsafe-vars` feature is enabled: `cargo test --features unsafe-vars`

        let expr_str = "sin(deg/360 * 2*pi())";
        let compiled = parser.parse(expr_str, &mut slab.ps)?.from(&slab.ps).compile(&slab.ps, &mut slab.cs);

        let mut ns = fasteval::EmptyNamespace;  // We only define unsafe variables, not normal variables,
                                                // so EmptyNamespace is fine.

        for d in 0..360 {
            deg = d as f64;
            let val = fasteval::eval_compiled!(compiled, &slab, &mut ns);
            eprintln!("sin({}°) = {}", deg, val);
        }

        Ok(())
    }
}