Skip to main content

cel_runtime/
c_stack_list.rs

1//! A [`CStackList`] is a [`List`] with guaranteed memory layout (`repr(C)`). The tail is stored
2//! first, so appending items does not change the memory layout of prior items (though the required
3//! alignment may increase). [`CNil<T>`] represents the empty list where `T` is used to hide the
4//! tail for [`std::ops::RangeTo`] and [`std::ops::RangeToInclusive`] indexing.
5//!
6//! See <https://doc.rust-lang.org/stable/reference/type-layout.html#r-layout.repr.c.struct>
7//!
8//! # Indexing
9//!
10//! Indexing is done using the [`typenum::uint::UInt`] type integral constants.
11//!
12//! Because the [`std::ops::Range`] trait requires a `start` and `end` that are the same type,
13//! it cannot be implemented for `List` types. Instead we use the [`std::ops::RangeFrom`] and
14//! [`std::ops::RangeTo`]
15//! traits. To Access a range of elements, you can use the syntax `list[..end][start..]`.
16//!
17//! # Example
18//!
19//!
20//! ```rust
21//! use cel_runtime::*;
22//! use typenum::*;
23//!
24//! let list = (1, 2.5, 3, 4, "world", "Hello").into_c_stack_list();
25//! assert_eq!(list[..U5::new()][U2::new()..], (3, 4, "world").into_c_stack_list());
26//! ```
27//!
28//! Indexing out of bounds will result in a compile error.
29//!
30//! ```compile_fail,E0277
31//! use cel_runtime::c_stack_list::*;
32//! use typenum::*;
33//!
34//! let list = (1, 2.5, 3, 4, "world", "Hello").into_c_stack_list()[U6::new()];
35//! ```
36use std::mem::offset_of;
37use std::ops::{Index, RangeFrom, RangeTo, RangeToInclusive, Sub};
38use std::{fmt, ptr};
39
40use typenum::{B1, Bit, Sub1, U0, UInt, Unsigned};
41
42use crate::list_traits::{
43    EmptyList, IntoList, List, ListIndex, ListTypeIterator, ListTypeIteratorAdvance,
44    ListTypeProperty,
45};
46
47/// Restricts layout metadata to representations controlled by this module.
48mod sealed {
49    /// Marks canonical representations whose field offsets the crate defines.
50    pub trait Layout {}
51}
52
53impl sealed::Layout for () {}
54impl<T: CStackListHeadLimit> sealed::Layout for CNil<T> {}
55impl<H: 'static, T: CStackListHeadLimit> sealed::Layout for CStackList<H, T> {}
56
57/// A list using a guaranteed memory layout (`repr(C)`), with tail stored first so appending items
58/// does not change the memory layout of prior items.
59///
60/// Cloning copies each field according to its `Clone` contract. Equality compares
61/// lengths and corresponding logical fields, independently of physical layout.
62///
63/// # Examples
64/// ```
65/// use cel_runtime::IntoCStackList;
66/// let list = (String::from("owned"), 7u8).into_c_stack_list();
67/// assert_eq!(list, list.clone());
68/// ```
69#[repr(C)]
70#[derive(Clone)]
71pub struct CStackList<H, T: CStackListHeadLimit>(pub T, pub H);
72
73/// Describes the trusted head boundary of a canonical stack-list representation.
74///
75/// Only this crate defines layout metadata used by safe indexing and execution.
76///
77/// # Examples
78/// ```
79/// use cel_runtime::{CStackList, CStackListHeadLimit, CNil};
80/// assert_eq!(CStackList::<u32, CNil<()>>::HEAD_LIMIT, 4);
81/// ```
82///
83/// Foreign types cannot supply unchecked representation metadata:
84///
85/// ```compile_fail
86/// use cel_runtime::CStackListHeadLimit;
87/// struct Foreign;
88/// impl CStackListHeadLimit for Foreign {
89///     const HEAD_LIMIT: usize = 0;
90/// }
91/// ```
92pub trait CStackListHeadLimit: sealed::Layout {
93    /// The offset to the _end_ of the head element.
94    ///
95    /// # Examples
96    /// See the [`CStackListHeadLimit`] example.
97    const HEAD_LIMIT: usize;
98}
99
100/// Indicates whether the head element is padded to satisfy alignment.
101///
102/// # Examples
103/// ```
104/// use cel_runtime::{CStackList, CStackListHeadPadded, CNil};
105/// type ByteStack = CStackList<u8, CNil<()>>;
106/// assert!(!ByteStack::HEAD_PADDED);
107/// ```
108pub trait CStackListHeadPadded: CStackListHeadLimit {
109    /// Whether the head element is padded to the next alignment boundary.
110    ///
111    /// # Examples
112    /// See the [`CStackListHeadPadded`] example.
113    const HEAD_PADDED: bool;
114}
115
116impl<H: 'static, T: CStackListHeadLimit> CStackListHeadPadded for CStackList<H, T> {
117    const HEAD_PADDED: bool = offset_of!(Self, 1) != T::HEAD_LIMIT;
118}
119
120impl<H: 'static, T: CStackListHeadLimit> CStackListHeadLimit for CStackList<H, T> {
121    const HEAD_LIMIT: usize = offset_of!(Self, 1) + size_of::<H>();
122}
123
124impl<T: CStackListHeadLimit> CStackListHeadLimit for CNil<T> {
125    const HEAD_LIMIT: usize = T::HEAD_LIMIT;
126}
127
128impl CStackListHeadLimit for () {
129    const HEAD_LIMIT: usize = 0;
130}
131
132impl<H: 'static, T: List + CStackListHeadLimit> List for CStackList<H, T> {
133    type Empty = CNil<()>;
134    /// Creates the canonical empty list without borrowing this list's values.
135    fn empty() -> Self::Empty {
136        CNil(())
137    }
138
139    type Head = H;
140    /// Borrows the first logical field.
141    fn head(&self) -> &Self::Head {
142        &self.1
143    }
144
145    type Tail = T;
146    /// Borrows the remaining logical fields.
147    fn tail(&self) -> &Self::Tail {
148        &self.0
149    }
150
151    type Push<U: 'static> = CStackList<U, Self>;
152    /// Moves a new first field and this list into their canonical node.
153    fn push<U: 'static>(self, item: U) -> Self::Push<U> {
154        CStackList(self, item)
155    }
156
157    type Append<U: List> = <T::Append<U> as List>::Push<H>;
158    /// Moves these fields before `other` without cloning them.
159    ///
160    /// - Complexity: O(n) field moves for n fields in this list.
161    fn append<U: List>(self, other: U) -> Self::Append<U> {
162        self.0.append(other).push(self.1)
163    }
164
165    type ReverseOnto<U: List> = T::ReverseOnto<U::Push<H>>;
166    /// Moves these fields in reverse order before `other`.
167    ///
168    /// - Complexity: O(n) field moves for n fields in this list.
169    fn reverse_onto<U: List>(self, other: U) -> Self::ReverseOnto<U> {
170        self.0.reverse_onto(other.push(self.1))
171    }
172}
173
174/// Converts tuples and list-like values into a source-ordered [`CStackList`].
175///
176/// The first source field becomes the logical head, even though each `repr(C)`
177/// node physically stores its tail before its head.
178///
179/// # Examples
180///
181/// ```
182/// use cel_runtime::{IntoCStackList, IntoRustTuple};
183///
184/// let list = (String::from("left"), 7_u8).into_c_stack_list();
185/// assert_eq!(list.into_rust_tuple(), (String::from("left"), 7));
186/// ```
187pub trait IntoCStackList {
188    /// The resulting list type.
189    type Output: List;
190    /// Moves fields into a `CStackList`, preserving logical source order.
191    ///
192    /// - Complexity: Native tuple conversions take O(n) field moves for n fields,
193    ///   without heap allocation.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use cel_runtime::{IntoCStackList, List};
199    ///
200    /// assert_eq!((1_u8, 2_u16).into_c_stack_list().len(), 2);
201    /// ```
202    fn into_c_stack_list(self) -> Self::Output;
203}
204
205impl<T: IntoList> IntoCStackList for T {
206    type Output = T::Output<CNil<()>>;
207    /// Moves the source fields into canonical source order.
208    ///
209    /// - Complexity: O(n) field moves for n source fields.
210    fn into_c_stack_list(self) -> Self::Output {
211        self.into_list()
212    }
213}
214
215/// Moves a canonical list into a native Rust tuple in logical source order.
216///
217/// Canonical lists terminate in [`CNil<()>`]. Native tuple bridges support zero
218/// through twelve fields; lists themselves have no arity limit. Nested list
219/// fields remain lists rather than being recursively converted or flattened.
220/// Conversion requires no cloning, equality, or formatting capabilities.
221///
222/// # Examples
223///
224/// ```
225/// use cel_runtime::{IntoCStackList, IntoRustTuple};
226///
227/// let list = (String::from("left"), 7_u8, 2.5_f64).into_c_stack_list();
228/// let value: (String, u8, f64) = list.into_rust_tuple();
229/// assert_eq!(value, (String::from("left"), 7, 2.5));
230/// ```
231pub trait IntoRustTuple {
232    /// The native tuple type with fields in logical source order.
233    type Tuple;
234
235    /// Moves each logical field into the corresponding native tuple field.
236    ///
237    /// - Complexity: O(n) field moves for n fields, without heap allocation.
238    ///
239    /// # Examples
240    ///
241    /// ```
242    /// use cel_runtime::{IntoCStackList, IntoRustTuple};
243    ///
244    /// let value: (String,) = (String::from("owned"),)
245    ///     .into_c_stack_list()
246    ///     .into_rust_tuple();
247    /// assert_eq!(value.0, "owned");
248    /// ```
249    fn into_rust_tuple(self) -> Self::Tuple;
250}
251
252impl IntoRustTuple for CNil<()> {
253    type Tuple = ();
254
255    /// Consumes the canonical empty list and returns the empty tuple.
256    fn into_rust_tuple(self) -> Self::Tuple {}
257}
258
259/// Implements native tuple bridges by destructuring tail-first canonical nodes.
260macro_rules! impl_rust_tuple {
261    (@type) => { CNil<()> };
262    (@type $head:ident $(, $tail:ident)*) => {
263        CStackList<$head, impl_rust_tuple!(@type $($tail),*)>
264    };
265    (@pattern) => { CNil(()) };
266    (@pattern $head:ident $(, $tail:ident)*) => {
267        CStackList(impl_rust_tuple!(@pattern $($tail),*), $head)
268    };
269    ($($head:ident : $value:ident),+) => {
270        impl<$($head: 'static),+> IntoRustTuple for impl_rust_tuple!(@type $($head),+) {
271            type Tuple = ($($head,)+);
272
273            /// Moves the canonical fields into their corresponding native tuple positions.
274            ///
275            /// - Complexity: O(n) field moves for n fields, without allocation.
276            fn into_rust_tuple(self) -> Self::Tuple {
277                let impl_rust_tuple!(@pattern $($value),+) = self;
278                ($($value,)+)
279            }
280        }
281    };
282}
283
284impl_rust_tuple!(A: a);
285impl_rust_tuple!(A: a, B: b);
286impl_rust_tuple!(A: a, B: b, C: c);
287impl_rust_tuple!(A: a, B: b, C: c, D: d);
288impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e);
289impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f);
290impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g);
291impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h);
292impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i);
293impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i, J: j);
294impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i, J: j, K: k);
295impl_rust_tuple!(A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i, J: j, K: k, L: l);
296
297impl<H: 'static, T: List + CStackListHeadLimit> ListIndex<RangeFrom<U0>> for CStackList<H, T> {
298    type Output = CStackList<H, T>;
299    /// Borrows the complete suffix starting at zero.
300    fn index(&self, _index: RangeFrom<U0>) -> &Self::Output {
301        self
302    }
303}
304
305impl<H: 'static, T: List + CStackListHeadLimit, U: Unsigned, B: Bit>
306    ListIndex<RangeFrom<UInt<U, B>>> for CStackList<H, T>
307where
308    T: ListIndex<RangeFrom<Sub1<UInt<U, B>>>>,
309    UInt<U, B>: Sub<B1>,
310{
311    type Output = <T as ListIndex<RangeFrom<Sub1<UInt<U, B>>>>>::Output;
312    /// Borrows the suffix at the type-checked source index.
313    ///
314    /// - Complexity: O(i) tail traversals for source index i.
315    fn index(&self, index: RangeFrom<UInt<U, B>>) -> &Self::Output {
316        self.tail().index((index.start - B1)..)
317    }
318}
319
320impl<H: 'static, T: List + CStackListHeadLimit> ListIndex<RangeTo<U0>> for CStackList<H, T> {
321    type Output = CNil<CStackList<H, T>>;
322    /// Borrows an empty prefix without transferring or dropping the backing fields.
323    fn index(&self, _index: RangeTo<U0>) -> &Self::Output {
324        unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
325    }
326}
327
328/// Selects the tail's exclusive prefix after removing the current logical head.
329type TailRangeTo<T, U, B> = <T as ListIndex<RangeTo<Sub1<UInt<U, B>>>>>::Output;
330
331impl<H: 'static, T: List + CStackListHeadLimit, U: Unsigned, B: Bit> ListIndex<RangeTo<UInt<U, B>>>
332    for CStackList<H, T>
333where
334    T: ListIndex<RangeTo<Sub1<UInt<U, B>>>>,
335    TailRangeTo<T, U, B>: List,
336    UInt<U, B>: Sub<B1>,
337{
338    type Output = <TailRangeTo<T, U, B> as List>::Push<H>;
339    /// Borrows the type-checked exclusive prefix in place.
340    fn index(&self, _index: RangeTo<UInt<U, B>>) -> &Self::Output {
341        unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
342    }
343}
344
345impl<H: 'static, T: List + CStackListHeadLimit> ListIndex<RangeToInclusive<U0>>
346    for CStackList<H, T>
347{
348    type Output = CStackList<H, CNil<T>>;
349    /// Borrows the singleton prefix without moving the backing tail.
350    fn index(&self, _index: RangeToInclusive<U0>) -> &Self::Output {
351        unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
352    }
353}
354
355/// Selects the tail's inclusive prefix after removing the current logical head.
356type TailRangeToInclusive<T, U, B> = <T as ListIndex<RangeToInclusive<Sub1<UInt<U, B>>>>>::Output;
357
358impl<H: 'static, T: List + CStackListHeadLimit, U: Unsigned, B: Bit>
359    ListIndex<RangeToInclusive<UInt<U, B>>> for CStackList<H, T>
360where
361    T: ListIndex<RangeToInclusive<Sub1<UInt<U, B>>>>,
362    TailRangeToInclusive<T, U, B>: List,
363    UInt<U, B>: Sub<B1>,
364{
365    type Output = <TailRangeToInclusive<T, U, B> as List>::Push<H>;
366    /// Borrows the type-checked inclusive prefix in place.
367    fn index(&self, _index: RangeToInclusive<UInt<U, B>>) -> &Self::Output {
368        unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
369    }
370}
371
372impl<H: 'static, T: List + CStackListHeadLimit> ListIndex<U0> for CStackList<H, T> {
373    type Output = H;
374    /// Borrows the first logical field.
375    fn index(&self, _index: U0) -> &Self::Output {
376        self.head()
377    }
378}
379
380impl<H: 'static, T: List + CStackListHeadLimit, U: Unsigned, B: Bit> ListIndex<UInt<U, B>>
381    for CStackList<H, T>
382where
383    T: ListIndex<Sub1<UInt<U, B>>>,
384    UInt<U, B>: Sub<B1>,
385{
386    type Output = <T as ListIndex<Sub1<UInt<U, B>>>>::Output;
387    /// Borrows the field at the type-checked source index.
388    ///
389    /// - Complexity: O(i) tail traversals for source index i.
390    fn index(&self, index: UInt<U, B>) -> &Self::Output {
391        self.tail().index(index - B1)
392    }
393}
394
395// Implement Index in terms of ListIndex for CStackList
396impl<H: 'static, T: List + CStackListHeadLimit, Idx> Index<Idx> for CStackList<H, T>
397where
398    Self: ListIndex<Idx>,
399    <Self as ListIndex<Idx>>::Output: Sized,
400{
401    type Output = <Self as ListIndex<Idx>>::Output;
402    /// Borrows the field or sublist selected by the underlying list index.
403    ///
404    /// - Complexity: The selected [`ListIndex`] operation's complexity.
405    fn index(&self, index: Idx) -> &Self::Output {
406        ListIndex::index(self, index)
407    }
408}
409
410/// Formats the remaining source-ordered fields after an opening tuple field.
411trait DebugHelper {
412    /// Writes field separators and closes the tuple.
413    ///
414    /// # Errors
415    /// Returns an error when the destination or a field formatter fails.
416    ///
417    /// - Complexity: O(n) field formatting operations for n remaining fields.
418    fn fmt_helper(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
419}
420
421impl<T: CStackListHeadLimit> DebugHelper for CNil<T> {
422    /// Closes a tuple after its last field.
423    ///
424    /// # Errors
425    /// Returns a destination formatting error.
426    fn fmt_helper(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        write!(f, ")")
428    }
429}
430
431impl<H: 'static, T: List + CStackListHeadLimit> DebugHelper for CStackList<H, T>
432where
433    H: fmt::Debug,
434    T: DebugHelper,
435{
436    /// Formats this head and the remaining logical fields in source order.
437    ///
438    /// # Errors
439    /// Returns a destination or field formatting error.
440    ///
441    /// - Complexity: O(n) field formatting operations for n fields.
442    fn fmt_helper(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443        write!(f, ", {:?}", self.head())?;
444        self.tail().fmt_helper(f)
445    }
446}
447
448impl<T: CStackListHeadLimit> fmt::Debug for CNil<T> {
449    /// Formats the empty list as an empty tuple.
450    ///
451    /// # Errors
452    /// Returns a destination formatting error.
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        write!(f, "()")
455    }
456}
457
458impl<H: 'static, T: List + CStackListHeadLimit> fmt::Debug for CStackList<H, T>
459where
460    H: fmt::Debug,
461    T: DebugHelper,
462{
463    /// Formats the logical fields as a source-ordered tuple.
464    ///
465    /// # Errors
466    /// Returns a destination or field formatting error.
467    ///
468    /// - Complexity: O(n) field formatting operations for n fields.
469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470        write!(f, "({:?}", self.head())?;
471        self.tail().fmt_helper(f)
472    }
473}
474
475impl<T: List + CStackListHeadLimit, O: List> std::cmp::PartialEq<O> for CNil<T> {
476    /// Returns whether the other logical list is also empty.
477    fn eq(&self, other: &O) -> bool {
478        other.is_empty()
479    }
480}
481
482impl<H: 'static, T: List + CStackListHeadLimit, O: List> std::cmp::PartialEq<O> for CStackList<H, T>
483where
484    H: PartialEq<O::Head>,
485    T: PartialEq<O::Tail>,
486{
487    /// Compares lengths and corresponding logical elements.
488    ///
489    /// - Complexity: O(n) field comparisons for n elements, excluding field costs.
490    fn eq(&self, other: &O) -> bool {
491        self.len() == other.len() && self.head() == other.head() && self.tail() == other.tail()
492    }
493}
494
495/// Empty `repr(C)` list used as the tail sentinel for [`CStackList`].
496///
497/// The hidden backing tail preserves prefix-view layout but contributes no
498/// logical fields. Construct an owning empty root through [`EmptyList::root_empty`].
499///
500/// # Examples
501/// ```
502/// use cel_runtime::{CNil, EmptyList, IntoCStackList, IntoRustTuple, List};
503/// let empty = CNil::<()>::root_empty();
504/// assert!(empty.is_empty());
505/// assert_eq!(empty.push_first("first").into_rust_tuple(), ("first",));
506/// assert_eq!(().into_c_stack_list().len(), 0);
507/// ```
508#[repr(C)]
509#[derive(Clone)]
510pub struct CNil<T: CStackListHeadLimit>(T);
511
512impl<T: CStackListHeadLimit> EmptyList for CNil<T> {
513    type PushFirst<U: 'static> = CStackList<U, CNil<T>>;
514    /// Moves a first field into a node backed by this empty sentinel.
515    fn push_first<U: 'static>(self, item: U) -> Self::PushFirst<U> {
516        CStackList(self, item)
517    }
518
519    type RootEmpty = CNil<()>;
520    /// Constructs the empty canonical root without backing fields.
521    fn root_empty() -> Self::RootEmpty {
522        CNil(())
523    }
524}
525
526impl<T: CStackListHeadLimit, P: ListTypeProperty> ListTypeIteratorAdvance<P> for CNil<T> {
527    /// Reports exhaustion without generating a property for the backing tail.
528    fn advancer<R: List>(_iter: &mut ListTypeIterator<R, P>) -> Option<P::Output> {
529        None
530    }
531}
532
533impl<P: ListTypeProperty, H: 'static, T: ListTypeIteratorAdvance<P> + CStackListHeadLimit>
534    ListTypeIteratorAdvance<P> for CStackList<H, T>
535{
536    /// Generates this head's property and advances the iterator to its tail.
537    ///
538    /// - Complexity: The property generator's complexity.
539    fn advancer<R: List>(iter: &mut ListTypeIterator<R, P>) -> Option<P::Output> {
540        iter.advance = T::advancer::<R>;
541        Some(P::property::<CStackList<H, T>>())
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use typenum::{U1, U2, U5};
548
549    use crate::list_traits::Item;
550
551    use super::*;
552
553    /// Moves empty, singleton, and maximum-arity native tuples without cloning their fields.
554    #[test]
555    fn native_tuple_bridge_moves_boundary_arities() {
556        /// Owns text without providing clone or equality capabilities.
557        struct MoveOnly(Box<str>);
558
559        let (): () = ().into_c_stack_list().into_rust_tuple();
560        let value = MoveOnly(String::from("singleton").into_boxed_str());
561        let pointer = value.0.as_ptr();
562        let (value,) = (value,).into_c_stack_list().into_rust_tuple();
563        assert_eq!(value.0.as_ptr(), pointer);
564        assert_eq!(&*value.0, "singleton");
565
566        let first = MoveOnly(String::from("first").into_boxed_str());
567        let last = MoveOnly(String::from("last").into_boxed_str());
568        let pointers = (first.0.as_ptr(), last.0.as_ptr());
569        let (first, a, b, c, d, e, flag, number, letter, unit, text, last) = (
570            first,
571            1u8,
572            2u16,
573            3u32,
574            4u64,
575            5u128,
576            true,
577            7f64,
578            'x',
579            (),
580            String::from("middle"),
581            last,
582        )
583            .into_c_stack_list()
584            .into_rust_tuple();
585        assert_eq!((first.0.as_ptr(), last.0.as_ptr()), pointers);
586        assert_eq!((&*first.0, &*last.0), ("first", "last"));
587        assert_eq!(
588            (a, b, c, d, e, flag, number, letter, unit, text.as_str()),
589            (1, 2, 3, 4, 5, true, 7.0, 'x', (), "middle")
590        );
591    }
592
593    /// Keeps cloned mutable fields disjoint and equality consistent across copies.
594    #[test]
595    fn clone_and_equality_laws() {
596        let mut original = (vec![String::from("first")],).into_c_stack_list();
597        let mut copied = original.clone();
598        let third = copied.clone();
599        assert!(original == original);
600        assert!(original == copied && copied == original);
601        assert!(copied == third && original == third);
602        assert!(!(original != copied));
603        copied.1.push(String::from("copy-only"));
604        assert_eq!(original.head(), &["first"]);
605        original.1[0].push_str("-original");
606        assert_eq!(copied.head(), &["first", "copy-only"]);
607        assert_eq!(third.head(), &["first"]);
608        assert!(original != copied);
609    }
610
611    /// Compares list lengths before accessing a potentially absent head.
612    #[test]
613    fn equality_handles_different_lengths() {
614        /// Compares equal to another token but not to an absent value.
615        #[derive(Clone, PartialEq)]
616        struct Token;
617
618        impl PartialEq<crate::list_traits::Undefined> for Token {
619            /// Distinguishes a present token from an empty-list marker.
620            fn eq(&self, _: &crate::list_traits::Undefined) -> bool {
621                false
622            }
623        }
624
625        let empty = ().into_c_stack_list();
626        let one = (Token,).into_c_stack_list();
627        let two = (Token, Token).into_c_stack_list();
628        assert!(one != empty);
629        assert!(empty != one);
630        assert!(two != one);
631        assert!(one != two);
632        assert!(one == one.clone());
633    }
634
635    /// Preserves heterogeneous native-tuple field order, including the empty tuple.
636    #[test]
637    fn into_c_stack_list() {
638        let list = (1, 2.5, 3, 4, "world", "Hello").into_c_stack_list();
639        assert_eq!(
640            list,
641            CStackList(
642                CStackList(
643                    CStackList(
644                        CStackList(CStackList(CStackList(CNil(()), "Hello"), "world"), 4),
645                        3
646                    ),
647                    2.5
648                ),
649                1
650            )
651        );
652        assert_eq!(().into_c_stack_list(), CNil(()));
653    }
654
655    /// Borrows each heterogeneous field at its type-checked source index.
656    #[test]
657    fn index() {
658        let list = (1, 2.5, "Hello").into_c_stack_list();
659        assert_eq!(list[U0::new()], 1);
660        assert_eq!(list[U1::new()], 2.5);
661        assert_eq!(list[U2::new()], "Hello");
662    }
663
664    /// Formats a composed borrowed prefix/suffix view without exposing its backing tail.
665    #[test]
666    fn slice() {
667        let list = (1, 2.5, 3, 4, "world", "Hello").into_c_stack_list();
668        let view = &list[..U5::new()][U2::new()..];
669        assert_eq!(view.len(), 3);
670        assert_eq!(format!("{view:?}"), "(3, 4, \"world\")");
671        assert_eq!(format!("{:?}", ().into_c_stack_list()), "()");
672    }
673
674    /// Indexes a borrowed suffix relative to its new logical beginning.
675    #[test]
676    fn index_range_from() {
677        let list = (1, 2.5, "Hello").into_c_stack_list();
678        assert_eq!(list[U1::new()..][U1::new()], "Hello");
679    }
680
681    /// Borrows an exclusive prefix without changing the retained fields.
682    #[test]
683    fn index_range_to() {
684        let list = (1, 2.5, "Hello").into_c_stack_list();
685        assert_eq!(list[..U2::new()][U1::new()], 2.5);
686    }
687
688    /// Resolves each logical field's Rust type from its type-level index.
689    #[test]
690    fn index_type() {
691        use std::any::type_name;
692
693        /// Describes the heterogeneous canonical source list.
694        type List = <(i32, f64, &'static str) as IntoList>::Output<CNil<()>>;
695        /// Selects the first field's concrete type.
696        type Zero = Item<List, U0>;
697        /// Selects the second field's concrete type.
698        type One = Item<List, U1>;
699        /// Selects the third field's concrete type.
700        type Two = Item<List, U2>;
701        assert_eq!(type_name::<Zero>(), "i32");
702        assert_eq!(type_name::<One>(), "f64");
703        assert_eq!(type_name::<Two>(), "&str");
704    }
705
706    /// Preserves the documented tail-first C representation of owned fields.
707    #[test]
708    fn cstack_list() {
709        let list = CStackList(CNil(()), 32i32).push("Hello").push(42.5);
710        // Test that we can cast to a C struct and read values
711        /// Mirrors the three fields' public tail-first C layout.
712        #[repr(C)]
713        struct TestStruct(i32, &'static str, f64);
714
715        let test_struct = unsafe {
716            std::mem::transmute::<
717                CStackList<f64, CStackList<&str, CStackList<i32, CNil<()>>>>,
718                TestStruct,
719            >(list)
720        };
721
722        assert_eq!(test_struct.0, 32);
723        assert_eq!(test_struct.1, "Hello");
724        assert_eq!(test_struct.2, 42.5);
725    }
726}