1use 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
47mod sealed {
49 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#[repr(C)]
70#[derive(Clone)]
71pub struct CStackList<H, T: CStackListHeadLimit>(pub T, pub H);
72
73pub trait CStackListHeadLimit: sealed::Layout {
93 const HEAD_LIMIT: usize;
98}
99
100pub trait CStackListHeadPadded: CStackListHeadLimit {
109 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 fn empty() -> Self::Empty {
136 CNil(())
137 }
138
139 type Head = H;
140 fn head(&self) -> &Self::Head {
142 &self.1
143 }
144
145 type Tail = T;
146 fn tail(&self) -> &Self::Tail {
148 &self.0
149 }
150
151 type Push<U: 'static> = CStackList<U, Self>;
152 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 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 fn reverse_onto<U: List>(self, other: U) -> Self::ReverseOnto<U> {
170 self.0.reverse_onto(other.push(self.1))
171 }
172}
173
174pub trait IntoCStackList {
188 type Output: List;
190 fn into_c_stack_list(self) -> Self::Output;
203}
204
205impl<T: IntoList> IntoCStackList for T {
206 type Output = T::Output<CNil<()>>;
207 fn into_c_stack_list(self) -> Self::Output {
211 self.into_list()
212 }
213}
214
215pub trait IntoRustTuple {
232 type Tuple;
234
235 fn into_rust_tuple(self) -> Self::Tuple;
250}
251
252impl IntoRustTuple for CNil<()> {
253 type Tuple = ();
254
255 fn into_rust_tuple(self) -> Self::Tuple {}
257}
258
259macro_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 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 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 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 fn index(&self, _index: RangeTo<U0>) -> &Self::Output {
324 unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
325 }
326}
327
328type 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 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 fn index(&self, _index: RangeToInclusive<U0>) -> &Self::Output {
351 unsafe { &*ptr::from_ref(self).cast::<Self::Output>() }
352 }
353}
354
355type 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 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 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 fn index(&self, index: UInt<U, B>) -> &Self::Output {
391 self.tail().index(index - B1)
392 }
393}
394
395impl<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 fn index(&self, index: Idx) -> &Self::Output {
406 ListIndex::index(self, index)
407 }
408}
409
410trait DebugHelper {
412 fn fmt_helper(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
419}
420
421impl<T: CStackListHeadLimit> DebugHelper for CNil<T> {
422 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 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 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 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 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 fn eq(&self, other: &O) -> bool {
491 self.len() == other.len() && self.head() == other.head() && self.tail() == other.tail()
492 }
493}
494
495#[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 fn push_first<U: 'static>(self, item: U) -> Self::PushFirst<U> {
516 CStackList(self, item)
517 }
518
519 type RootEmpty = CNil<()>;
520 fn root_empty() -> Self::RootEmpty {
522 CNil(())
523 }
524}
525
526impl<T: CStackListHeadLimit, P: ListTypeProperty> ListTypeIteratorAdvance<P> for CNil<T> {
527 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 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 #[test]
555 fn native_tuple_bridge_moves_boundary_arities() {
556 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 #[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 #[test]
613 fn equality_handles_different_lengths() {
614 #[derive(Clone, PartialEq)]
616 struct Token;
617
618 impl PartialEq<crate::list_traits::Undefined> for Token {
619 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 #[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 #[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 #[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 #[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 #[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 #[test]
690 fn index_type() {
691 use std::any::type_name;
692
693 type List = <(i32, f64, &'static str) as IntoList>::Output<CNil<()>>;
695 type Zero = Item<List, U0>;
697 type One = Item<List, U1>;
699 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 #[test]
708 fn cstack_list() {
709 let list = CStackList(CNil(()), 32i32).push("Hello").push(42.5);
710 #[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}