facet_reflect/peek/
tuple.rs

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