Skip to content

Commit

Permalink
Add Ord implementation for BoundedVec (paritytech#10615)
Browse files Browse the repository at this point in the history
* Add Ord implementation for BoundedVec

* Update frame/support/src/storage/bounded_vec.rs

* Update frame/support/src/storage/bounded_vec.rs

* Update frame/support/src/storage/bounded_vec.rs

* Update frame/support/src/storage/bounded_vec.rs

Co-authored-by: Bastian Köcher <[email protected]>
  • Loading branch information
kianenigma and bkchr authored Jan 9, 2022
1 parent 617c36e commit 42bac67
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions frame/support/src/storage/bounded_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,18 @@ impl<'a, T: Encode + Decode, S: Get<u32>> EncodeLike<WeakBoundedVec<T, S>>
}
impl<'a, T: Encode + Decode, S: Get<u32>> EncodeLike<Vec<T>> for BoundedSlice<'a, T, S> {}

impl<T: PartialOrd, Bound: Get<u32>> PartialOrd for BoundedVec<T, Bound> {
fn partial_cmp(&self, other: &Self) -> Option<sp_std::cmp::Ordering> {
self.0.partial_cmp(&other.0)
}
}

impl<T: Ord, Bound: Get<u32>> Ord for BoundedVec<T, Bound> {
fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering {
self.0.cmp(&other.0)
}
}

impl<'a, T, S: Get<u32>> TryFrom<&'a [T]> for BoundedSlice<'a, T, S> {
type Error = ();
fn try_from(t: &'a [T]) -> Result<Self, Self::Error> {
Expand Down Expand Up @@ -545,4 +557,15 @@ pub mod test {
let b2: BoundedVec<u32, B2> = vec![1, 2, 3].try_into().unwrap();
assert_eq!(b1, b2);
}

#[test]
fn ord_works() {
use std::cmp::Ordering;
let b1: BoundedVec<u32, ConstU32<7>> = vec![1, 2, 3].try_into().unwrap();
let b2: BoundedVec<u32, ConstU32<7>> = vec![1, 3, 2].try_into().unwrap();

// ordering for vec is lexicographic.
assert_eq!(b1.cmp(&b2), Ordering::Less);
assert_eq!(b1.cmp(&b2), b1.into_inner().cmp(&b2.into_inner()));
}
}

0 comments on commit 42bac67

Please sign in to comment.