Skip to content

Instantly share code, notes, and snippets.

@YoshiTheChinchilla
Created August 6, 2020 09:55
Show Gist options
  • Save YoshiTheChinchilla/f26e1a280312e599641acbbaeb72d08d to your computer and use it in GitHub Desktop.
Save YoshiTheChinchilla/f26e1a280312e599641acbbaeb72d08d to your computer and use it in GitHub Desktop.
Simple and efficient Vec<[T; N]> into Vec<T> implementation
#![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