mathexpr
A fast, safe mathematical expression parser and evaluator for Rust.
Features
- Fast - Compiles expressions to bytecode for efficient repeated evaluation (~15-80ns per eval)
- Safe - No unsafe code, proper error handling
no_stdcompatible - Works in embedded environments withalloc- Rich function library - 27 built-in functions including trig, logarithms, rounding, and more
Quick Start
use Expression;
// Parse, compile, and evaluate
let expr = parse?
.compile?;
assert_eq!;
assert_eq!;
One-liner Evaluation
For simple cases where you don't need to reuse the compiled expression:
use eval;
let result = eval?;
// result ≈ 31.4159
Current Value (_)
Use _ to reference an input value, useful for transformations:
use Expression;
let normalize = parse?
.compile?;
// Normalize 50 to range [0, 100]
let result = normalize.eval_with_current?;
assert_eq!;
Operators
| Operator | Description | Precedence |
|---|---|---|
+, - |
Addition, Subtraction | Lowest |
*, /, % |
Multiplication, Division, Modulo | Medium |
^ |
Exponentiation (right-associative) | Highest |
-x |
Unary negation | Highest |
Functions
Core Math
| Function | Description |
|---|---|
abs(x) |
Absolute value |
sqrt(x) |
Square root |
cbrt(x) |
Cube root |
exp(x) |
Exponential (e^x) |
log(x), ln(x) |
Natural logarithm |
log2(x) |
Base-2 logarithm |
log10(x) |
Base-10 logarithm |
pow(base, exp) |
Power |
mod(a, b) |
Modulo |
min(a, b) |
Minimum |
max(a, b) |
Maximum |
clamp(x, min, max) |
Clamp to range |
Trigonometric
| Function | Description |
|---|---|
sin(x), cos(x), tan(x) |
Basic trig |
asin(x), acos(x), atan(x) |
Inverse trig |
sinh(x), cosh(x), tanh(x) |
Hyperbolic |
Rounding
| Function | Description |
|---|---|
floor(x) |
Round down |
ceil(x) |
Round up |
round(x) |
Round to nearest |
trunc(x) |
Truncate toward zero |
signum(x) |
Sign (-1, 0, or 1) |
Constants
| Constant | Description |
|---|---|
pi or pi() |
π ≈ 3.14159... |
e or e() |
Euler's number ≈ 2.71828... |
Error Handling
mathexpr provides three error types:
use ;
// Parse errors - invalid syntax
match parse
// Compile errors - undefined variables or unknown functions
match parse?.compile
// Eval errors - runtime errors
match expr.eval
Note: Domain errors (like sqrt(-1)) return NaN rather than errors.
Performance
Typical evaluation times on modern hardware:
| Expression Complexity | Time per Eval |
|---|---|
Simple (a + b) |
~15 ns |
Medium (sqrt(x^2 + y^2)) |
~25 ns |
| Complex (5+ functions) | ~60-80 ns |
Examples
Run the included examples:
# Basic API usage
# Error handling patterns
# Interactive calculator with history
Feature Flags
| Feature | Description |
|---|---|
std (default) |
Enables std::error::Error implementations |
For no_std environments:
[]
= { = "0.1", = false }
Requires the alloc crate.
License
MIT License. See LICENSE for details.