(val: &Value, to_type: &crate::expr::CastType)
| 6 | use nodedb_types::Value; |
| 7 | |
| 8 | pub fn eval_cast(val: &Value, to_type: &crate::expr::CastType) -> Value { |
| 9 | use crate::expr::CastType; |
| 10 | match to_type { |
| 11 | CastType::Int => match val { |
| 12 | Value::Integer(_) => val.clone(), |
| 13 | Value::Float(f) => Value::Integer(*f as i64), |
| 14 | Value::String(s) => s.parse::<i64>().map(Value::Integer).unwrap_or(Value::Null), |
| 15 | Value::Bool(b) => Value::Integer(*b as i64), |
| 16 | Value::Decimal(d) => { |
| 17 | use rust_decimal::prelude::ToPrimitive; |
| 18 | d.to_i64().map(Value::Integer).unwrap_or(Value::Null) |
| 19 | } |
| 20 | _ => Value::Null, |
| 21 | }, |
| 22 | CastType::Float => match val { |
| 23 | Value::Float(_) => val.clone(), |
| 24 | Value::Integer(i) => Value::Float(*i as f64), |
| 25 | Value::String(s) => s |
| 26 | .parse::<f64>() |
| 27 | .map(Value::Float) |
| 28 | .ok() |
| 29 | .unwrap_or(Value::Null), |
| 30 | Value::Decimal(d) => { |
| 31 | use rust_decimal::prelude::ToPrimitive; |
| 32 | d.to_f64().map(Value::Float).unwrap_or(Value::Null) |
| 33 | } |
| 34 | _ => Value::Null, |
| 35 | }, |
| 36 | CastType::String => Value::String(value_to_display_string(val)), |
| 37 | CastType::Bool => Value::Bool(is_truthy(val)), |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | #[cfg(test)] |
| 42 | mod tests { |
no test coverage detected