Created
December 25, 2022 00:40
-
-
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]
This file contains hidden or 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
| 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