facet-reflect 0.46.0

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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use core::{fmt::Debug, marker::PhantomData, mem::ManuallyDrop, ptr::NonNull};
use facet_core::{FieldError, PtrMut, PtrUninit, Shape, ShapeLayout};

use crate::{Guard, HeapValue, ReflectError, ReflectErrorKind, peek::ListLikeDef};

use super::Poke;

/// Lets you mutate a list, array or slice.
pub struct PokeListLike<'mem, 'facet> {
    value: Poke<'mem, 'facet>,
    def: ListLikeDef,
    len: usize,
}

impl<'mem, 'facet> Debug for PokeListLike<'mem, 'facet> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PokeListLike").finish_non_exhaustive()
    }
}

/// Iterator over a `PokeListLike` yielding mutable `Poke`s.
///
/// Constructed by [`PokeListLike::iter_mut`]. Only contiguous list-likes support
/// mutable iteration — this iterator walks element strides starting from
/// `as_mut_ptr`. See [`PokeListLike::iter_mut`] for the error conditions.
pub struct PokeListLikeIter<'mem, 'facet> {
    data: PtrMut,
    stride: usize,
    index: usize,
    len: usize,
    elem_shape: &'static Shape,
    _list: PhantomData<Poke<'mem, 'facet>>,
}

impl<'mem, 'facet> Iterator for PokeListLikeIter<'mem, 'facet> {
    type Item = Poke<'mem, 'facet>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.len {
            return None;
        }
        let item_ptr = unsafe { self.data.field(self.stride * self.index) };
        self.index += 1;
        Some(unsafe { Poke::from_raw_parts(item_ptr, self.elem_shape) })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.len.saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl<'mem, 'facet> ExactSizeIterator for PokeListLikeIter<'mem, 'facet> {}

impl<'mem, 'facet> PokeListLike<'mem, 'facet> {
    /// Creates a new poke list-like
    ///
    /// # Safety
    ///
    /// The caller must ensure that `def` contains valid vtable function pointers that:
    /// - Correctly implement the list-like operations for the actual type
    /// - Do not cause undefined behavior when called
    /// - Return pointers within valid memory bounds
    /// - Match the element type specified in `def.t()`
    #[inline]
    pub unsafe fn new(value: Poke<'mem, 'facet>, def: ListLikeDef) -> Self {
        let len = match def {
            ListLikeDef::List(v) => unsafe { (v.vtable.len)(value.data()) },
            ListLikeDef::Slice(_) => {
                let slice_as_units = unsafe { value.data().get::<[()]>() };
                slice_as_units.len()
            }
            ListLikeDef::Array(v) => v.n,
        };
        Self { value, def, len }
    }

    fn err(&self, kind: ReflectErrorKind) -> ReflectError {
        self.value.err(kind)
    }

    /// Get the length of the list-like.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the list-like is empty.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Def getter.
    #[inline]
    pub const fn def(&self) -> ListLikeDef {
        self.def
    }

    /// Get a read-only `Peek` for the item at the specified index.
    #[inline]
    pub fn get(&self, index: usize) -> Option<crate::Peek<'_, 'facet>> {
        self.as_peek_list_like().get(index)
    }

    /// Get a mutable `Poke` for the item at the specified index.
    pub fn get_mut(&mut self, index: usize) -> Option<Poke<'_, 'facet>> {
        if index >= self.len {
            return None;
        }

        let item_ptr = match self.def {
            ListLikeDef::List(def) => {
                let get_mut_fn = def.vtable.get_mut?;
                unsafe { get_mut_fn(self.value.data_mut(), index, self.value.shape())? }
            }
            ListLikeDef::Array(def) => {
                let elem_layout = match self.def.t().layout {
                    ShapeLayout::Sized(layout) => layout,
                    ShapeLayout::Unsized => return None,
                };
                let base = unsafe { (def.vtable.as_mut_ptr)(self.value.data_mut()) };
                unsafe { base.field(index * elem_layout.size()) }
            }
            ListLikeDef::Slice(def) => {
                let elem_layout = match self.def.t().layout {
                    ShapeLayout::Sized(layout) => layout,
                    ShapeLayout::Unsized => return None,
                };
                let base = unsafe { (def.vtable.as_mut_ptr)(self.value.data_mut()) };
                unsafe { base.field(index * elem_layout.size()) }
            }
        };

        Some(unsafe { Poke::from_raw_parts(item_ptr, self.def.t()) })
    }

