From 85e2092d8f73db09064bc97a55078fdf1ecb0fe4 Mon Sep 17 00:00:00 2001
From: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Date: Wed, 10 Aug 2022 10:39:24 +0200
Subject: [PATCH] Add BoundedVec::sort_by_key (#11998)

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
---
 .../runtime/src/bounded/bounded_vec.rs        | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/substrate/primitives/runtime/src/bounded/bounded_vec.rs b/substrate/primitives/runtime/src/bounded/bounded_vec.rs
index d5f3f2da0d6..aed1a156ad6 100644
--- a/substrate/primitives/runtime/src/bounded/bounded_vec.rs
+++ b/substrate/primitives/runtime/src/bounded/bounded_vec.rs
@@ -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.
@@ -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]);
+	}
 }
-- 
GitLab