Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#![feature(maybe_uninit_uninit_array)]
#![feature(maybe_uninit_array_assume_init)]
use std::{
iter::FromIterator,
mem::MaybeUninit
};
fn main() {
let bar = vec![1,2,3];
let qux: Foo<i32, 3> = bar.into_iter().collect();
dbg!(qux);
}
// coherence-mollifying newtype,
// stdlib could implement directly on Option<[T; N]>
// (unless something unexpected overlaps?)
#[derive(Debug)]
struct Foo<T, const N: usize>(Option<[T; N]>);
impl<T, const N: usize> FromIterator<T> for Foo<T, N> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
let mut iter = iter.into_iter();
let mut array: [MaybeUninit<T>; N] = MaybeUninit::uninit_array();
for i in 0..N {
if let Some(e) = iter.next() {
array[i] = MaybeUninit::new(e);
} else {
return Foo(None);
}
}
let array = unsafe {
MaybeUninit::array_assume_init(array)
};
Foo(Some(array))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment