Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions primitives/runtime/src/bounded/bounded_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,17 @@ impl<T, S> BoundedVec<T, S> {
self.0.sort_by(compare)
}

/// Exactly the same semantics as [`slice::sort_by_key`].
///
/// This is safe since sorting cannot change the number of elements in the vector.
pub fn sort_by_key<K, F>(&mut self, f: F)
where
F: FnMut(&T) -> K,
K: sp_std::cmp::Ord,
{
self.0.sort_by_key(f)
}

/// Exactly the same semantics as [`slice::sort`].
///
/// This is safe since sorting cannot change the number of elements in the vector.
Expand Down Expand Up @@ -1189,4 +1200,12 @@ pub mod test {
b1.iter().map(|x| x + 1).rev().take(2).try_collect();
assert!(b2.is_err());
}

#[test]
fn bounded_vec_sort_by_key_works() {
let mut v: BoundedVec<i32, ConstU32<5>> = bounded_vec![-5, 4, 1, -3, 2];
// Sort by absolute value.
v.sort_by_key(|k| k.abs());
assert_eq!(v, vec![1, 2, -3, 4, -5]);
}
}