From f07d18723fb7a81713f71f8fa5f01879e03e8244 Mon Sep 17 00:00:00 2001 From: jinlow Date: Thu, 7 Sep 2023 11:26:16 -0500 Subject: [PATCH] Fix formatting function, so that we never have integer overflow --- src/splitter.rs | 2 +- src/tree.rs | 5 +---- src/utils.rs | 25 +++++++++++++++++-------- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/splitter.rs b/src/splitter.rs index d68a532..e093385 100644 --- a/src/splitter.rs +++ b/src/splitter.rs @@ -512,7 +512,7 @@ impl Splitter for MissingBranchSplitter { let n_right = total_recs - split_idx; let n_left = total_recs - n_right - missing_split_idx; let n_missing = total_recs - (n_right + n_left); - let max_ = match vec![n_missing, n_left, n_right] + let max_ = match [n_missing, n_left, n_right] .iter() .enumerate() .max_by(|(_, i), (_, j)| i.cmp(j)) diff --git a/src/tree.rs b/src/tree.rs index e098f01..0f1e6b0 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -531,10 +531,7 @@ impl Display for Tree { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut print_buffer: Vec = vec![0]; let mut r = String::new(); - while !print_buffer.is_empty() { - // This will always be populated, because we confirm - // that the buffer is not empty. - let idx = print_buffer.pop().unwrap(); + while let Some(idx) = print_buffer.pop() { let node = &self.nodes[idx]; if node.is_leaf { r += format!("{}{}\n", " ".repeat(node.depth).as_str(), node).as_str(); diff --git a/src/utils.rs b/src/utils.rs index 7191f6d..56262b9 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -17,15 +17,16 @@ pub fn items_to_strings(items: Vec<&str>) -> String { pub fn fmt_vec_output>(v: &[T]) -> String { let mut res = String::new(); - let last = v.len() - 1; - if last == 0 { - return format!("{:.4}", v[0]); - } - for n in &v[..last] { - res.push_str(format!("{:.4}", n).as_str()); - res.push_str(", "); + if let Some(last) = v.len().checked_sub(1) { + if last == 0 { + return format!("{:.4}", v[0]); + } + for n in &v[..last] { + res.push_str(format!("{:.4}", n).as_str()); + res.push_str(", "); + } + res.push_str(format!("{:.4}", &v[last]).as_str()); } - res.push_str(format!("{:.4}", &v[last]).as_str()); res } @@ -932,4 +933,12 @@ mod tests { // println!("Multiplication Results {}", vec[0] * (records as f32)); // println!("f64_sum Results {}", f64_sum(&vec)); } + + #[test] + fn test_fmt_vec_output() { + let v = Vec::::new(); + assert_eq!(fmt_vec_output(&v), String::from("")); + let v: Vec = vec![0.1, 1.0]; + assert_eq!(fmt_vec_output(&v), String::from("0.1000, 1.0000")); + } }