From 03ab76e9c7a1e19d8373760c196aee12bc926a71 Mon Sep 17 00:00:00 2001 From: Xiliang Chen <xlchen1291@gmail.com> Date: Mon, 11 Apr 2022 20:35:25 +1200 Subject: [PATCH] add sort & try_append to bounded_vec (#11196) --- .../frame/support/src/storage/bounded_vec.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/substrate/frame/support/src/storage/bounded_vec.rs b/substrate/frame/support/src/storage/bounded_vec.rs index 137015098cf..92ca167f984 100644 --- a/substrate/frame/support/src/storage/bounded_vec.rs +++ b/substrate/frame/support/src/storage/bounded_vec.rs @@ -129,6 +129,16 @@ impl<T, S> BoundedVec<T, S> { self.0.sort_by(compare) } + /// Exactly the same semantics as [`slice::sort`]. + /// + /// This is safe since sorting cannot change the number of elements in the vector. + pub fn sort(&mut self) + where + T: sp_std::cmp::Ord, + { + self.0.sort() + } + /// Exactly the same semantics as `Vec::remove`. /// /// # Panics @@ -374,6 +384,17 @@ impl<T, S: Get<u32>> BoundedVec<T, S> { } } + /// Exactly the same semantics as [`Vec::append`], but returns an error and does nothing if the + /// length of the outcome is larger than the bound. + pub fn try_append(&mut self, other: &mut Vec<T>) -> Result<(), ()> { + if other.len().saturating_add(self.len()) <= Self::bound() { + self.0.append(other); + Ok(()) + } else { + Err(()) + } + } + /// Consumes self and mutates self via the given `mutate` function. /// /// If the outcome of mutation is within bounds, `Some(Self)` is returned. Else, `None` is -- GitLab