Skip to content

Instantly share code, notes, and snippets.

@Pagwin2
Created December 25, 2022 00:40
Show Gist options
  • Select an option

  • Save Pagwin2/ac65fde8ba533080af876dc4d0ec5206 to your computer and use it in GitHub Desktop.

Select an option

Save Pagwin2/ac65fde8ba533080af876dc4d0ec5206 to your computer and use it in GitHub Desktop.
making a somewhat useful rust trait which allows for attempting to collect into a container and implementing it for [const len:usize; T]
trait UnreliableFromIter<T>:Sized{
type Error;
fn try_from_iter<I:IntoIterator<Item = T>>(iter:I)->Result<Self,Self::Error> where Self:Sized;
}
enum ArrayFromIterErr<const len:usize, T,I:Iterator<Item = T>>{InsufficientItemCount,
TooManyItems{
gathered:[T;len],
extra: T,
rem: I
}
}
impl <const len:usize, T:Sized> UnreliableFromIter<T> for [T;len] {
type Error = ArrayFromIterErr<len,T>;
fn try_from_iter<I:IntoIterator<Item = T>>(iter:I)->Result<Self,Self::Error>{
let mut container:[T;len] = unsafe{
core::mem::zeroed()
};
let mut iter = iter.into_iter();
for item in 0..len {
container[0] = iter.next().ok_or(ArrayFromIterErr::InsufficientItemCount)?;
}
if let Some(item) = iter.next(){
Err(ArrayFromIterErr<len,T,I::IntoIter>::TooManyItems{
gathered:container,
extra: item,
rem: iter
})
}
else {
Ok(container)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment