From a9756bd652a78f6e05e156a9e9c2849ff6ae6a88 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 23 Nov 2021 12:54:55 +0100 Subject: [PATCH] Implement TryFrom<&[T]> for Vec There already is the Vec::from_slice method that does the same, but implementing the TryFrom trait makes it easier to write code that works both with heapless::Vec and std::vec::Vec. --- src/vec.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/vec.rs b/src/vec.rs index 8c9944f0..51b4d50c 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -1,4 +1,7 @@ -use core::{cmp::Ordering, fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr, slice}; +use core::{ + cmp::Ordering, convert::TryFrom, fmt, hash, iter::FromIterator, mem::MaybeUninit, ops, ptr, + slice, +}; use hash32; /// A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) @@ -569,6 +572,14 @@ impl Drop for Vec { } } +impl<'a, T: Clone, const N: usize> TryFrom<&'a [T]> for Vec { + type Error = (); + + fn try_from(slice: &'a [T]) -> Result { + Vec::from_slice(slice) + } +} + impl Extend for Vec { fn extend(&mut self, iter: I) where