Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Jul 29, 2023
1 parent 2891279 commit db6c437
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

/// Like `a % b` but returns `b` instead of `0`.
#[must_use]
pub(crate) const fn rem_up(a: usize, b: usize) -> usize {
Expand All @@ -9,19 +12,23 @@ pub(crate) const fn rem_up(a: usize, b: usize) -> usize {
}
}

fn last_idx<T: PartialEq>(x: &[T], value: &T) -> Option<usize> {
x.iter().rposition(|b| b != value)
#[allow(dead_code)]
#[inline]
fn last_idx<T: PartialEq>(x: &[T], value: &T) -> usize {
x.iter().rposition(|b| b != value).map_or(0, |idx| idx + 1)
}

#[allow(dead_code)]
#[must_use]
#[inline]
pub(crate) fn trim_end_slice<'a, T: PartialEq>(slice: &'a [T], value: &T) -> &'a [T] {
&slice[..last_idx(slice, value).unwrap_or(0)]
&slice[..last_idx(slice, value)]
}

#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn trim_end_vec<T: PartialEq>(vec: &mut Vec<T>, value: &T) {
vec.truncate(last_idx(vec, value).map_or(0, |idx| idx + 1));
vec.truncate(last_idx(vec, value));
}

// Branch prediction hints.
Expand Down Expand Up @@ -52,3 +59,31 @@ pub(crate) const fn unlikely(b: bool) -> bool {
}
b
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_trim() {
assert_eq!(trim_end_slice(&[], &0), &[] as &[i32]);
assert_eq!(trim_end_slice(&[0], &0), &[] as &[i32]);
assert_eq!(trim_end_slice(&[0, 1], &0), &[0, 1]);
assert_eq!(trim_end_slice(&[0, 1, 0], &0), &[0, 1]);
assert_eq!(trim_end_slice(&[0, 1, 0, 0], &0), &[0, 1]);
assert_eq!(trim_end_slice(&[0, 1, 0, 0, 0], &0), &[0, 1]);
assert_eq!(trim_end_slice(&[0, 1, 0, 1, 0], &0), &[0, 1, 0, 1]);

let trim_end_vec = |mut v: Vec<i32>, x: &i32| {
trim_end_vec(&mut v, x);
v
};
assert_eq!(trim_end_vec(vec![], &0), &[] as &[i32]);
assert_eq!(trim_end_vec(vec![0], &0), &[] as &[i32]);
assert_eq!(trim_end_vec(vec![0, 1], &0), &[0, 1]);
assert_eq!(trim_end_vec(vec![0, 1, 0], &0), &[0, 1]);
assert_eq!(trim_end_vec(vec![0, 1, 0, 0], &0), &[0, 1]);
assert_eq!(trim_end_vec(vec![0, 1, 0, 0, 0], &0), &[0, 1]);
assert_eq!(trim_end_vec(vec![0, 1, 0, 1, 0], &0), &[0, 1, 0, 1]);
}
}

0 comments on commit db6c437

Please sign in to comment.