refactor: impl From for Node to easily insert constants

this is mostly useful for tests and in Node::from_name
This commit is contained in:
electria 2026-10-04 16:22:53 -07:00
commit 69bf8f4635
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs
2 changed files with 19 additions and 11 deletions

View file

@ -4,7 +4,7 @@
use std::fmt::{Debug, Display}; use std::fmt::{Debug, Display};
use rug::Float; use rug::{Assign, Float};
mod eval; mod eval;
pub mod parse; pub mod parse;
@ -53,6 +53,14 @@ impl Display for Node {
Debug::fmt(&self, f) Debug::fmt(&self, f)
} }
} }
impl<T> From<T> for Node
where
Float: Assign<T>,
{
fn from(value: T) -> Self {
Self::Number(Float::with_val(PREC, value))
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq)] #[derive(Debug, Default, Copy, Clone, PartialEq)]
pub enum Operator { pub enum Operator {

View file

@ -8,12 +8,12 @@ use crate::nodes::{Function, Node, Nodes, Operator, PREC};
impl Node { impl Node {
fn from_name(s: &str) -> Result<Self, String> { fn from_name(s: &str) -> Result<Self, String> {
Ok(match s { Ok(match s {
"c" => Self::Number(Float::with_val(PREC, 299_792_458)), "c" => Self::from(299_792_458),
"A" => Self::Number(Float::with_val(PREC, 6.02214076e23)), "A" => Self::from(6.02214076e23),
"pi" => Self::Number(Float::with_val(PREC, f64::consts::PI)), "pi" => Self::from(f64::consts::PI),
// Planck's constant, in J*s (joule-seconds) // Planck's constant, in J*s (joule-seconds)
"h" => Self::Number(Float::with_val(PREC, 6.62607015e-34)), "h" => Self::from(6.62607015e-34),
"e" => Self::Number(Float::with_val(PREC, f64::consts::E)), "e" => Self::from(f64::consts::E),
_ => Self::Function(s.parse()?), _ => Self::Function(s.parse()?),
}) })
} }
@ -203,10 +203,10 @@ fn test() {
&[ &[
Node::Function(Function::Sine), Node::Function(Function::Sine),
Node::ParenthesisStart, Node::ParenthesisStart,
Node::Number(Float::with_val(PREC, 2)), Node::from(2),
Node::ParenthesisEnd, Node::ParenthesisEnd,
Node::Operator(Operator::Plus), Node::Operator(Operator::Plus),
Node::Number(Float::with_val(PREC, 1)) Node::from(1),
], ],
) )
} }
@ -215,11 +215,11 @@ fn test_e() {
assert_eq!( assert_eq!(
Nodes::from_str("5e * 5").unwrap().as_ref(), Nodes::from_str("5e * 5").unwrap().as_ref(),
&[ &[
Node::Number(Float::with_val(PREC, 5)), Node::from(5),
Node::Operator(Operator::Mult), Node::Operator(Operator::Mult),
Node::Number(Float::with_val(PREC, f64::consts::E)), Node::from(f64::consts::E),
Node::Operator(Operator::Mult), Node::Operator(Operator::Mult),
Node::Number(Float::with_val(PREC, 5)) Node::from(5),
], ],
) )
} }