Skip to content

Instantly share code, notes, and snippets.

@lcnr
Created March 14, 2020 21:42
Show Gist options
  • Save lcnr/5208cc249333c771ae2770dfa351f8f4 to your computer and use it in GitHub Desktop.
Save lcnr/5208cc249333c771ae2770dfa351f8f4 to your computer and use it in GitHub Desktop.
Array FromIterator proposal
/// This takes at most `N` elements from the iterator.
///
/// # Examples
///
/// ```
/// let mut iter = 0..;
/// let arr: [usize, 10] = iter.by_ref().collect().unwrap();
/// assert_eq!(iter.next(), 10);
/// ```
impl<T, const N: usize> FromIterator<T> for Result<[T; N], FillError<T, N>> {
/* ... */
}
/// An error returned by `FromIterator` for arrays if the iterator contained less than `N` elements.
pub struct FillError<T, const N: usize> {
arr: [MaybeUninit<T>; N]
len: usize,
}
impl<T, const N: usize> FillError<T, N> {
/// Returns the how many elements were read from the given iterator.
pub fn len(&self) -> usize {
self.len
}
/// Returns an immutable slice of all initialized elements.
pub fn as_slice(&self) -> &[T] {
MaybeUninit::slice_get_ref(&self.arr[0..self.len])
}
/// Returns a mutable slice of all initialized elements.
pub fn as_mut_slice(&mut self) -> &mut [T] {
MaybeUninit::slice_get_mut(&mut self.arr[0..self.len])
}
/// Tries to initialize the left-over elements using `iter`.
pub fn fill<I>(self, iter: I) -> Result<[T; N], FillError<T; N>> {
/* ... */
}
}
@lcnr
Copy link
Author

lcnr commented Mar 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment