Skip to content

Commit

Permalink
float function
Browse files Browse the repository at this point in the history
  • Loading branch information
adamtrilling committed Mar 10, 2022
1 parent 6b5098c commit dd39d05
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
23 changes: 23 additions & 0 deletions rust/src/eval/function/float.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use crate::{Error, Result};

pub fn float(args: Vec<serde_json::Value>) -> Result<serde_json::Value> {
if let Some(val) = args.get(0) {
match val {
// serde_json::from_str(pair.as_str());
serde_json::Value::Number(num) => match num.as_f64() {
Some(float_num) => Ok(serde_json::Value::from(float_num)),
None => Err(Error::eval(format!("invalid number {}", num))),
},
serde_json::Value::String(string) => match string.trim().parse::<f64>() {
Ok(val) => Ok(val.into()),
Err(err) => Err(Error::eval(err.to_string())),
},
serde_json::Value::Bool(true) => Ok(serde_json::Value::from(1.0)),
serde_json::Value::Bool(false) => Ok(serde_json::Value::from(0.0)),
serde_json::Value::Null => Ok(serde_json::Value::from(0.0)),
_ => Err(Error::eval("argument does not cast to float".to_string())),
}
} else {
Err(Error::eval("float requires one argument".to_string()))
}
}
4 changes: 4 additions & 0 deletions rust/src/eval/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ use std::str::FromStr;
use crate::eval::expr;
use crate::{Error, Result, Rule};

mod float;
mod string;

enum Function {
Count,
Float,
Log,
String,
}
Expand All @@ -18,6 +20,7 @@ impl FromStr for Function {
fn from_str(s: &str) -> Result<Self> {
match s {
"count" => Ok(Function::Count),
"float" => Ok(Function::Float),
"log" => Ok(Function::Log),
"string" => Ok(Function::String),
_ => Err(Error::query(format!("unknown function {}", s))),
Expand All @@ -34,6 +37,7 @@ pub fn eval(pair: Pair<Rule>, context: &serde_json::Value) -> Result<serde_json:

match function {
Function::Count => count(args),
Function::Float => float::float(args),
Function::Log => log(args),
Function::String => string::string(args),
}
Expand Down

0 comments on commit dd39d05

Please sign in to comment.