Skip to content

Commit 2b3fcf1

Browse files
committed
refactor: create a utility trait to sort arrays
1 parent 2ea1c88 commit 2b3fcf1

1 file changed

Lines changed: 37 additions & 2 deletions

File tree

tests/_utils.rs

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use pretty_assertions::assert_eq;
1414
use rand::{distr::Alphanumeric, rng, Rng};
1515
use rayon::prelude::*;
1616
use std::{
17+
cmp::Ordering,
1718
env::temp_dir,
1819
fs::{create_dir, metadata, remove_dir_all},
1920
io::Error,
@@ -110,10 +111,10 @@ where
110111
let DataTreeReflection {
111112
name,
112113
size,
113-
mut children,
114+
children,
114115
} = tree_reflection;
115-
children.sort_by(|left, right| left.name.cmp(&right.name));
116116
let children = children
117+
.into_sorted_by(|left, right| left.name.cmp(&right.name))
117118
.into_par_iter()
118119
.map(sanitize_tree_reflection)
119120
.collect();
@@ -330,3 +331,37 @@ pub fn inspect_stderr(stderr: &[u8]) {
330331
eprintln!("STDERR:\n{text}\n");
331332
}
332333
}
334+
335+
/// Utility methods to sort various types of arrays.
336+
pub trait IntoSorted<Item>: Sized {
337+
/// Sort an array by [`Ord`] and return it.
338+
fn into_sorted(self) -> Self
339+
where
340+
Item: Ord;
341+
342+
/// Sort an array by a function and return it.
343+
fn into_sorted_by<Order>(self, order: Order) -> Self
344+
where
345+
Order: FnMut(&Item, &Item) -> Ordering;
346+
}
347+
348+
impl<Item, Array> IntoSorted<Item> for Array
349+
where
350+
Array: AsMut<[Item]> + Sized,
351+
{
352+
fn into_sorted(mut self) -> Self
353+
where
354+
Item: Ord,
355+
{
356+
self.as_mut().sort();
357+
self
358+
}
359+
360+
fn into_sorted_by<Order>(mut self, order: Order) -> Self
361+
where
362+
Order: FnMut(&Item, &Item) -> Ordering,
363+
{
364+
self.as_mut().sort_by(order);
365+
self
366+
}
367+
}

0 commit comments

Comments
 (0)