Created
January 31, 2021 23:25
-
-
Save bstrie/97cd1b12978382a07031a327f0e36c87 to your computer and use it in GitHub Desktop.
This file contains 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
#![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