facet-reflect 0.44.4

Build and manipulate values of arbitrary Facet types at runtime while respecting invariants - safe runtime reflection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use super::*;
use facet_core::{Def, DynDateTimeKind, KnownPointer, NumericType, PrimitiveType, Type};

////////////////////////////////////////////////////////////////////////////////////////////////////
// `Set` and set helpers
////////////////////////////////////////////////////////////////////////////////////////////////////
impl<'facet, const BORROW: bool> Partial<'facet, BORROW> {
    /// Set a shared slice reference (`&[T]`) to an empty slice without knowing `T` at compile time.
    ///
    /// This writes a valid wide reference with len=0 and a suitably aligned dangling data pointer.
    pub fn set_empty_shared_slice(mut self) -> Result<Self, ReflectError> {
        let shape = self.frames().last().unwrap().allocated.shape();
        let align = match shape.def {
            Def::Pointer(ptr_def)
                if matches!(ptr_def.known, Some(KnownPointer::SharedReference)) =>
            {
                let Some(pointee) = ptr_def.pointee() else {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape,
                        operation: "shared reference pointer missing pointee shape",
                    }));
                };
                let Def::Slice(slice_def) = pointee.def else {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape,
                        operation: "set_empty_shared_slice requires a slice pointee",
                    }));
                };
                slice_def
                    .t
                    .layout
                    .sized_layout()
                    .map_or(1, |l| l.align().max(1))
            }
            _ => {
                return Err(self.err(ReflectErrorKind::OperationFailed {
                    shape,
                    operation: "set_empty_shared_slice requires a shared slice reference",
                }));
            }
        };

        let fr = self.frames_mut().last_mut().unwrap();
        fr.deinit_for_replace();

        // For len=0, any non-null aligned pointer is valid.
        let data_ptr = align as *const u8 as usize;
        unsafe {
            let dst = fr.data.as_mut_byte_ptr() as *mut [usize; 2];
            core::ptr::write(dst, [data_ptr, 0]);
            fr.mark_as_init();
        }

        Ok(self)
    }

    /// Sets a value wholesale into the current frame.
    ///
    /// If the current frame was already initialized, the previous value is
    /// dropped. If it was partially initialized, the fields that were initialized
    /// are dropped, etc.
    pub fn set<U>(mut self, value: U) -> Result<Self, ReflectError>
    where
        U: Facet<'facet>,
    {
        struct DropVal<U> {
            ptr: *mut U,
        }
        impl<U> Drop for DropVal<U> {
            #[inline]
            fn drop(&mut self) {
                unsafe { core::ptr::drop_in_place(self.ptr) };
            }
        }

        let mut value = ManuallyDrop::new(value);
        let drop = DropVal {
            ptr: (&mut value) as *mut ManuallyDrop<U> as *mut U,
        };

        let ptr_const = PtrConst::new(drop.ptr);
        // Safety: We are calling set_shape with a valid shape and a valid pointer
        self = unsafe { self.set_shape(ptr_const, U::SHAPE)? };
        core::mem::forget(drop);

        Ok(self)
    }

    /// Sets a value into the current frame by [PtrConst] / [Shape].
    ///
    /// # Safety
    ///
    /// The caller must ensure that `src_value` points to a valid instance of a value
    /// whose memory layout and type matches `src_shape`, and that this value can be
    /// safely copied (bitwise) into the destination specified by the Partial's current frame.
    ///
    /// After a successful call, the ownership of the value at `src_value` is effectively moved
    /// into the Partial (i.e., the destination), and the original value should not be used
    /// or dropped by the caller; you should use `core::mem::forget` on the passed value.
    ///
    /// If an error is returned, the destination remains unmodified and safe for future operations.
    #[inline]
    pub unsafe fn set_shape(
        mut self,
        src_value: PtrConst,
        src_shape: &'static Shape,
    ) -> Result<Self, ReflectError> {
        // Get shape upfront to avoid borrow conflicts
        let shape = self.frames().last().unwrap().allocated.shape();
        let fr = self.frames_mut().last_mut().unwrap();
        crate::trace!("set_shape({src_shape:?})");

        // Check if target is a DynamicValue - if so, convert the source value
        if let Def::DynamicValue(dyn_def) = &shape.def {
            return unsafe { self.set_into_dynamic_value(src_value, src_shape, dyn_def) };
        }

        if !shape.is_shape(src_shape) {
            return Err(self.err(ReflectErrorKind::WrongShape {
                expected: shape,
                actual: src_shape,
            }));
        }

        fr.deinit_for_replace();

        // SAFETY: `fr.allocated.shape()` and `src_shape` are the same, so they have the same size,
        // and the preconditions for this function are that `src_value` is fully intialized.
        unsafe {
            // unwrap safety: the only failure condition for copy_from is that shape is unsized,
            // which is not possible for `Partial`
            fr.data.copy_from(src_value, fr.allocated.shape()).unwrap();
        }

        // SAFETY: if we reached this point, `fr.data` is correctly initialized
        unsafe {
            fr.mark_as_init();
        }

        Ok(self)
    }

    /// Sets a value into a DynamicValue target by converting the source value.
    ///
    /// # Safety
    ///
    /// Same safety requirements as `set_shape`.
    unsafe fn set_into_dynamic_value(
        mut self,
        src_value: PtrConst,
        src_shape: &'static Shape,
        dyn_def: &facet_core::DynamicValueDef,
    ) -> Result<Self, ReflectError> {
        let fr = self.frames_mut().last_mut().unwrap();
        let vtable = dyn_def.vtable;

        // Use deinit_for_replace which handles BorrowedInPlace and Field frames correctly
        fr.deinit_for_replace();

        // If source shape is also the same DynamicValue shape, just copy it
        if fr.allocated.shape().is_shape(src_shape) {
            unsafe {
                fr.data.copy_from(src_value, fr.allocated.shape()).unwrap();
                fr.mark_as_init();
            }
            return Ok(self);
        }

        // Get the size in bits for numeric conversions
        let size_bits = src_shape
            .layout
            .sized_layout()
            .map(|l| l.size() * 8)
            .unwrap_or(0);

        // Convert based on source shape's type
        match &src_shape.ty {
            Type::Primitive(PrimitiveType::Boolean) => {
                let val = unsafe { *(src_value.as_byte_ptr() as *const bool) };
                unsafe { (vtable.set_bool)(fr.data, val) };
            }
            Type::Primitive(PrimitiveType::Numeric(NumericType::Float)) => {
                if size_bits == 64 {
                    let val = unsafe { *(src_value.as_byte_ptr() as *const f64) };
                    let success = unsafe { (vtable.set_f64)(fr.data, val) };
                    if !success {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: src_shape,
                            operation: "f64 value (NaN/Infinity) not representable in dynamic value",
                        }));
                    }
                } else if size_bits == 32 {
                    let val = unsafe { *(src_value.as_byte_ptr() as *const f32) } as f64;
                    let success = unsafe { (vtable.set_f64)(fr.data, val) };
                    if !success {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: src_shape,
                            operation: "f32 value (NaN/Infinity) not representable in dynamic value",
                        }));
                    }
                } else {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape: src_shape,
                        operation: "unsupported float size for dynamic value",
                    }));
                }
            }
            Type::Primitive(PrimitiveType::Numeric(NumericType::Integer { signed: true })) => {
                let val: i64 = match size_bits {
                    8 => (unsafe { *(src_value.as_byte_ptr() as *const i8) }) as i64,
                    16 => (unsafe { *(src_value.as_byte_ptr() as *const i16) }) as i64,
                    32 => (unsafe { *(src_value.as_byte_ptr() as *const i32) }) as i64,
                    64 => unsafe { *(src_value.as_byte_ptr() as *const i64) },
                    _ => {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: src_shape,
                            operation: "unsupported signed integer size for dynamic value",
                        }));
                    }
                };
                unsafe { (vtable.set_i64)(fr.data, val) };
            }
            Type::Primitive(PrimitiveType::Numeric(NumericType::Integer { signed: false })) => {
                let val: u64 = match size_bits {
                    8 => (unsafe { *src_value.as_byte_ptr() }) as u64,
                    16 => (unsafe { *(src_value.as_byte_ptr() as *const u16) }) as u64,
                    32 => (unsafe { *(src_value.as_byte_ptr() as *const u32) }) as u64,
                    64 => unsafe { *(src_value.as_byte_ptr() as *const u64) },
                    _ => {
                        return Err(self.err(ReflectErrorKind::OperationFailed {
                            shape: src_shape,
                            operation: "unsupported unsigned integer size for dynamic value",
                        }));
                    }
                };
                unsafe { (vtable.set_u64)(fr.data, val) };
            }
            Type::Primitive(PrimitiveType::Textual(_)) => {
                // char or str - for char, convert to string
                if *src_shape == *char::SHAPE {
                    let c = unsafe { *(src_value.as_byte_ptr() as *const char) };
                    let mut buf = [0u8; 4];
                    let s = c.encode_utf8(&mut buf);
                    unsafe { (vtable.set_str)(fr.data, s) };
                } else {
                    // &str
                    let s: &str = unsafe { *(src_value.as_byte_ptr() as *const &str) };
                    unsafe { (vtable.set_str)(fr.data, s) };
                }
            }
            _ => {
                if let Some(set_bytes) = vtable.set_bytes
                    && let Def::List(list_def) = &src_shape.def
                    && list_def.t.is_type::<u8>()
                {
                    let bytes: &::alloc::vec::Vec<u8> =
                        unsafe { &*(src_value.as_byte_ptr() as *const ::alloc::vec::Vec<u8>) };
                    unsafe { (set_bytes)(fr.data, bytes.as_slice()) };
                    // Drop the source Vec since we've copied the bytes into the dynamic value.
                    unsafe {
                        src_shape
                            .call_drop_in_place(PtrMut::new(src_value.as_byte_ptr() as *mut u8));
                    }
                    let fr = self.frames_mut().last_mut().unwrap();
                    fr.tracker = Tracker::DynamicValue {
                        state: DynamicValueState::Scalar,
                    };
                    unsafe { fr.mark_as_init() };
                    return Ok(self);
                }

                // Handle String type (not a primitive but common)
                if *src_shape == *::alloc::string::String::SHAPE {
                    let s: &::alloc::string::String =
                        unsafe { &*(src_value.as_byte_ptr() as *const ::alloc::string::String) };
                    unsafe { (vtable.set_str)(fr.data, s.as_str()) };
                    // Drop the source String since we cloned its content
                    unsafe {
                        src_shape
                            .call_drop_in_place(PtrMut::new(src_value.as_byte_ptr() as *mut u8));
                    }
                } else {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape: src_shape,
                        operation: "cannot convert this type to dynamic value",
                    }));
                }
            }
        }

        let fr = self.frames_mut().last_mut().unwrap();
        fr.tracker = Tracker::DynamicValue {
            state: DynamicValueState::Scalar,
        };
        unsafe { fr.mark_as_init() };
        Ok(self)
    }

    /// Sets a datetime value into a DynamicValue target.
    ///
    /// This is used for format-specific datetime types (like TOML datetime).
    /// Returns an error if the target doesn't support datetime values.
    #[allow(clippy::too_many_arguments)]
    pub fn set_datetime(
        mut self,
        year: i32,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        nanos: u32,
        kind: DynDateTimeKind,
    ) -> Result<Self, ReflectError> {
        // Get shape upfront to avoid borrow conflicts
        let shape = self.frames().last().unwrap().allocated.shape();
        let fr = self.frames_mut().last_mut().unwrap();

        // Must be a DynamicValue type
        let dyn_def = match &shape.def {
            Def::DynamicValue(dv) => dv,
            _ => {
                return Err(self.err(ReflectErrorKind::OperationFailed {
                    shape,
                    operation: "set_datetime requires a DynamicValue target",
                }));
            }
        };

        let vtable = dyn_def.vtable;

        // Check if the vtable supports datetime
        let Some(set_datetime_fn) = vtable.set_datetime else {
            return Err(self.err(ReflectErrorKind::OperationFailed {
                shape,
                operation: "dynamic value type does not support datetime",
            }));
        };

        fr.deinit_for_replace();

        // Call the vtable's set_datetime function
        unsafe {
            set_datetime_fn(fr.data, year, month, day, hour, minute, second, nanos, kind);
        }

        let fr = self.frames_mut().last_mut().unwrap();
        fr.tracker = Tracker::DynamicValue {
            state: DynamicValueState::Scalar,
        };
        unsafe { fr.mark_as_init() };
        Ok(self)
    }

    /// Sets the current frame using a function that initializes the value
    ///
    /// # Safety
    ///
    /// If `f` returns Ok(), it is assumed that it initialized the passed pointer fully and with a
    /// value of the right type.
    ///
    /// If `f` returns Err(), it is assumed that it did NOT initialize the passed pointer and that
    /// there is no need to drop it in place.
    pub unsafe fn set_from_function<F>(mut self, f: F) -> Result<Self, ReflectError>
    where
        F: FnOnce(PtrUninit) -> Result<(), ReflectErrorKind>,
    {
        let frame = self.frames_mut().last_mut().unwrap();

        frame.deinit_for_replace();
        if let Err(kind) = f(frame.data) {
            // Only compute path on error (path construction allocates)
            return Err(self.err(kind));
        }

        // safety: `f()` returned Ok, so `frame.data` must be initialized
        unsafe {
            frame.mark_as_init();
        }

        Ok(self)
    }

    /// Sets the current frame to its default value using `default_in_place` from the
    /// vtable.
    ///
    /// Note: if you have `struct S { field: F }`, and `F` does not implement `Default`
    /// but `S` does, this doesn't magically uses S's `Default` implementation to get a value
    /// for `field`.
    ///
    /// If the current frame's shape does not implement `Default`, then this returns an error.
    #[inline]
    pub fn set_default(self) -> Result<Self, ReflectError> {
        let frame = self.frames().last().unwrap();
        let shape = frame.allocated.shape();

        // SAFETY: `call_default_in_place` fully initializes the passed pointer.
        unsafe {
            self.set_from_function(move |ptr| {
                shape
                    .call_default_in_place(ptr)
                    .ok_or(ReflectErrorKind::OperationFailed {
                        shape,
                        operation: "type does not implement Default",
                    })
            })
        }
    }

    /// Copy a value from a Peek into the current frame.
    ///
    /// # Invariants
    ///
    /// `peek` must be a thin pointer, otherwise this panics.
    ///
    /// # Safety
    ///
    /// If this succeeds, the value `Peek` points to has been moved out of, and
    /// as such, should not be dropped (but should be deallocated).
    pub unsafe fn set_from_peek(self, peek: &Peek<'_, '_>) -> Result<Self, ReflectError> {
        // Get the source value's pointer and shape
        let src_ptr = peek.data();
        let src_shape = peek.shape();

        // SAFETY: `Peek` guarantees that src_ptr is initialized and of type src_shape
        unsafe { self.set_shape(src_ptr, src_shape) }
    }

    /// Parses a string value into the current frame using the type's ParseFn from the vtable.
    ///
    /// If the current frame was previously initialized, its contents are dropped in place.
    pub fn parse_from_str(mut self, s: &str) -> Result<Self, ReflectError> {
        let frame = self.frames_mut().last_mut().unwrap();
        let shape = frame.allocated.shape();

        frame.deinit_for_replace();

        // Parse the string value using the type's parse function
        let result = unsafe { shape.call_parse(s, frame.data) };

        match result {
            Some(Ok(())) => {
                // SAFETY: `call_parse` returned `Ok`, so `frame.data` is fully initialized now.
                unsafe {
                    frame.mark_as_init();
                }
                Ok(self)
            }
            Some(Err(_pe)) => {
                // Return a ParseFailed error with the input value for better diagnostics
                Err(self.err(ReflectErrorKind::ParseFailed {
                    shape,
                    input: s.into(),
                }))
            }
            None => Err(self.err(ReflectErrorKind::OperationFailed {
                shape,
                operation: "Type does not support parsing from string",
            })),
        }
    }

    /// Parses a byte slice into the current frame using the type's ParseBytesFn from the vtable.
    ///
    /// This is used for binary formats where types have efficient binary representations
    /// (e.g., UUID as 16 raw bytes instead of a string).
    ///
    /// If the current frame was previously initialized, its contents are dropped in place.
    pub fn parse_from_bytes(mut self, bytes: &[u8]) -> Result<Self, ReflectError> {
        let frame = self.frames_mut().last_mut().unwrap();
        let shape = frame.allocated.shape();

        frame.deinit_for_replace();

        // Parse the bytes using the type's parse_bytes function
        let result = unsafe { shape.call_parse_bytes(bytes, frame.data) };

        match result {
            Some(Ok(())) => {
                // SAFETY: `call_parse_bytes` returned `Ok`, so `frame.data` is fully initialized.
                unsafe {
                    frame.mark_as_init();
                }
                Ok(self)
            }
            Some(Err(_pe)) => {
                // TODO: can we propagate the ParseError somehow?
                Err(self.err(ReflectErrorKind::OperationFailed {
                    shape,
                    operation: "Failed to parse bytes value",
                }))
            }
            None => Err(self.err(ReflectErrorKind::OperationFailed {
                shape,
                operation: "Type does not support parsing from bytes",
            })),
        }
    }
}