Skip to content

Commit 90daba1

Browse files
committed
Add new Vec::into_array method
1 parent 3b49836 commit 90daba1

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/vec.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,32 @@ impl<T, const N: usize> Vec<T, N> {
107107
unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const T, self.len) }
108108
}
109109

110+
/// Returns the contents of the vector as an array of length `M` if the length
111+
/// of the vector is exactly `M`, otherwise returns `Err(self)`.
112+
///
113+
/// # Examples
114+
///
115+
/// ```
116+
/// use heapless::Vec;
117+
/// let buffer: Vec<u8, 42> = Vec::from_slice(&[1, 2, 3, 5, 8]).unwrap();
118+
/// let array: [u8; 5] = buffer.into_array().unwrap();
119+
/// assert_eq!(array, [1, 2, 3, 5, 8]);
120+
/// ```
121+
pub fn into_array<const M: usize>(self) -> Result<[T; M], Self> {
122+
if self.len() == M {
123+
// This is how the unstable `MaybeUninit::array_assume_init` method does it
124+
let array = unsafe { (&self.buffer as *const _ as *const [T; M]).read() };
125+
126+
// We don't want `self`'s destructor to be called because that would drop all the
127+
// items in the array
128+
core::mem::forget(self);
129+
130+
Ok(array)
131+
} else {
132+
Err(self)
133+
}
134+
}
135+
110136
/// Extracts a mutable slice containing the entire vector.
111137
///
112138
/// Equivalent to `&s[..]`.

0 commit comments

Comments
 (0)