From e241b824cc633ffe76f6280469f27e559a96f6f6 Mon Sep 17 00:00:00 2001 From: Valerie Date: Mon, 13 Jun 2022 00:18:32 -0400 Subject: [PATCH] made average helper function and made an initial implementation of a hex parser/formatter --- src/helper.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 13 +++++++++-- 2 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 src/helper.rs diff --git a/src/helper.rs b/src/helper.rs new file mode 100644 index 0000000..0a20097 --- /dev/null +++ b/src/helper.rs @@ -0,0 +1,65 @@ +use evalexpr::{ + Value, + + EvalexprError +}; + +pub fn average(arg: &Value) -> Result { + let arguments = arg.as_tuple()?; + let count = arguments.len() as i64; + let mut is_float = false; + let mut total_i = 0i64; + let mut total_f = 0f64; + + for argument in arguments { + if let Value::Float(float) = argument { + if !is_float { + total_f = total_i as f64; + is_float = true; + } + total_f += float; + } else if let Value::Int(int) = argument { + if is_float { + total_f += int as f64; + } else { + total_i += int; + } + } + } + + let result_i: i64; + let result_f: f64; + if !is_float { + is_float = total_i % count == 0; + total_f = total_i as f64; + } + + if is_float { + result_f = total_f / (count as f64); + return Ok(result_f.into()); + } else { + result_i = total_i / count; + return Ok(result_i.into()); + } +} + +pub fn hex(arg: &Value) -> Option { + if !arg.is_string() { + if arg.is_int() { + let num = arg.as_int().ok().unwrap(); + let fmt = format!("0x{:X}", num); + return Some(fmt.into()); + } + return None; + } + let i_parse = arg.as_string().ok().unwrap(); + let parse = i_parse.strip_prefix("0x").unwrap_or(i_parse.as_str()); + + let i_result = i64::from_str_radix(parse, 16); + if i_result.is_err() { return None; } + let result: Option = i_result.ok(); + if result.is_none() { return None; } + + let output: Value = result.unwrap().into(); + return Some(output); +} diff --git a/src/main.rs b/src/main.rs index 55dcf87..fedf5ea 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,8 @@ use std::{ }; use evalexpr::{ + context_map, + eval_with_context_mut, HashMapContext, @@ -19,11 +21,18 @@ use termion::{ style }; +mod helper; + +pub const VERSION: &str = "0.1.4"; + fn main() { - let mut context = HashMapContext::new(); + let mut context = context_map! { + "avg" => Function::new(|arg| helper::average(arg)), + "hex" => Function::new(|arg| Ok(helper::hex(arg).unwrap_or(0.into()))) + }.unwrap(); let expressions: Vec = env::args().skip(1).collect(); if expressions.len() == 0 { - println!("{}quickmaths v0.1.3{}\n{}Interactive Mode{}", style::Bold, style::Reset, style::Faint, style::Reset); + println!("{}quickmaths v{}{}\n{}Interactive Mode{}", style::Bold, VERSION, style::Reset, style::Faint, style::Reset); loop { print!("> "); stdout().flush().unwrap();