From 45b35927399704d6184d9d299e1dff000c8ed147 Mon Sep 17 00:00:00 2001 From: JT <547158+jntrnr@users.noreply.github.com> Date: Thu, 20 Jan 2022 13:23:26 -0500 Subject: [PATCH] add some more division for units (#783) --- crates/nu-parser/src/type_check.rs | 2 ++ crates/nu-protocol/src/value/mod.rs | 34 +++++++++++++++++++++++++++++ src/tests/test_engine.rs | 10 +++++++++ 3 files changed, 46 insertions(+) diff --git a/crates/nu-parser/src/type_check.rs b/crates/nu-parser/src/type_check.rs index a362645add..2d6bff4bcc 100644 --- a/crates/nu-parser/src/type_check.rs +++ b/crates/nu-parser/src/type_check.rs @@ -115,6 +115,8 @@ pub fn math_result_type( (Type::Float, Type::Int) => (Type::Float, None), (Type::Int, Type::Float) => (Type::Float, None), (Type::Float, Type::Float) => (Type::Float, None), + (Type::Filesize, Type::Filesize) => (Type::Float, None), + (Type::Duration, Type::Duration) => (Type::Float, None), (Type::Unknown, _) => (Type::Unknown, None), (_, Type::Unknown) => (Type::Unknown, None), diff --git a/crates/nu-protocol/src/value/mod.rs b/crates/nu-protocol/src/value/mod.rs index 660c3c3ed2..c050ea0186 100644 --- a/crates/nu-protocol/src/value/mod.rs +++ b/crates/nu-protocol/src/value/mod.rs @@ -1110,6 +1110,40 @@ impl Value { Err(ShellError::DivisionByZero(op)) } } + (Value::Filesize { val: lhs, .. }, Value::Filesize { val: rhs, .. }) => { + if *rhs != 0 { + if lhs % rhs == 0 { + Ok(Value::Int { + val: lhs / rhs, + span, + }) + } else { + Ok(Value::Float { + val: (*lhs as f64) / (*rhs as f64), + span, + }) + } + } else { + Err(ShellError::DivisionByZero(op)) + } + } + (Value::Duration { val: lhs, .. }, Value::Duration { val: rhs, .. }) => { + if *rhs != 0 { + if lhs % rhs == 0 { + Ok(Value::Int { + val: lhs / rhs, + span, + }) + } else { + Ok(Value::Float { + val: (*lhs as f64) / (*rhs as f64), + span, + }) + } + } else { + Err(ShellError::DivisionByZero(op)) + } + } (Value::CustomValue { val: lhs, span }, rhs) => { lhs.operation(*span, Operator::Divide, op, rhs) } diff --git a/src/tests/test_engine.rs b/src/tests/test_engine.rs index b8cac9a972..88eaa3eb69 100644 --- a/src/tests/test_engine.rs +++ b/src/tests/test_engine.rs @@ -148,3 +148,13 @@ fn proper_variable_captures_with_nesting() -> TestResult { fn proper_variable_for() -> TestResult { run_test(r#"for x in 1..3 { if $x == 2 { "bob" } } | get 1"#, "bob") } + +#[test] +fn divide_duration() -> TestResult { + run_test(r#"4ms / 4ms"#, "1") +} + +#[test] +fn divide_filesize() -> TestResult { + run_test(r#"4mb / 4mb"#, "1") +}