diff --git a/substrate/frame/support/src/storage/bounded_vec.rs b/substrate/frame/support/src/storage/bounded_vec.rs index 9fcfe40352..5b253f7633 100644 --- a/substrate/frame/support/src/storage/bounded_vec.rs +++ b/substrate/frame/support/src/storage/bounded_vec.rs @@ -21,6 +21,7 @@ use sp_std::prelude::*; use sp_std::{convert::TryFrom, marker::PhantomData}; use codec::{FullCodec, Encode, EncodeLike, Decode}; +use core::{ops::{Index, IndexMut}, slice::SliceIndex}; use crate::{ traits::Get, storage::{generator, StorageDecodeLength, StorageValue, StorageMap, StorageDoubleMap}, @@ -179,6 +180,18 @@ impl> AsRef> for BoundedVec { } } +impl> AsRef<[T]> for BoundedVec { + fn as_ref(&self) -> &[T] { + &self.0 + } +} + +impl> AsMut<[T]> for BoundedVec { + fn as_mut(&mut self) -> &mut [T] { + &mut self.0 + } +} + // will allow for immutable all operations of `Vec` on `BoundedVec`. impl> sp_std::ops::Deref for BoundedVec { type Target = Vec; @@ -189,10 +202,19 @@ impl> sp_std::ops::Deref for BoundedVec { } // Allows for indexing similar to a normal `Vec`. Can panic if out of bound. -impl> sp_std::ops::Index for BoundedVec { - type Output = T; - fn index(&self, index: usize) -> &Self::Output { - self.get(index).expect("index out of bound") +impl, I: SliceIndex<[T]>> Index for BoundedVec { + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + self.0.index(index) + } +} + +impl, I: SliceIndex<[T]>> IndexMut for BoundedVec { + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + self.0.index_mut(index) } } @@ -212,6 +234,12 @@ impl> codec::DecodeLength for BoundedVec { } } +impl> PartialEq> for BoundedVec { + fn eq(&self, other: &Vec) -> bool { + &self.0 == other + } +} + impl> StorageDecodeLength for BoundedVec {} /// Storage value that is *maybe* capable of [`StorageAppend`](crate::storage::StorageAppend). @@ -467,4 +495,16 @@ pub mod test { assert_eq!(bounded.len(), 7); assert!(bounded.try_mutate(|v| v.push(8)).is_none()); } + + #[test] + fn slice_indexing_works() { + let bounded: BoundedVec = vec![1, 2, 3, 4, 5, 6].try_into().unwrap(); + assert_eq!(&bounded[0..=2], &[1, 2, 3]); + } + + #[test] + fn vec_eq_works() { + let bounded: BoundedVec = vec![1, 2, 3, 4, 5, 6].try_into().unwrap(); + assert_eq!(bounded, vec![1, 2, 3, 4, 5, 6]); + } }