facet_core/impls_core/
tuple.rs

1use core::{cmp::Ordering, fmt, mem};
2
3use crate::{
4    Characteristic, Facet, MarkerTraits, SequenceType, Shape, TupleType, Type, TypeNameOpts,
5    VTableView, ValueVTable, types::field_in_type,
6};
7
8#[inline(always)]
9pub fn write_type_name_list(
10    f: &mut fmt::Formatter<'_>,
11    opts: TypeNameOpts,
12    open: &'static str,
13    delimiter: &'static str,
14    close: &'static str,
15    shapes: &'static [&'static Shape],
16) -> fmt::Result {
17    f.pad(open)?;
18    if let Some(opts) = opts.for_children() {
19        for (index, shape) in shapes.iter().enumerate() {
20            if index > 0 {
21                f.pad(delimiter)?;
22            }
23            shape.write_type_name(f, opts)?;
24        }
25    } else {
26        write!(f, "⋯")?;
27    }
28    f.pad(close)?;
29    Ok(())
30}
31
32macro_rules! impl_facet_for_tuple {
33    // Used to implement the next bigger tuple type, by taking the next typename & associated index
34    // out of `remaining`, if it exists.
35    {
36        continue from ($($elems:ident.$idx:tt,)+),
37        remaining ()
38    } => {};
39    {
40        continue from ($($elems:ident.$idx:tt,)+),
41        remaining ($next:ident.$nextidx:tt, $($remaining:ident.$remainingidx:tt,)*)
42    } => {
43        impl_facet_for_tuple! {
44            impl ($($elems.$idx,)+ $next.$nextidx,),
45            remaining ($($remaining.$remainingidx,)*)
46        }
47    };
48    // Handle commas correctly for the debug implementation
49    { debug on $f:ident { $first:stmt; } } => {
50        write!($f, "(")?;
51        $first
52        write!($f, ",)")
53    };
54    { debug on $f:ident { $first:stmt; $($stmt:stmt;)+ } } => {
55        write!($f, "(")?;
56        $first
57        $(
58            write!($f, ", ")?;
59            $stmt
60        )+
61        write!($f, ")")
62    };
63    // Common structure of eq, partial_ord & ord
64    { ord on ($($elems:ident.$idx:tt,)+), $cmp:ident($a:ident, $b:ident), eq = $eq:expr } => {{
65        $(
66            unsafe {
67                let ordering = (<VTableView<$elems>>::of().$cmp().unwrap_unchecked())(
68                    &$a.$idx,
69                    &$b.$idx,
70                );
71
72                if ordering != $eq {
73                    return ordering;
74                }
75            }
76        )+
77
78        $eq
79    }};
80    // Actually generate the trait implementation, and keep the remaining possible elements around
81    {
82        impl ($($elems:ident.$idx:tt,)+),
83        remaining ($($remaining:ident.$remainingidx:tt,)*)
84    } => {
85        unsafe impl<'a $(, $elems)+> Facet<'a> for ($($elems,)+)
86        where
87            $($elems: Facet<'a>,)+
88        {
89            const VTABLE: &'static ValueVTable = &const {
90                let mut builder = ValueVTable::builder::<Self>()
91                    .type_name(|f, opts| {
92                        write_type_name_list(f, opts, "(", ", ", ")", &[$($elems::SHAPE),+])
93                    })
94                    .drop_in_place(|data| unsafe { data.drop_in_place::<Self>() })
95                    .marker_traits(
96                        MarkerTraits::all()
97                            $(.intersection($elems::SHAPE.vtable.marker_traits))+
98                    );
99
100                let elem_shapes = const { &[$($elems::SHAPE),+] };
101                if Characteristic::Debug.all(elem_shapes) {
102                    builder = builder.debug(|value, f| {
103                        impl_facet_for_tuple! {
104                            debug on f {
105                                $(
106                                    (<VTableView<$elems>>::of().debug().unwrap())(
107                                        &value.$idx,
108                                        f,
109                                    )?;
110                                )+
111                            }
112                        }
113                    });
114                }
115
116                if Characteristic::Default.all(elem_shapes) {
117                    builder = builder.default_in_place(|mut dst| {
118                        $(
119                            unsafe {
120                                (<VTableView<$elems>>::of().default_in_place().unwrap())(
121                                    dst.field_uninit_at(mem::offset_of!(Self, $idx))
122                                );
123                            }
124                        )+
125
126                        unsafe { dst.assume_init() }
127                    });
128                }
129
130            //     if Characteristic::Clone.all(elem_shapes) {
131            //          builder = builder.clone_into(|src, dst| {
132            //             $({
133            //                 let offset = mem::offset_of!(Self, $idx);
134            //                 unsafe {
135            //                     (<VTableView<$elems>>::of().clone_into().unwrap())(
136            //                         src.field(offset),
137            //                         dst.field_uninit_at(offset),
138            //                     );
139            //                 }
140            //             })+
141
142            //             unsafe { dst.assume_init() }
143            //         });
144            //    }
145
146                if Characteristic::PartialEq.all(elem_shapes) {
147                    builder = builder.eq(|a, b| impl_facet_for_tuple! {
148                        ord on ($($elems.$idx,)+),
149                        eq(a, b),
150                        eq = true
151                    });
152                }
153
154                if Characteristic::PartialOrd.all(elem_shapes) {
155                    builder = builder.partial_ord(|a, b| impl_facet_for_tuple! {
156                        ord on ($($elems.$idx,)+),
157                        partial_ord(a, b),
158                        eq = Some(Ordering::Equal)
159                    });
160                }
161
162                if Characteristic::Ord.all(elem_shapes) {
163                    builder = builder.ord(|a, b| impl_facet_for_tuple! {
164                        ord on ($($elems.$idx,)+),
165                        ord(a, b),
166                        eq = Ordering::Equal
167                    });
168                }
169
170                if Characteristic::Hash.all(elem_shapes) {
171                    builder = builder.hash(|value, hasher_this, hasher_write_fn| {
172                        $(
173                            (<VTableView<$elems>>::of().hash().unwrap())(
174                                &value.$idx,
175                                hasher_this,
176                                hasher_write_fn,
177                            );
178                        )+
179                   });
180                }
181
182                builder.build()
183            };
184
185            const SHAPE: &'static Shape<'static> = &const {
186                Shape::builder_for_sized::<Self>()
187                    .ty(Type::Sequence(SequenceType::Tuple(TupleType {
188                        fields: &const {[
189                            $(field_in_type!(Self, $idx),)+
190                        ]}
191                    })))
192                    .build()
193            };
194        }
195
196        impl_facet_for_tuple! {
197            continue from ($($elems.$idx,)+),
198            remaining ($($remaining.$remainingidx,)*)
199        }
200    };
201    // The entry point into this macro, all smaller tuple types get implemented as well.
202    { ($first:ident.$firstidx:tt $(, $remaining:ident.$remainingidx:tt)* $(,)?) } => {
203        impl_facet_for_tuple! {
204            impl ($first.$firstidx,),
205            remaining ($($remaining.$remainingidx,)*)
206        }
207    };
208}
209
210impl_facet_for_tuple! {
211    (T0.0, T1.1, T2.2, T3.3, T4.4, T5.5, T6.6, T7.7, T8.8, T9.9, T10.10, T11.11)
212}