generic_array/
functional.rs

1//! Functional programming with generic sequences
2//!
3//! Please see `tests/generics.rs` for examples of how to best use these in your generic functions.
4
5use core::iter::FromIterator;
6
7use crate::sequence::*;
8
9/// Defines the relationship between one generic sequence and another,
10/// for operations such as `map` and `zip`.
11pub trait MappedGenericSequence<T, U>: GenericSequence<T> {
12    /// Mapped sequence type
13    type Mapped: GenericSequence<U, Length = Self::Length>;
14}
15
16impl<'a, T, U, S: MappedGenericSequence<T, U>> MappedGenericSequence<T, U> for &'a S
17where
18    &'a S: GenericSequence<T>,
19    S: GenericSequence<T, Length = <&'a S as GenericSequence<T>>::Length>,
20{
21    type Mapped = <S as MappedGenericSequence<T, U>>::Mapped;
22}
23
24impl<'a, T, U, S: MappedGenericSequence<T, U>> MappedGenericSequence<T, U> for &'a mut S
25where
26    &'a mut S: GenericSequence<T>,
27    S: GenericSequence<T, Length = <&'a mut S as GenericSequence<T>>::Length>,
28{
29    type Mapped = <S as MappedGenericSequence<T, U>>::Mapped;
30}
31
32/// Accessor type for a mapped generic sequence
33pub type MappedSequence<S, T, U> =
34    <<S as MappedGenericSequence<T, U>>::Mapped as GenericSequence<U>>::Sequence;
35
36/// Defines functional programming methods for generic sequences
37pub trait FunctionalSequence<T>: GenericSequence<T> {
38    /// Maps a `GenericSequence` to another `GenericSequence`.
39    ///
40    /// If the mapping function panics, any already initialized elements in the new sequence
41    /// will be dropped, AND any unused elements in the source sequence will also be dropped.
42    #[inline]
43    fn map<U, F>(self, f: F) -> MappedSequence<Self, T, U>
44    where
45        Self: MappedGenericSequence<T, U>,
46        F: FnMut(Self::Item) -> U,
47    {
48        FromIterator::from_iter(self.into_iter().map(f))
49    }
50
51    /// Combines two `GenericSequence` instances and iterates through both of them,
52    /// initializing a new `GenericSequence` with the result of the zipped mapping function.
53    ///
54    /// If the mapping function panics, any already initialized elements in the new sequence
55    /// will be dropped, AND any unused elements in the source sequences will also be dropped.
56    ///
57    /// **WARNING**: If using the `alloc` crate feature, mixing stack-allocated
58    /// `GenericArray<T, N>` and heap-allocated `Box<GenericArray<T, N>>` within [`zip`](FunctionalSequence::zip)
59    /// should be done with care or avoided.
60    ///
61    /// For copy-types, it could be easy to accidentally move the array
62    /// out of the `Box` when zipping with a stack-allocated array, which could cause a stack-overflow
63    /// if the array is sufficiently large. However, that being said, the second where clause
64    /// ensuring they map to the same sequence type will catch common errors, such as:
65    ///
66    /// ```compile_fail
67    /// # use generic_array::{*, functional::FunctionalSequence};
68    /// # #[cfg(feature = "alloc")]
69    /// fn test() {
70    ///     let stack = arr![1, 2, 3, 4];
71    ///     let heap = box_arr![5, 6, 7, 8];
72    ///     let mixed = stack.zip(heap, |a, b| a + b);
73    ///     //                --- ^^^^ expected struct `GenericArray`, found struct `Box`
74    /// }
75    /// # #[cfg(not(feature = "alloc"))]
76    /// # compile_error!("requires alloc feature to test this properly");
77    /// ```
78    #[inline]
79    fn zip<B, Rhs, U, F>(self, rhs: Rhs, f: F) -> MappedSequence<Self, T, U>
80    where
81        Self: MappedGenericSequence<T, U>,
82        Rhs: MappedGenericSequence<B, U, Mapped = MappedSequence<Self, T, U>>,
83        Rhs: GenericSequence<B, Length = Self::Length>,
84        F: FnMut(Self::Item, Rhs::Item) -> U,
85    {
86        rhs.inverted_zip2(self, f)
87    }
88
89    /// Folds (or reduces) a sequence of data into a single value.
90    ///
91    /// If the fold function panics, any unused elements will be dropped.
92    #[inline]
93    fn fold<U, F>(self, init: U, f: F) -> U
94    where
95        F: FnMut(U, Self::Item) -> U,
96    {
97        self.into_iter().fold(init, f)
98    }
99}
100
101impl<'a, T, S: GenericSequence<T>> FunctionalSequence<T> for &'a S where &'a S: GenericSequence<T> {}
102
103impl<'a, T, S: GenericSequence<T>> FunctionalSequence<T> for &'a mut S where
104    &'a mut S: GenericSequence<T>
105{
106}