atools/
lib.rs

1//! a collection of useful features for working with arrays
2#![cfg_attr(not(test), no_std)]
3#![allow(incomplete_features, internal_features)]
4#![feature(
5    const_destruct,
6    adt_const_params,
7    generic_const_exprs,
8    core_intrinsics,
9    iter_intersperse,
10    const_trait_impl,
11    maybe_uninit_array_assume_init,
12    array_windows,
13    iter_map_windows
14)]
15#![warn(
16    clippy::undocumented_unsafe_blocks,
17    clippy::missing_const_for_fn,
18    clippy::missing_safety_doc,
19    clippy::suboptimal_flops,
20    unsafe_op_in_unsafe_fn,
21    clippy::dbg_macro,
22    clippy::use_self,
23    missing_docs
24)]
25use core::{
26    array::from_fn,
27    intrinsics::transmute_unchecked,
28    marker::Destruct,
29    mem::{MaybeUninit as MU, offset_of},
30};
31pub mod pervasive;
32mod slice;
33mod tuple;
34#[doc(inline)]
35pub use slice::Slice;
36pub use tuple::*;
37
38/// The prelude. You should
39/// ```
40/// use atools::prelude::*;
41/// ```
42pub mod prelude {
43    #[doc(inline)]
44    pub use super::{
45        Array, ArrayTools, Chunked, CollectArray, Couple, Deconstruct, Flatten, Join, Split, Tuple,
46        Zip, pervasive::prelude::*, range, slice::Slice, slice::r, splat,
47    };
48    #[doc(inline)]
49    pub use core::array::from_fn;
50}
51
52#[repr(C)]
53struct Pair<X, Y>(X, Y);
54impl<X, Y> Pair<X, Y> {
55    const fn tuple() -> bool {
56        (size_of::<(X, Y)>() == size_of::<Self>())
57            & (offset_of!(Self, 0) == offset_of!((X, Y), 0))
58            & (offset_of!(Self, 1) == offset_of!((X, Y), 1))
59    }
60
61    const fn into(self) -> (X, Y) {
62        if Self::tuple() {
63            // SAFETY: we are a tuple!!!
64            unsafe { transmute_unchecked::<Self, (X, Y)>(self) }
65        } else {
66            // SAFETY: this is safe.
67            let out = unsafe { (core::ptr::read(&self.0), core::ptr::read(&self.1)) };
68            core::mem::forget(self);
69            out
70        }
71    }
72
73    const unsafe fn splat<T>(x: T) -> (X, Y) {
74        assert!(core::mem::size_of::<T>() == core::mem::size_of::<Pair<X, Y>>());
75        // SAFETY: well.
76        unsafe { transmute_unchecked::<_, Self>(x) }.into()
77    }
78}
79
80/// Convenience function for when clonage is required; prefer `[T; N]` if possible. Also useful if `N` should be inferred.
81pub fn splat<T: Clone, const N: usize>(a: T) -> [T; N] {
82    from_fn(|_| a.clone())
83}
84
85/// Creates a array of indices.
86/// ```
87/// # #![feature(generic_const_exprs)]
88/// # use atools::prelude::*;
89/// assert_eq!(range::<5>(), [0, 1, 2, 3, 4]);
90/// ```
91pub const fn range<const N: usize>() -> [usize; N] {
92    let mut out = unsafe { MU::<[MU<usize>; N]>::uninit().assume_init() };
93    let mut i = 0usize;
94    while i < out.len() {
95        out[i] = MU::new(i);
96        i += 1;
97    }
98    unsafe { transmute_unchecked(out) }
99}
100
101/// Collect an iterator into a array.
102pub trait CollectArray<T> {
103    /// Collect an iterator into a array.
104    ///
105    /// # Panics
106    ///
107    /// if the array isn't big enough.
108    fn carr<const N: usize>(&mut self) -> [T; N];
109}
110
111impl<T, I: Iterator<Item = T>> CollectArray<T> for I {
112    fn carr<const N: usize>(&mut self) -> [T; N] {
113        from_fn(|_| self.next().unwrap())
114    }
115}
116
117/// Deconstruct some array.
118/// Use
119/// ```
120/// let [t, arr @ ..] = [1, 2];
121/// ```
122/// when possible. If the length of the array is a const generic, use
123/// ```
124/// # #![feature(generic_const_exprs)]
125/// # use atools::prelude::*;
126/// let (t, arr) = [1, 2].uncons();
127/// ```
128/// <img src="https://media.discordapp.net/attachments/1190100233233895585/1430294602144813167/listmonster.png?ex=68f94126&is=68f7efa6&hm=1e2f1d83a8348d1369eb33c5f4f62aa5787eb05eec3d782bf49d93f84b04d94a&=&width=710&height=355">
129pub const trait Deconstruct<T, const N: usize> {
130    /// Gives you the <code>[[head](Deconstruct_::head), [tail](Deconstruct_::tail) @ ..]</code>
131    /// ```
132    /// # #![feature(generic_const_exprs)]
133    /// # use atools::prelude::*;
134    /// let (t, arr) = b"abc".uncons();
135    /// # assert_eq!(t, b'a');
136    /// # assert_eq!(arr, *b"bc");
137    /// ```
138    fn uncons(self) -> (T, [T; N - 1]);
139    /// Gives you the <code>[[init](Deconstruct_::init) @ .., [last](Deconstruct_::last)]</code>
140    /// ```
141    /// # #![feature(generic_const_exprs)]
142    /// # use atools::prelude::*;
143    /// let (arr, t) = [0.1f32, 0.2, 0.3].unsnoc();
144    /// # assert_eq!(arr, [0.1, 0.2]);
145    /// assert_eq!(t, 0.3);
146    /// ```
147    fn unsnoc(self) -> ([T; N - 1], T);
148    /// Gives you a <code>[init @ .., [_](Deconstruct_::last)]</code>
149    /// See also [`unsnoc`](Deconstruct::unsnoc).
150    /// ```
151    /// # #![feature(generic_const_exprs)]
152    /// # use atools::prelude::*;
153    /// let a = [1u64, 2, 3].init();
154    /// assert_eq!(a, [1, 2]);
155    /// ```
156    fn init(self) -> [T; N - 1];
157    /// Gives you a <code>[[_](Deconstruct_::head), tail @ ..]</code>.
158    /// See also [`uncons`](Deconstruct::uncons).
159    /// ```
160    /// # #![feature(generic_const_exprs)]
161    /// # use atools::prelude::*;
162    /// let x = atools::range::<5>();
163    /// assert!(x.tail() == atools::range::<4>().map(|x| x + 1));
164    /// ```
165    fn tail(self) -> [T; N - 1];
166    /// Gives you a <code>[[_](Deconstruct_::init) @ .., last]</code>.
167    /// See also [`unsnoc`](Deconstruct::unsnoc).
168    fn last(self) -> T
169    where
170        [(); N - 1]:;
171
172    /// Gives you a <code>[head, [_](Deconstruct_::tail) @ ..]</code>.
173    /// See also [`uncons`](Deconstruct::uncons).
174    fn head(self) -> T
175    where
176        [(); N - 1]:;
177}
178
179impl<T, const N: usize> const Deconstruct<T, N> for [T; N]
180where
181    T: [const] Destruct,
182{
183    #[doc(alias = "pop_front")]
184    fn uncons(self) -> (T, [T; N - 1]) {
185        // SAFETY: the layout is alright.
186        unsafe { Pair::splat(self) }
187    }
188
189    #[doc(alias = "pop")]
190    fn unsnoc(self) -> ([T; N - 1], T) {
191        // SAFETY: the layout is still alright.
192        unsafe { Pair::splat(self) }
193    }
194    fn tail(self) -> [T; N - 1]
195    where
196        T: [const] Destruct,
197    {
198        self.uncons().1
199    }
200    #[doc(alias = "trunc")]
201    fn init(self) -> [T; N - 1] {
202        self.unsnoc().0
203    }
204    fn last(self) -> T
205    where
206        [(); N - 1]:,
207    {
208        self.unsnoc().1
209    }
210
211    fn head(self) -> T
212    where
213        [(); N - 1]:,
214    {
215        self.uncons().0
216    }
217}
218
219/// Join scalars together.
220pub const trait Join<T, const N: usize, const O: usize, U> {
221    /// Join a array and an scalar together. For joining two arrays together, see [`Couple`].
222    /// ```
223    /// # #![feature(generic_const_exprs)]
224    /// # use atools::prelude::*;
225    /// let a = [1, 2].join(3);
226    /// let b = 1.join([2, 3]);
227    /// let c = 1.join(2).join(3);
228    /// ```
229    fn join(self, with: U) -> [T; N + O];
230}
231
232/// Couple two arrays together.
233pub const trait Couple<T, const N: usize, const O: usize> {
234    /// Couple two arrays together. This could have been [`Join`], but the methods would require disambiguation.
235    /// ```
236    /// # #![feature(generic_const_exprs)]
237    /// # use atools::prelude::*;
238    /// let a = 1.join(2).couple([3, 4]);
239    /// ```
240    fn couple(self, with: [T; O]) -> [T; N + O];
241}
242
243impl<T, const N: usize, const O: usize> const Couple<T, N, O> for [T; N] {
244    fn couple(self, with: [T; O]) -> [T; N + O] {
245        // SAFETY: adjacent
246        unsafe { transmute_unchecked(Pair(self, with)) }
247    }
248}
249
250impl<T, const N: usize> const Join<T, N, 1, T> for [T; N] {
251    fn join(self, with: T) -> [T; N + 1] {
252        self.couple([with])
253    }
254}
255
256impl<T> const Join<T, 1, 1, T> for T {
257    fn join(self, with: T) -> [T; 2] {
258        [self, with]
259    }
260}
261
262impl<T, const O: usize> const Join<T, 1, O, [T; O]> for T {
263    fn join(self, with: [T; O]) -> [T; 1 + O] {
264        [self].couple(with)
265    }
266}
267
268/// 🍪
269#[allow(private_bounds)]
270pub const trait Chunked<T, const N: usize> {
271    /// Chunks.
272    /// This will compile fail if `N ∤ (does not divide) C`
273    /// ```
274    /// # #![feature(generic_const_exprs)]
275    /// # use atools::prelude::*;
276    /// assert_eq!(range::<6>().chunked::<3>(), [[0, 1, 2], [3, 4, 5]]);
277    /// assert_eq!(range::<6>().chunked::<4>(), [[0, 1, 2], [3, 4, 5]]);
278    /// ```
279    #[allow(private_bounds)]
280    fn chunked<const C: usize>(self) -> [[T; C]; N / C]
281    where
282        // N % C == 0
283        [(); N % C + usize::MAX]:;
284}
285
286impl<const N: usize, T> const Chunked<T, N> for [T; N] {
287    #[allow(private_bounds)]
288    fn chunked<const C: usize>(self) -> [[T; C]; N / C]
289    where
290        [(); N % C + usize::MAX]:,
291    {
292        // SAFETY: N != 0 && wont leak as N % C == 0.
293        let retval = unsafe { self.as_ptr().cast::<[[T; C]; N / C]>().read() };
294        core::mem::forget(self);
295        retval
296    }
297}
298
299/// Flatten arrays.
300pub const trait Flatten<T, const N: usize, const N2: usize> {
301    /// Takes a `[[T; N]; N2]`, and flattens it to a `[T; N * N2]`.
302    ///
303    /// # Examples
304    ///
305    /// ```
306    /// # #![feature(generic_const_exprs)]
307    /// # use atools::prelude::*;
308    /// assert_eq!([[1, 2, 3], [4, 5, 6]].flatten(), [1, 2, 3, 4, 5, 6]);
309    ///
310    /// assert_eq!(
311    ///     [[1, 2, 3], [4, 5, 6]].flatten(),
312    ///     [[1, 2], [3, 4], [5, 6]].flatten(),
313    /// );
314    ///
315    /// let array_of_empty_arrays: [[i32; 0]; 5] = [[], [], [], [], []];
316    /// assert!(array_of_empty_arrays.flatten().is_empty());
317    ///
318    /// let empty_array_of_arrays: [[u32; 10]; 0] = [];
319    /// assert!(empty_array_of_arrays.flatten().is_empty());
320    /// ```
321    fn flatten(self) -> [T; N * N2];
322}
323
324impl<T, const N: usize, const M: usize> const Flatten<T, N, M> for [[T; M]; N] {
325    fn flatten(self) -> [T; N * M] {
326        // SAFETY: layout is the same.
327        unsafe { core::intrinsics::transmute_unchecked(self) }
328    }
329}
330
331/// Splitting arrays up.
332pub const trait Split<T, const N: usize> {
333    /// Splits the array into twain.
334    /// ```
335    /// # #![feature(generic_const_exprs)]
336    /// # use atools::prelude::*;
337    /// let x = [1u8, 2, 3];
338    /// let ([x], [y, z]) = x.split::<1>();
339    /// ```
340    fn split<const AT: usize>(self) -> ([T; AT], [T; N - AT]);
341    /// Take `AT` elements, discarding the rest.
342    /// ```
343    /// # #![feature(generic_const_exprs)]
344    /// # use atools::prelude::*;
345    /// assert_eq!(range::<50>().take::<5>(), range::<5>());
346    /// ```
347    fn take<const AT: usize>(self) -> [T; AT]
348    where
349        [(); N - AT]:,
350        T: [const] Destruct;
351    /// Discard `AT` elements, returning the rest.
352    fn drop<const AT: usize>(self) -> [T; N - AT]
353    where
354        T: [const] Destruct;
355}
356
357impl<T, const N: usize> const Split<T, N> for [T; N] {
358    fn split<const AT: usize>(self) -> ([T; AT], [T; N - AT]) {
359        // SAFETY: N - AT overflows when AT > N so the size of the returned "array" is the same.
360        unsafe { Pair::splat(self) }
361    }
362    fn take<const M: usize>(self) -> [T; M]
363    where
364        // M <= N
365        [(); N - M]:,
366        T: [const] Destruct,
367    {
368        self.split::<M>().0
369    }
370    fn drop<const M: usize>(self) -> [T; N - M]
371    where
372        T: [const] Destruct,
373    {
374        self.split::<M>().1
375    }
376}
377/// Zip arrays together.
378pub const trait Zip<T, const N: usize> {
379    /// Zip arrays together.
380    fn zip<U>(self, with: [U; N]) -> [(T, U); N];
381}
382
383impl<T, const N: usize> const Zip<T, N> for [T; N] {
384    fn zip<U>(self, with: [U; N]) -> [(T, U); N] {
385        let mut out = unsafe { MU::<[MU<_>; N]>::uninit().assume_init() };
386        let mut i = 0usize;
387        while i < out.len() {
388            out[i] = MU::new(unsafe { (self.as_ptr().add(i).read(), with.as_ptr().add(i).read()) });
389            i += 1;
390        }
391        core::mem::forget((self, with));
392        unsafe { transmute_unchecked(out) }
393    }
394}
395
396/// Array tools.
397pub trait ArrayTools<T, const N: usize> {
398    /// Skip `BY` elements.
399    fn skip<const BY: usize>(self) -> [T; N - BY];
400    /// Skip every `BY` elements.
401    ///
402    /// ```
403    /// # #![feature(generic_const_exprs)]
404    /// # use atools::prelude::*;
405    /// let x = range::<5>().step::<2>();
406    /// assert_eq!(x, [0, 2, 4]);
407    /// let x = range::<20>().step::<5>();
408    /// assert_eq!(x, [0, 5, 10, 15]);
409    /// assert_eq!(range::<50>().step::<3>(), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]);
410    /// ```
411    fn step<const STEP: usize>(self) -> [T; 1 + (N - 1) / (STEP)];
412    /// Intersperse a element in between items.
413    /// ```
414    /// # #![feature(generic_const_exprs)]
415    /// # use atools::prelude::*;
416    /// let x = range::<3>().intersperse(5);
417    /// assert_eq!(x, [0, 5, 1, 5, 2]);
418    /// ```
419    fn intersperse(self, with: T) -> [T; (N * 2) - 1]
420    where
421        T: Clone;
422    /// Run a function on every element.
423    fn each(self, apply: impl FnMut(T));
424    /// Embed the index.
425    fn enumerate(self) -> [(T, usize); N];
426    /// Get the sliding windows of this array.
427    /// ```
428    /// # #![feature(generic_const_exprs)]
429    /// # use atools::prelude::*;
430    /// assert_eq!(range::<5>().windowed::<2>(), [&[0, 1], &[1, 2], &[2, 3], &[3, 4]]);
431    /// ```
432    fn windowed<const W: usize>(&self) -> [&[T; W]; N - W + 1];
433    /// Inspect every element of this array.
434    fn inspect(self, f: impl FnMut(&T)) -> Self;
435    /// Reverse this array.
436    fn rev(self) -> Self;
437    /// Interleave items from two arrays.
438    /// ```
439    /// # #![feature(generic_const_exprs)]
440    /// # use atools::prelude::*;
441    /// assert_eq!([0u8, 2, 4].interleave([1, 3, 5]), [0, 1, 2, 3, 4, 5]);
442    /// ```
443    fn interleave(self, with: [T; N]) -> [T; N * 2];
444    /// [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) (`A  ×  B`) of two arrays.
445    /// ```
446    /// # #![feature(generic_const_exprs)]
447    /// # use atools::prelude::*;
448    /// assert_eq!([1u64, 2].cartesian_product(&["Π", "Σ"]), [(1, "Π"), (1, "Σ"), (2, "Π"), (2, "Σ")]);
449    /// ```
450    fn cartesian_product<U: Clone, const M: usize>(self, with: &[U; M]) -> [(T, U); N * M]
451    where
452        T: Clone;
453    /// Sorts it. This uses <code>[[T](slice)]::[sort_unstable](slice::sort_unstable)</code>.
454    fn sort(self) -> Self
455    where
456        T: Ord;
457    /// Sum of the array.
458    fn sum(self) -> T
459    where
460        T: core::iter::Sum<T>;
461    /// Product of the array.
462    fn product(self) -> T
463    where
464        T: core::iter::Product<T>;
465}
466
467impl<T, const N: usize> ArrayTools<T, N> for [T; N] {
468    fn skip<const BY: usize>(self) -> [T; N - BY] {
469        self.into_iter().skip(BY).carr()
470    }
471    fn step<const STEP: usize>(self) -> [T; 1 + (N - 1) / (STEP)] {
472        self.into_iter().step_by(STEP).carr()
473    }
474    fn intersperse(self, with: T) -> [T; (N * 2) - 1]
475    where
476        T: Clone,
477    {
478        self.into_iter().intersperse(with).carr()
479    }
480
481    fn each(self, apply: impl FnMut(T)) {
482        self.into_iter().for_each(apply);
483    }
484
485    fn enumerate(self) -> [(T, usize); N] {
486        let mut n = 0;
487        self.map(|x| {
488            let o = n;
489            n += 1;
490            (x, o)
491        })
492    }
493
494    fn windowed<const W: usize>(&self) -> [&[T; W]; N - W + 1] {
495        self.array_windows().carr()
496    }
497
498    fn inspect(self, f: impl FnMut(&T)) -> Self {
499        self.iter().for_each(f);
500        self
501    }
502
503    fn rev(mut self) -> Self {
504        self.reverse();
505        self
506    }
507
508    fn interleave(self, with: [T; N]) -> [T; N * 2] {
509        let mut which = true;
510        let mut a = self.into_iter();
511        let mut b = with.into_iter();
512        from_fn(|_| {
513            which = !which;
514            match which {
515                false => a.next().unwrap(),
516                true => b.next().unwrap(),
517            }
518        })
519    }
520
521    fn cartesian_product<U: Clone, const M: usize>(self, with: &[U; M]) -> [(T, U); N * M]
522    where
523        T: Clone,
524    {
525        self.map(|a| with.clone().map(move |b| (a.clone(), b)))
526            .flatten()
527    }
528
529    fn sort(mut self) -> Self
530    where
531        T: Ord,
532    {
533        <[T]>::sort_unstable(&mut self);
534        self
535    }
536
537    fn sum(self) -> T
538    where
539        T: core::iter::Sum<T>,
540    {
541        self.into_iter().sum()
542    }
543
544    fn product(self) -> T
545    where
546        T: core::iter::Product<T>,
547    {
548        self.into_iter().product()
549    }
550}