Created
August 6, 2020 09:55
-
-
Save YoshiTheChinchilla/f26e1a280312e599641acbbaeb72d08d to your computer and use it in GitHub Desktop.
Simple and efficient Vec<[T; N]> into Vec<T> implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(incomplete_features)] | |
#![feature(const_generics)] | |
#[derive(Debug)] | |
pub enum TryFromVecArrayError { | |
OverflowedLen, | |
OverflowedCap, | |
} | |
pub trait TryFromVecArray<T, const N: usize> { | |
type Error; | |
type Into; | |
fn try_from_vec_array(v: Vec<[T; N]>) -> Result<Self::Into, Self::Error>; | |
} | |
impl<T, const N: usize> TryFromVecArray<T, N> for Vec<T> { | |
type Error = TryFromVecArrayError; | |
type Into = Self; | |
fn try_from_vec_array(v: Vec<[T; N]>) -> Result<Self::Into, Self::Error> { | |
let mut v = std::mem::ManuallyDrop::new(v); | |
let p = v.as_mut_ptr() as *mut T; | |
let len = v.len().checked_mul(N).ok_or(TryFromVecArrayError::OverflowedLen)?; | |
let cap = v.capacity().checked_mul(N).ok_or(TryFromVecArrayError::OverflowedCap)?; | |
unsafe { | |
Ok(Vec::from_raw_parts(p, len, cap)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment