From ec31844ee7d57b2a3a437619de8e21e6d61080c2 Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Tue, 7 Apr 2026 01:58:12 +0100 Subject: [PATCH] helper: new ExactSizedArr adaptor for ExactSizedIterators Given an ExactSizedIterator and a compile time known size (N), we should be able to generate stack allocated arrays of the contents of an iterator as long as the iterator has at least the required size. --- src/helper.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/helper.rs b/src/helper.rs index 2c91f75..44cc143 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -1,4 +1,30 @@ +/** Given an array of arguments, return them sorted. +Best utilised with array destructuring. */ pub fn ordered(mut xs: [T; N]) -> [T; N] { xs.sort(); xs } + +/** An iterator adaptor (derived from ExactSizedIterator) which has a guaranteed +compile time size, allowing for collection of an iterator into a stack allocated +array. */ +pub trait ExactSizedArr: ExactSizeIterator + Sized +where + I: Default, +{ + fn into_array(mut self) -> Result<[Self::Item; N], Self> { + if self.len() < N { + Err(self) + } else { + Ok(std::array::from_fn(|_| self.next().unwrap())) + } + } +} + +/** Default implementation of ExactSizedArr for any ExactSizeIterator. */ +impl ExactSizedArr for I +where + T: Default + Copy + Clone, + I: ExactSizeIterator, +{ +}