sim_lib_view_math/num.rs
1//! Numeric helpers shared by the math lenses.
2//!
3//! The math lenses display values from the numeric domains (`sim-lib-numbers-*`)
4//! by reading their canonical literal as `f64` for layout. The runtime value
5//! stays the authoritative number; this is a display projection only.
6
7use sim_kernel::{Expr, NumberLiteral, Symbol};
8
9/// Build an `f64`-domain number value.
10pub fn number(value: f64) -> Expr {
11 Expr::Number(NumberLiteral {
12 domain: Symbol::new("f64"),
13 canonical: format_f64(value),
14 })
15}
16
17/// Read a number value's canonical literal as `f64`, if it is a number.
18pub fn as_f64(value: &Expr) -> Option<f64> {
19 match value {
20 Expr::Number(number) => number.canonical.parse::<f64>().ok(),
21 _ => None,
22 }
23}
24
25/// Format an `f64` canonically (integers without a trailing `.0` noise).
26pub fn format_f64(value: f64) -> String {
27 if value.fract() == 0.0 && value.is_finite() {
28 format!("{}", value as i64)
29 } else {
30 format!("{value}")
31 }
32}
33
34/// Build a 2D point value `[x, y]`.
35pub fn point(x: f64, y: f64) -> Expr {
36 Expr::Vector(vec![number(x), number(y)])
37}