@@ -1232,6 +1232,7 @@ impl<T, const N: usize> TryFrom<alloc::vec::Vec<T>> for Vec<T, N> {
1232
1232
let mut vec = Vec :: new ( ) ;
1233
1233
1234
1234
for e in alloc_vec {
1235
+ // Push each element individually to allow handling capacity errors.
1235
1236
vec. push ( e) . map_err ( |_| ( ) ) ?;
1236
1237
}
1237
1238
@@ -1241,10 +1242,26 @@ impl<T, const N: usize> TryFrom<alloc::vec::Vec<T>> for Vec<T, N> {
1241
1242
1242
1243
#[ cfg( feature = "alloc" ) ]
1243
1244
/// 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
+
1245
1248
/// 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)
1248
1265
}
1249
1266
}
1250
1267
0 commit comments