Skip to main content

cel_runtime/
tuple_list.rs

1//! Implements [`List`] for tuples where `()` is an empty list and `(H, T)` is a list with a head
2//! and tail.
3//!
4//! ```
5//! use cel_runtime::{IntoTupleList, List};
6//! let list = (String::from("first"), 7u8).into_tuple_list();
7//! assert_eq!(list.head(), "first");
8//! assert_eq!(list.reverse().reverse().len(), 2);
9//! ```
10
11use typenum::{B1, Bit, Sub1, U0, UInt, Unsigned};
12
13use crate::list_traits::{
14    EmptyList, IntoList, List, ListIndex, ListTypeIterator, ListTypeIteratorAdvance,
15    ListTypeProperty,
16};
17use std::ops::{RangeFrom, Sub};
18
19/// Converts tuples into a `List` representation where `()` is empty and `(H, T)` is a cons cell.
20///
21/// # Examples
22/// See the [module tutorial](self).
23pub trait IntoTupleList {
24    /// The resulting list type.
25    type Output: List;
26    /// Moves source fields into a `List` where `(H, T)` models a cons cell.
27    ///
28    /// - Complexity: O(n) field moves for n source fields, without allocation.
29    ///
30    /// # Examples
31    /// See [`IntoTupleList`].
32    fn into_tuple_list(self) -> Self::Output;
33}
34
35impl<T: IntoList> IntoTupleList for T {
36    type Output = T::Output<()>;
37    /// Moves fields into their source-ordered tuple-list representation.
38    ///
39    /// - Complexity: O(n) field moves for n source fields.
40    fn into_tuple_list(self) -> Self::Output {
41        self.into_list()
42    }
43}
44
45//--------------------------------------------------------------------------------------------------
46// ListTypeIteratorAdvance
47
48impl<P: ListTypeProperty> ListTypeIteratorAdvance<P> for () {
49    /// Reports exhaustion without generating a head property.
50    fn advancer<R: List>(_iter: &mut ListTypeIterator<R, P>) -> Option<P::Output> {
51        None
52    }
53}
54
55impl<P: ListTypeProperty, H: 'static, T: ListTypeIteratorAdvance<P>> ListTypeIteratorAdvance<P>
56    for (H, T)
57{
58    /// Generates the current head property and advances to the tail.
59    ///
60    /// - Complexity: The property generator's complexity.
61    fn advancer<R: List>(iter: &mut ListTypeIterator<R, P>) -> Option<P::Output> {
62        iter.advance = T::advancer::<R>;
63        Some(P::property::<(H, T)>())
64    }
65}
66
67//--------------------------------------------------------------------------------------------------
68// EmptyList for ()
69
70impl EmptyList for () {
71    type PushFirst<U: 'static> = (U, ());
72    /// Moves the first field into a singleton tuple list.
73    fn push_first<U: 'static>(self, item: U) -> Self::PushFirst<U> {
74        (item, ())
75    }
76
77    type RootEmpty = Self;
78    /// Constructs the empty tuple-list root.
79    fn root_empty() -> Self::RootEmpty {}
80}
81
82//--------------------------------------------------------------------------------------------------
83// List for (H, T)
84
85impl<H: 'static, T: List> List for (H, T) {
86    type Empty = ();
87    /// Constructs an empty tuple-list root without accessing these fields.
88    fn empty() -> Self::Empty {}
89
90    type Head = H;
91    /// Borrows the first logical field.
92    fn head(&self) -> &Self::Head {
93        &self.0
94    }
95
96    type Tail = T;
97    /// Borrows the remaining logical fields.
98    fn tail(&self) -> &Self::Tail {
99        &self.1
100    }
101
102    type Push<U: 'static> = (U, Self);
103    /// Moves a new first field and this list into their tuple node.
104    fn push<U: 'static>(self, item: U) -> Self::Push<U> {
105        (item, self)
106    }
107
108    type Append<U: List> = <T::Append<U> as List>::Push<H>;
109    /// Moves these source-ordered fields before `other`.
110    ///
111    /// - Complexity: O(n) field moves for n fields in this list.
112    fn append<U: List>(self, other: U) -> Self::Append<U> {
113        self.1.append(other).push(self.0)
114    }
115
116    type ReverseOnto<U: List> = T::ReverseOnto<U::Push<H>>;
117    /// Moves these fields in reverse order before `other`.
118    ///
119    /// - Complexity: O(n) field moves for n fields in this list.
120    fn reverse_onto<U: List>(self, other: U) -> Self::ReverseOnto<U> {
121        self.1.reverse_onto(other.push(self.0))
122    }
123}
124
125impl ListIndex<RangeFrom<U0>> for () {
126    type Output = ();
127    /// Borrows the empty suffix at the only valid empty-list boundary.
128    fn index(&self, _index: RangeFrom<U0>) -> &Self::Output {
129        self
130    }
131}
132
133impl<H: 'static, T: List> ListIndex<RangeFrom<U0>> for (H, T) {
134    type Output = (H, T);
135    /// Borrows the complete suffix starting at zero.
136    fn index(&self, _index: RangeFrom<U0>) -> &Self::Output {
137        self
138    }
139}
140
141impl<H: 'static, T: List, U: Unsigned, B: Bit> ListIndex<RangeFrom<UInt<U, B>>> for (H, T)
142where
143    T: ListIndex<RangeFrom<Sub1<UInt<U, B>>>>,
144    UInt<U, B>: Sub<B1>,
145{
146    type Output = <T as ListIndex<RangeFrom<Sub1<UInt<U, B>>>>>::Output;
147    /// Borrows the suffix at the type-checked source index.
148    ///
149    /// - Complexity: O(i) tail traversals for source index i.
150    fn index(&self, index: RangeFrom<UInt<U, B>>) -> &Self::Output {
151        self.tail().index((index.start - B1)..)
152    }
153}
154
155impl<H: 'static, T: List> ListIndex<U0> for (H, T) {
156    type Output = H;
157    /// Borrows the first source field.
158    fn index(&self, _index: U0) -> &Self::Output {
159        self.head()
160    }
161}
162
163impl<H: 'static, T: List, U: Unsigned, B: Bit> ListIndex<UInt<U, B>> for (H, T)
164where
165    T: ListIndex<Sub1<UInt<U, B>>>,
166    UInt<U, B>: Sub<B1>,
167{
168    type Output = <T as ListIndex<Sub1<UInt<U, B>>>>::Output;
169    /// Borrows the field at the type-checked source index.
170    ///
171    /// - Complexity: O(i) tail traversals for source index i.
172    fn index(&self, index: UInt<U, B>) -> &Self::Output {
173        self.tail().index(index - B1)
174    }
175}
176
177//--------------------------------------------------------------------------------------------------
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::list_traits::TypeIdIterator;
183    use std::any::TypeId;
184    use typenum::{U0, U1, U2, U3};
185
186    /// Iterates both list families in source order and remains exhausted.
187    #[test]
188    fn type_id_iterator() {
189        let ids: [TypeId; 3] = [
190            TypeId::of::<u32>(),
191            TypeId::of::<f64>(),
192            TypeId::of::<&str>(),
193        ];
194        for mut iter in [
195            TypeIdIterator::<(u32, (f64, (&str, ())))>::new(),
196            TypeIdIterator::<(u32, (f64, (&str, ())))>::default(),
197        ] {
198            assert!(iter.by_ref().eq(ids.iter().copied()));
199            assert_eq!(iter.next(), None);
200        }
201        /// Describes the same source fields in the other canonical list family.
202        type Canonical = <(u32, f64, &'static str) as crate::IntoCStackList>::Output;
203        let mut canonical = TypeIdIterator::<Canonical>::default();
204        assert!(canonical.by_ref().eq(ids));
205        assert_eq!(canonical.next(), None);
206        assert_eq!(TypeIdIterator::<()>::default().next(), None);
207        assert_eq!(TypeIdIterator::<crate::CNil<()>>::new().next(), None);
208    }
209
210    /// Constructs the empty tuple-list identity.
211    #[test]
212    fn empty_list() {
213        let () = <()>::empty();
214    }
215
216    /// Moves empty and heterogeneous native tuples into logical source order.
217    #[test]
218    fn into_list() {
219        let () = ().into_tuple_list();
220        assert_eq!((1, 2, 3).into_tuple_list(), (1, (2, (3, ()))));
221        assert_eq!(
222            (1, 2.5, "Hello").into_tuple_list(),
223            (1, (2.5, ("Hello", ())))
224        );
225    }
226
227    /// Prepends a value while preserving every existing field.
228    #[test]
229    fn push() {
230        assert_eq!(().push_first(1), (1, ()));
231        assert_eq!((1, 2, 3).into_tuple_list().push(4), (4, (1, (2, (3, ())))));
232    }
233
234    /// Concatenates two lists without reversing either sequence.
235    #[test]
236    fn append() {
237        assert_eq!(
238            (1, 2, 3)
239                .into_tuple_list()
240                .append((4, 5, 6).into_tuple_list()),
241            (1, (2, (3, (4, (5, (6, ()))))))
242        );
243    }
244
245    /// Reverses logical source order while retaining every value.
246    #[test]
247    fn reverse() {
248        assert_eq!((1, 2, 3).into_tuple_list().reverse(), (3, (2, (1, ()))));
249    }
250
251    /// Accounts for empty, singleton, and multiple-field logical lists.
252    #[test]
253    fn list_length() {
254        assert_eq!(<()>::LENGTH, 0);
255        assert_eq!(<(i32, ())>::LENGTH, 1);
256        assert_eq!(<(i32, (f64, ()))>::LENGTH, 2);
257    }
258
259    /// Borrows each heterogeneous field at its type-checked source index.
260    #[test]
261    fn list_index() {
262        let list = (1, 2.5, "Hello").into_tuple_list();
263        assert_eq!(*list.index(U0::new()), 1);
264        assert_eq!(*list.index(U1::new()), 2.5);
265        assert_eq!(*list.index(U2::new()), "Hello");
266    }
267
268    /// Borrows each suffix, including the empty suffix at the terminal index.
269    #[test]
270    fn list_range_from_index() {
271        let list = (1, 2.5, "Hello").into_tuple_list();
272        assert_eq!(*list.index(U0::new()..), (1, (2.5, ("Hello", ()))));
273        assert_eq!(*list.index(U1::new()..), (2.5, ("Hello", ())));
274        assert_eq!(*list.index(U2::new()..), ("Hello", ()));
275        let () = *list.index(U3::new()..);
276        // assert_eq!(*list.index(U4::new()..), ()); // Compiler error: index out of bounds
277    }
278}