    /// Returns a mutable iterator over the list-like.
    ///
    /// Requires contiguous mutable access to the backing storage: the element type must be
    /// sized, and for `List` the vtable must expose `as_mut_ptr`. (`Array` and `Slice` always
    /// expose `as_mut_ptr`.) Returns [`ReflectErrorKind::OperationFailed`] if either condition
    /// fails; use [`PokeListLike::get_mut`] per index when `iter_mut` is unavailable.
    ///
    /// The previous fallback that synthesized a mutable iterator from the list's `iter_vtable`
    /// was unsound: that vtable yields `PtrConst` items backed by shared references, and
    /// writing through them is UB.
    pub fn iter_mut(self) -> Result<PokeListLikeIter<'mem, 'facet>, ReflectError> {
        let elem_shape = self.def.t();
        let stride = match elem_shape.layout {
            ShapeLayout::Sized(layout) => layout.size(),
            ShapeLayout::Unsized => {
                return Err(self.err(ReflectErrorKind::OperationFailed {
                    shape: self.value.shape,
                    operation: "iter_mut requires sized element type",
                }));
            }
        };

        let data = match self.def {
            ListLikeDef::List(def) => match def.vtable.as_mut_ptr {
                Some(as_mut_ptr_fn) => unsafe { as_mut_ptr_fn(self.value.data) },
                None => {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape: self.value.shape,
                        operation:
                            "iter_mut requires a contiguous `as_mut_ptr` vtable entry; use `get_mut` per index",
                    }));
                }
            },
            ListLikeDef::Array(def) => unsafe { (def.vtable.as_mut_ptr)(self.value.data) },
            ListLikeDef::Slice(def) => unsafe { (def.vtable.as_mut_ptr)(self.value.data) },
        };

        Ok(PokeListLikeIter {
            data,
            stride,
            index: 0,
            len: self.len,
            elem_shape,
            _list: PhantomData,
        })
    }

    /// Push a value onto the end of the list.
    ///
    /// Only supported for `List` variants whose element type provides a `push`
    /// operation (e.g. `Vec<T>`). Fails for arrays and slices as their length
    /// is fixed.
    pub fn push<T: facet_core::Facet<'facet>>(&mut self, value: T) -> Result<(), ReflectError> {
        if self.def.t() != T::SHAPE {
            return Err(self.err(ReflectErrorKind::WrongShape {
                expected: self.def.t(),
                actual: T::SHAPE,
            }));
        }
        let push_fn = self.push_fn()?;
        let mut value = ManuallyDrop::new(value);
        unsafe {
            let item_ptr = PtrMut::new(&mut value as *mut ManuallyDrop<T> as *mut u8);
            push_fn(self.value.data_mut(), item_ptr);
        }
        self.len += 1;
        Ok(())
    }

    /// Type-erased [`push`](Self::push).
    ///
    /// Accepts a [`HeapValue`] whose shape must match the list's element type.
    /// The value is moved out of the `HeapValue` into the list.
    pub fn push_from_heap<const BORROW: bool>(
        &mut self,
        value: HeapValue<'facet, BORROW>,
    ) -> Result<(), ReflectError> {
        if self.def.t() != value.shape() {
            return Err(self.err(ReflectErrorKind::WrongShape {
                expected: self.def.t(),
                actual: value.shape(),
            }));
        }
        let push_fn = self.push_fn()?;
        let mut value = value;
        let guard = value
            .guard
            .take()
            .expect("HeapValue guard was already taken");
        unsafe {
            let item_ptr = PtrMut::new(guard.ptr.as_ptr());
            push_fn(self.value.data_mut(), item_ptr);
        }
        drop(guard);
        self.len += 1;
        Ok(())
    }

    /// Pop the last value off the end of the list.
    ///
    /// Returns `Ok(None)` if the list is empty. Only supported for `List`
    /// variants whose element type provides a `pop` operation.
    pub fn pop(&mut self) -> Result<Option<HeapValue<'facet, true>>, ReflectError> {
        let list_def = match self.def {
            ListLikeDef::List(def) => def,
            _ => {
                return Err(self.err(ReflectErrorKind::OperationFailed {
                    shape: self.value.shape(),
                    operation: "pop: only list-backed list-likes support pop",
                }));
            }
        };
        let pop_fn = list_def.pop().ok_or_else(|| {
            self.err(ReflectErrorKind::OperationFailed {
                shape: self.value.shape(),
                operation: "pop: list type does not support pop",
            })
        })?;
        let elem_shape = self.def.t();
        let layout = elem_shape.layout.sized_layout().map_err(|_| {
            self.err(ReflectErrorKind::Unsized {
                shape: elem_shape,
                operation: "pop",
            })
        })?;
        let ptr = if layout.size() == 0 {
            NonNull::<u8>::dangling()
        } else {
            let raw = unsafe { alloc::alloc::alloc(layout) };
            match NonNull::new(raw) {
                Some(p) => p,
                None => alloc::alloc::handle_alloc_error(layout),
            }
        };
        let out = PtrUninit::new(ptr.as_ptr());
        let popped = unsafe { pop_fn(self.value.data_mut(), out) };
        if !popped {
            if layout.size() != 0 {
                unsafe { alloc::alloc::dealloc(ptr.as_ptr(), layout) };
            }
            return Ok(None);
        }
        self.len -= 1;
        Ok(Some(HeapValue {
            guard: Some(Guard {
                ptr,
                layout,
                should_dealloc: layout.size() != 0,
            }),
            shape: elem_shape,
            phantom: PhantomData,
        }))
    }

    /// Swap the elements at indices `a` and `b`.
    ///
    /// For `List` variants, uses the list's `swap` vtable entry if present and
    /// errors otherwise. For `Array` and `Slice` variants, performs a generic
    /// byte-swap using the element stride (always available). Returns an error
    /// if either index is out of bounds. Swapping an index with itself is a
    /// no-op.
    pub fn swap(&mut self, a: usize, b: usize) -> Result<(), ReflectError> {
        let len = self.len;
        if a >= len || b >= len {
            let out_of_bounds = if a >= len { a } else { b };
            return Err(self.err(ReflectErrorKind::FieldError {
                shape: self.value.shape(),
                field_error: FieldError::IndexOutOfBounds {
                    index: out_of_bounds,
                    bound: len,
                },
            }));
        }
        if a == b {
            return Ok(());
        }

        match self.def {
            ListLikeDef::List(def) => {
                let swap_fn = def.vtable.swap.ok_or_else(|| {
                    self.err(ReflectErrorKind::OperationFailed {
                        shape: self.value.shape(),
                        operation: "swap: list type does not support swap",
                    })
                })?;
                let ok = unsafe { swap_fn(self.value.data_mut(), a, b, self.value.shape()) };
                if !ok {
                    return Err(self.err(ReflectErrorKind::OperationFailed {
                        shape: self.value.shape(),
                        operation: "swap: vtable refused the operation",
                    }));
                }
                Ok(())
            }
            ListLikeDef::Array(def) => {
                let elem_size = match self.def.t().layout {
                    ShapeLayout::Sized(l) => l.size(),
                    ShapeLayout::Unsized => {
                        return Err(self.err(ReflectErrorKind::Unsized {
                            shape: self.def.t(),
                            operation: "swap",
                        }));
                    }
                };
                unsafe {
                    let base = (def.vtable.as_mut_ptr)(self.value.data_mut());
                    let pa = base.field(a * elem_size);
                    let pb = base.field(b * elem_size);
                    core::ptr::swap_nonoverlapping(
                        pa.as_mut_byte_ptr(),
                        pb.as_mut_byte_ptr(),
                        elem_size,
                    );
                }
                Ok(())
            }
            ListLikeDef::Slice(def) => {
                let elem_size = match self.def.t().layout {
                    ShapeLayout::Sized(l) => l.size(),
                    ShapeLayout::Unsized => {
                        return Err(self.err(ReflectErrorKind::Unsized {
                            shape: self.def.t(),
                            operation: "swap",
                        }));
                    }
                };
                unsafe {
                    let base = (def.vtable.as_mut_ptr)(self.value.data_mut());
                    let pa = base.field(a * elem_size);
                    let pb = base.field(b * elem_size);
                    core::ptr::swap_nonoverlapping(
                        pa.as_mut_byte_ptr(),
                        pb.as_mut_byte_ptr(),
                        elem_size,
                    );
                }
                Ok(())
            }
        }
    }

    /// Resolve the per-T push function for the underlying list, or build an
    /// error if the list-like is an array/slice or the list lacks push.
    #[inline]
    fn push_fn(&self) -> Result<facet_core::ListPushFn, ReflectError> {
        match self.def {
            ListLikeDef::List(def) => def.push().ok_or_else(|| {
                self.err(ReflectErrorKind::OperationFailed {
                    shape: self.value.shape(),
                    operation: "push: list type does not support push",
                })
            }),
            _ => Err(self.err(ReflectErrorKind::OperationFailed {
                shape: self.value.shape(),
                operation: "push: only list-backed list-likes support push",
            })),
        }
    }

    /// Converts this `PokeListLike` back into a `Poke`.
    #[inline]
    pub fn into_inner(self) -> Poke<'mem, 'facet> {
        self.value
    }

    /// Returns a read-only `PeekListLike` view.
    #[inline]
    pub fn as_peek_list_like(&self) -> crate::PeekListLike<'_, 'facet> {
        unsafe { crate::PeekListLike::new(self.value.as_peek(), self.def) }
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;

    use super::*;

    #[test]
    fn poke_list_like_vec_len_and_get_mut() {
        let mut v: Vec<i32> = alloc::vec![1, 2, 3];
        let poke = Poke::new(&mut v);
        let mut ll = poke.into_list_like().unwrap();
        assert_eq!(ll.len(), 3);

        {
            let mut item = ll.get_mut(1).unwrap();
            item.set(200i32).unwrap();
        }
        assert_eq!(v, alloc::vec![1, 200, 3]);
    }

    #[test]
    fn poke_list_like_array_get_mut() {
        let mut arr: [i32; 3] = [10, 20, 30];
        let poke = Poke::new(&mut arr);
        let mut ll = poke.into_list_like().unwrap();
        assert_eq!(ll.len(), 3);

        {
            let mut item = ll.get_mut(0).unwrap();
            item.set(99i32).unwrap();
        }
        assert_eq!(arr, [99, 20, 30]);
    }

    #[test]
    fn poke_list_like_iter_mut() {
        let mut v: Vec<i32> = alloc::vec![1, 2, 3];
        let poke = Poke::new(&mut v);
        let ll = poke.into_list_like().unwrap();
        for mut item in ll.iter_mut().unwrap() {
            let cur = *item.get::<i32>().unwrap();
            item.set(cur * 10).unwrap();
        }
        assert_eq!(v, alloc::vec![10, 20, 30]);
    }

    #[test]
    fn poke_list_like_vec_push_pop() {
        let mut v: Vec<i32> = alloc::vec![];
        {
            let poke = Poke::new(&mut v);
            let mut ll = poke.into_list_like().unwrap();
            ll.push(10i32).unwrap();
            ll.push(20i32).unwrap();
            assert_eq!(ll.len(), 2);
            let popped = ll.pop().unwrap().unwrap();
            assert_eq!(popped.materialize::<i32>().unwrap(), 20);
            assert_eq!(ll.len(), 1);
        }
        assert_eq!(v, alloc::vec![10]);
    }

    #[test]
    fn poke_list_like_array_push_fails() {
        let mut arr: [i32; 3] = [1, 2, 3];
        let poke = Poke::new(&mut arr);
        let mut ll = poke.into_list_like().unwrap();
        let res = ll.push(4i32);
        assert!(matches!(
            res,
            Err(ref err) if matches!(err.kind, ReflectErrorKind::OperationFailed { .. })
        ));
    }

    #[test]
    fn poke_list_like_array_pop_fails() {
        let mut arr: [i32; 3] = [1, 2, 3];
        let poke = Poke::new(&mut arr);
        let mut ll = poke.into_list_like().unwrap();
        let res = ll.pop();
        assert!(matches!(
            res,
            Err(ref err) if matches!(err.kind, ReflectErrorKind::OperationFailed { .. })
        ));
    }

    #[test]
    fn poke_list_like_vec_swap() {
        let mut v: Vec<i32> = alloc::vec![1, 2, 3];
        let poke = Poke::new(&mut v);
        let mut ll = poke.into_list_like().unwrap();
        ll.swap(0, 2).unwrap();
        assert_eq!(v, alloc::vec![3, 2, 1]);
    }

    #[test]
    fn poke_list_like_array_swap() {
        let mut arr: [i32; 3] = [10, 20, 30];
        let poke = Poke::new(&mut arr);
        let mut ll = poke.into_list_like().unwrap();
        ll.swap(0, 2).unwrap();
        assert_eq!(arr, [30, 20, 10]);
    }

    #[test]
    fn poke_list_like_swap_out_of_bounds_fails() {
        let mut v: Vec<i32> = alloc::vec![1, 2, 3];
        let poke = Poke::new(&mut v);
        let mut ll = poke.into_list_like().unwrap();
        let res = ll.swap(5, 0);
        assert!(matches!(
            res,
            Err(ref err) if matches!(err.kind, ReflectErrorKind::FieldError { .. })
        ));
    }
}