Skip to content

Commit

Permalink
Fix formatting function, so that we never have integer overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
jinlow committed Sep 7, 2023
1 parent 5c0d30e commit f07d187
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/splitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
5 changes: 1 addition & 4 deletions src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,10 +531,7 @@ impl Display for Tree {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut print_buffer: Vec<usize> = 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();
Expand Down
25 changes: 17 additions & 8 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ pub fn items_to_strings(items: Vec<&str>) -> String {

pub fn fmt_vec_output<T: FloatData<T>>(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
}

Expand Down Expand Up @@ -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::<f32>::new();
assert_eq!(fmt_vec_output(&v), String::from(""));
let v: Vec<f32> = vec![0.1, 1.0];
assert_eq!(fmt_vec_output(&v), String::from("0.1000, 1.0000"));
}
}

0 comments on commit f07d187

Please sign in to comment.