Skip to content

Commit f3b24a7

Browse files
committed
Make the heapless to alloc Vec conversion fallible as well.
This allows to catch OOM errors.
1 parent d87e4f3 commit f3b24a7

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

CHANGELOG.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
4242
- Make `String::from_utf8_unchecked` const.
4343
- Implemented `PartialEq` and `Eq` for `Deque`.
4444
- Added `alloc` feature to enable `alloc`-Vec interoperability.
45-
- Added `From<alloc::vec::Vec>` impl for `Vec`.
46-
- Added `From<Vec>` impl for `alloc::vec::Vec`.
45+
- Added `TryFrom<alloc::vec::Vec>` impl for `Vec`.
46+
- Added `TryFrom<Vec>` impl for `alloc::vec::Vec`.
4747

4848
### Changed
4949

src/vec/mod.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,6 +1232,7 @@ impl<T, const N: usize> TryFrom<alloc::vec::Vec<T>> for Vec<T, N> {
12321232
let mut vec = Vec::new();
12331233

12341234
for e in alloc_vec {
1235+
// Push each element individually to allow handling capacity errors.
12351236
vec.push(e).map_err(|_| ())?;
12361237
}
12371238

@@ -1241,10 +1242,26 @@ impl<T, const N: usize> TryFrom<alloc::vec::Vec<T>> for Vec<T, N> {
12411242

12421243
#[cfg(feature = "alloc")]
12431244
/// Converts the given `Vec<T, N>` into an `alloc::vec::Vec<T>`.
1244-
impl<T, const N: usize> From<Vec<T, N>> for alloc::vec::Vec<T> {
1245+
impl<T, const N: usize> TryFrom<Vec<T, N>> for alloc::vec::Vec<T> {
1246+
type Error = ();
1247+
12451248
/// Converts the given `Vec<T, N>` into an `alloc::vec::Vec<T>`.
1246-
fn from(vec: Vec<T, N>) -> Self {
1247-
alloc::vec::Vec::from_iter(vec.into_iter())
1249+
///
1250+
/// # Errors
1251+
///
1252+
/// Returns `Err` if the `alloc::vec::Vec` fails to allocate memory.
1253+
fn try_from(vec: Vec<T, N>) -> Result<Self, Self::Error> {
1254+
let mut alloc_vec = alloc::vec::Vec::new();
1255+
1256+
// Allocate enough space for the elements, return an error if the
1257+
// allocation fails.
1258+
alloc_vec.try_reserve(vec.len()).map_err(|_| ())?;
1259+
1260+
// Transfer the elements, since we reserved enough space above, this
1261+
// should not fail due to OOM.
1262+
alloc_vec.extend(vec);
1263+
1264+
Ok(alloc_vec)
12481265
}
12491266
}
12501267

0 commit comments

Comments
 (0)