From 6e340426e2354e5220bbbb4a4b7d2acdb295baf0 Mon Sep 17 00:00:00 2001 From: Romain Milon Date: Thu, 4 Aug 2022 17:28:25 +0200 Subject: [PATCH] Fix mean on empty arrays (#2612) * Fix mean on empty arrays * Update code style * Add empty slice tests --- common/src/calc.rs | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/common/src/calc.rs b/common/src/calc.rs index 13238a49ec3c..b4d6a0cb4055 100644 --- a/common/src/calc.rs +++ b/common/src/calc.rs @@ -9,6 +9,10 @@ pub fn mean(values: &[T]) -> U256 where T: Into + Copy, { + if values.is_empty() { + return U256::zero() + } + values.iter().copied().fold(U256::zero(), |sum, val| sum + val.into()) / values.len() } @@ -18,16 +22,16 @@ pub fn median_sorted(values: &[T]) -> T where T: Add + Div + From + Copy, { + if values.is_empty() { + return 0u64.into() + } + let len = values.len(); - if len > 0 { - let mid = len / 2; - if len % 2 == 0 { - (values[mid - 1] + values[mid]) / 2u64 - } else { - values[mid] - } + let mid = len / 2; + if len % 2 == 0 { + (values[mid - 1] + values[mid]) / 2u64 } else { - 0u64.into() + values[mid] } } @@ -35,6 +39,13 @@ where mod tests { use super::*; + #[test] + fn calc_mean_empty() { + let values: [u64; 0] = []; + let m = mean(&values); + assert_eq!(m, U256::zero()); + } + #[test] fn calc_mean() { let values = [0u64, 1u64, 2u64, 3u64, 4u64, 5u64, 6u64]; @@ -42,6 +53,13 @@ mod tests { assert_eq!(m, 3u64.into()); } + #[test] + fn calc_median_empty() { + let values: Vec = vec![]; + let m = median_sorted(&values); + assert_eq!(m, 0); + } + #[test] fn calc_median() { let mut values = vec![29, 30, 31, 40, 59, 61, 71];