split_from: use REAL generics

This commit is contained in:
2025-01-28 12:49:14 -05:00
parent 8099326d63
commit a2fe0daf28
3 changed files with 93 additions and 12 deletions

View File

@@ -2,11 +2,7 @@ use std::{iter::Rev, ops::RangeInclusive};
pub fn split_from<T>(min: T, max: T, x: T) -> Vec<Vec<T>>
where
T: std::cmp::PartialOrd
+ std::ops::Add<usize, Output = T>
+ std::ops::Sub<usize, Output = T>
+ Copy
+ Ord,
T: num::Integer + Copy,
RangeInclusive<T>: Iterator<Item = T> + DoubleEndedIterator,
Rev<RangeInclusive<T>>: Iterator<Item = T>,
{
@@ -14,15 +10,14 @@ where
return Vec::new();
}
let x_upper = (x + 1).min(max);
let mut output: Vec<Vec<T>> = Vec::new();
if x > min + 1 {
let x_lower = x - 1;
let mut output: Vec<Vec<T>> = Vec::with_capacity(2);
if x > min + T::one() {
let x_lower = x - T::one();
output.push((min..=x_lower).rev().collect());
}
if x_upper < max {
output.push((x_upper..=max).collect());
if x + T::one() < max {
output.push(((x + T::one())..=max).collect());
}
output
}
@@ -38,5 +33,8 @@ mod test {
assert_eq!(split_from(0, 6, 0), vec![vec![1, 2, 3, 4, 5, 6]]);
assert_eq!(split_from(0, 6, 6), vec![vec![5, 4, 3, 2, 1, 0]]);
// test out-of-bounds and also generics
assert_eq!(split_from::<i16>(-1, 4, 10), Vec::<Vec<i16>>::new());
}
}