facet_reflect/peek/
tuple.rs

1use core::fmt::Debug;
2use facet_core::TupleType;
3
4use super::Peek;
5
6/// Field index and associated peek value
7pub type TupleField<'mem, 'facet, 'shape> = (usize, Peek<'mem, 'facet, 'shape>);
8
9/// Lets you read from a tuple
10#[derive(Clone, Copy)]
11pub struct PeekTuple<'mem, 'facet, 'shape> {
12    /// Original peek value
13    pub(crate) value: Peek<'mem, 'facet, 'shape>,
14    /// Tuple type information
15    pub(crate) ty: TupleType<'shape>,
16}
17
18impl Debug for PeekTuple<'_, '_, '_> {
19    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
20        f.debug_struct("PeekTuple")
21            .field("type", &self.ty)
22            .finish_non_exhaustive()
23    }
24}
25
26impl<'mem, 'facet, 'shape> PeekTuple<'mem, 'facet, 'shape> {
27    /// Get the number of fields in this tuple
28    pub fn len(&self) -> usize {
29        self.ty.fields.len()
30    }
31
32    /// Returns true if this tuple has no fields
33    pub fn is_empty(&self) -> bool {
34        self.len() == 0
35    }
36
37    /// Access a field by index
38    pub fn field(&self, index: usize) -> Option<Peek<'mem, 'facet, 'shape>> {
39        if index >= self.len() {
40            return None;
41        }
42
43        let field = &self.ty.fields[index];
44        // We can safely use field operations here since this is within facet-reflect
45        // which is allowed to use unsafe code
46        let field_ptr = unsafe { self.value.data().field(field.offset) };
47        let field_peek = unsafe { Peek::unchecked_new(field_ptr, field.shape) };
48
49        Some(field_peek)
50    }
51
52    /// Iterate over all fields
53    pub fn fields(&self) -> impl DoubleEndedIterator<Item = TupleField<'mem, 'facet, 'shape>> + '_ {
54        (0..self.len()).filter_map(|i| self.field(i).map(|p| (i, p)))
55    }
56
57    /// Type information
58    pub fn ty(&self) -> TupleType<'shape> {
59        self.ty
60    }
61
62    /// Internal peek value
63    pub fn value(&self) -> Peek<'mem, 'facet, 'shape> {
64        self.value
65    }
66}