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/// Mapped type for a generic sequence
33pub type Mapped<S, T, U> = <S as MappedGenericSequence<T, U>>::Mapped;
34
35/// Accessor type for a mapped generic sequence
36///
37/// NOTE: The choice to use the `Sequence` associated type here instead of `Mapped`
38/// is due to only the `Sequence` type being guaranteed to implement `FromIterator`.
39/// However, this does lead to some oddity where `FallibleGenericSequence::from_fallible_iter`
40/// is implemented on `Mapped`, but returns the `Sequence`/`MappedSequence` type. Same difference, though.
41pub type MappedSequence<S, T, U> = <Mapped<S, T, U> as GenericSequence<U>>::Sequence;
42
43/// Defines functional programming methods for generic sequences
44pub trait FunctionalSequence<T>: GenericSequence<T> {
45 /// Maps a `GenericSequence` to another `GenericSequence`.
46 ///
47 /// If the mapping function panics, any already initialized elements in the new sequence
48 /// will be dropped, AND any unused elements in the source sequence will also be dropped.
49 #[inline(always)]
50 fn map<U, F>(self, f: F) -> MappedSequence<Self, T, U>
51 where
52 Self: MappedGenericSequence<T, U>,
53 F: FnMut(Self::Item) -> U,
54 {
55 FromIterator::from_iter(self.into_iter().map(f))
56 }
57
58 /// Tries to map a `GenericSequence` to another `GenericSequence`, returning a `Result`.
59 ///
60 /// If the mapping function errors or panics, any already initialized elements in the new sequence
61 /// will be dropped, AND any unused elements in the source sequence will also be dropped.
62 #[inline(always)]
63 fn try_map<U, F, E>(self, f: F) -> Result<MappedSequence<Self, T, U>, E>
64 where
65 Self: MappedGenericSequence<T, U>,
66 MappedSequence<Self, T, U>: FromFallibleIterator<U>,
67 F: FnMut(Self::Item) -> Result<U, E>,
68 {
69 FromFallibleIterator::from_fallible_iter(self.into_iter().map(f))
70 }
71
72 /// Combines two `GenericSequence` instances and iterates through both of them,
73 /// initializing a new `GenericSequence` with the result of the zipped mapping function.
74 ///
75 /// If the mapping function panics, any already initialized elements in the new sequence
76 /// will be dropped, AND any unused elements in the source sequences will also be dropped.
77 ///
78 /// **WARNING**: If using the `alloc` crate feature, mixing stack-allocated
79 /// `GenericArray<T, N>` and heap-allocated `Box<GenericArray<T, N>>` within [`zip`](FunctionalSequence::zip)
80 /// should be done with care or avoided.
81 ///
82 /// For copy-types, it could be easy to accidentally move the array
83 /// out of the `Box` when zipping with a stack-allocated array, which could cause a stack-overflow
84 /// if the array is sufficiently large. However, that being said, the second where clause
85 /// ensuring they map to the same sequence type will catch common errors, such as:
86 ///
87 /// ```compile_fail
88 /// # use generic_array::{*, functional::FunctionalSequence};
89 /// # #[cfg(feature = "alloc")]
90 /// fn test() {
91 /// let stack = arr![1, 2, 3, 4];
92 /// let heap = box_arr![5, 6, 7, 8];
93 /// let mixed = stack.zip(heap, |a, b| a + b);
94 /// // --- ^^^^ expected struct `GenericArray`, found struct `Box`
95 /// }
96 /// # #[cfg(not(feature = "alloc"))]
97 /// # compile_error!("requires alloc feature to test this properly");
98 /// ```
99 #[inline(always)]
100 fn zip<B, Rhs, U, F>(self, rhs: Rhs, f: F) -> MappedSequence<Self, T, U>
101 where
102 Self: MappedGenericSequence<T, U>,
103 Rhs: MappedGenericSequence<B, U, Mapped = MappedSequence<Self, T, U>>,
104 Rhs: GenericSequence<B, Length = Self::Length>,
105 F: FnMut(Self::Item, Rhs::Item) -> U,
106 {
107 rhs.inverted_zip2(self, f)
108 }
109
110 /// Folds (or reduces) a sequence of data into a single value.
111 ///
112 /// If the fold function panics, any unused elements will be dropped.
113 #[inline(always)]
114 fn fold<U, F>(self, init: U, f: F) -> U
115 where
116 F: FnMut(U, Self::Item) -> U,
117 {
118 self.into_iter().fold(init, f)
119 }
120
121 /// Folds (or reduces) a sequence of data into a single value, returning a `Result`.
122 ///
123 /// If the fold function errors or panics, any unused elements will be dropped.
124 #[inline(always)]
125 fn try_fold<U, E, F>(self, init: U, f: F) -> Result<U, E>
126 where
127 F: FnMut(U, Self::Item) -> Result<U, E>,
128 {
129 self.into_iter().try_fold(init, f)
130 }
131}
132
133impl<'a, T, S: GenericSequence<T>> FunctionalSequence<T> for &'a S where &'a S: GenericSequence<T> {}
134
135impl<'a, T, S: GenericSequence<T>> FunctionalSequence<T> for &'a mut S where
136 &'a mut S: GenericSequence<T>
137{
138}