Skip to content

Commit 73038de

Browse files
authored
Allow constructing BoundedVec from slice (#944)
1 parent 57ec9fb commit 73038de

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

bounded-collections/src/bounded_vec.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,14 @@ impl<'a, T, S: Get<u32>> BoundedSlice<'a, T, S> {
265265
pub fn truncate_from(s: &'a [T]) -> Self {
266266
Self(&s[0..(s.len().min(S::get() as usize))], PhantomData)
267267
}
268+
269+
/// Copies `self` into a new `BoundedVec`.
270+
pub fn to_bounded_vec(self) -> BoundedVec<T, S>
271+
where
272+
T: Clone,
273+
{
274+
BoundedVec(self.0.to_vec(), PhantomData)
275+
}
268276
}
269277

270278
impl<T, S> BoundedVec<T, S> {
@@ -685,6 +693,19 @@ impl<T, S: Get<u32>> TryFrom<Vec<T>> for BoundedVec<T, S> {
685693
}
686694
}
687695

696+
impl<'a, T: Clone, S: Get<u32>> TryFrom<&'a [T]> for BoundedVec<T, S> {
697+
type Error = ();
698+
699+
fn try_from(t: &'a [T]) -> Result<Self, Self::Error> {
700+
if t.len() <= Self::bound() {
701+
// explicit check just above
702+
Ok(Self::unchecked_from(t.to_vec()))
703+
} else {
704+
Err(())
705+
}
706+
}
707+
}
708+
688709
impl<T, S: Get<u32>> TruncateFrom<Vec<T>> for BoundedVec<T, S> {
689710
fn truncate_from(unbound: Vec<T>) -> Self {
690711
BoundedVec::<T, S>::truncate_from(unbound)

0 commit comments

Comments
 (0)