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
//! Support for poking (mutating) DynamicValue types like `facet_value::Value`
use core::mem::ManuallyDrop;
use facet_core::{DynValueKind, DynamicValueDef, Facet, PtrMut, PtrUninit};
use crate::{HeapValue, ReflectError, ReflectErrorKind};
use super::Poke;
/// Lets you mutate a dynamic value (implements mutable operations for DynamicValue types).
///
/// This is used for types like `facet_value::Value` that can hold any of:
/// null, bool, number, string, bytes, array, or object - determined at runtime.
///
/// The setter methods (`set_null`, `set_bool`, etc.) drop the previous value and
/// re-initialize the storage with the new kind.
pub struct PokeDynamicValue<'mem, 'facet> {
pub(crate) value: Poke<'mem, 'facet>,
pub(crate) def: DynamicValueDef,
}
impl<'mem, 'facet> core::fmt::Debug for PokeDynamicValue<'mem, 'facet> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PokeDynamicValue")
.field("kind", &self.kind())
.finish_non_exhaustive()
}
}
impl<'mem, 'facet> PokeDynamicValue<'mem, 'facet> {
/// Creates a new poke dynamic value.
///
/// # Safety
///
/// The caller must ensure that `def` contains valid vtable function pointers that
/// correctly implement the dynamic-value operations for the actual type.
#[inline]
pub const unsafe fn new(value: Poke<'mem, 'facet>, def: DynamicValueDef) -> Self {
Self { value, def }
}
/// Returns the dynamic value definition.
#[inline(always)]
pub const fn def(&self) -> DynamicValueDef {
self.def
}
/// Returns the underlying `Poke` as a read-only `Peek`.
#[inline]
pub fn as_peek(&self) -> crate::Peek<'_, 'facet> {
self.value.as_peek()
}
/// Returns the kind of value stored.
#[inline]
pub fn kind(&self) -> DynValueKind {
unsafe { (self.def.vtable.get_kind)(self.value.data()) }
}
/// Returns true if the value is null.
#[inline]
pub fn is_null(&self) -> bool {
self.kind() == DynValueKind::Null
}
/// Returns the boolean value if this is a bool, `None` otherwise.
#[inline]
pub fn as_bool(&self) -> Option<bool> {
unsafe { (self.def.vtable.get_bool)(self.value.data()) }
}
/// Returns the i64 value if representable, `None` otherwise.
#[inline]
pub fn as_i64(&self) -> Option<i64> {
unsafe { (self.def.vtable.get_i64)(self.value.data()) }
}
/// Returns the u64 value if representable, `None` otherwise.
#[inline]
pub fn as_u64(&self) -> Option<u64> {
unsafe { (self.def.vtable.get_u64)(self.value.data()) }
}
/// Returns the f64 value if this is a number, `None` otherwise.
#[inline]
pub fn as_f64(&self) -> Option<f64> {
unsafe { (self.def.vtable.get_f64)(self.value.data()) }
}
/// Returns the string value if this is a string, `None` otherwise.
#[inline]
pub fn as_str(&self) -> Option<&str> {
unsafe { (self.def.vtable.get_str)(self.value.data()) }
}
/// Returns the bytes value if this is bytes, `None` otherwise.
#[inline]
pub fn as_bytes(&self) -> Option<&[u8]> {
self.def
.vtable
.get_bytes
.and_then(|f| unsafe { f(self.value.data()) })
}
/// Returns the length of the array if this is an array, `None` otherwise.
#[inline]
pub fn array_len(&self) -> Option<usize> {
unsafe { (self.def.vtable.array_len)(self.value.data()) }
}
/// Returns the length of the object if this is an object, `None` otherwise.
#[inline]
pub fn object_len(&self) -> Option<usize> {
unsafe { (self.def.vtable.object_len)(self.value.data()) }
}
/// Helper: drop the existing value and return a `PtrUninit` to the same location.
#[inline]
unsafe fn drop_and_as_uninit(&mut self) -> PtrUninit {
unsafe { self.value.shape.call_drop_in_place(self.value.data_mut()) };
PtrUninit::new(self.value.data_mut().as_mut_byte_ptr())
}
/// Replace the value with `null`, dropping the previous contents.
pub fn set_null(&mut self) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_null)(uninit);
}
}
/// Replace the value with a boolean, dropping the previous contents.
pub fn set_bool(&mut self, v: bool) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_bool)(uninit, v);
}
}
/// Replace the value with an i64, dropping the previous contents.
pub fn set_i64(&mut self, v: i64) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_i64)(uninit, v);
}
}
/// Replace the value with a u64, dropping the previous contents.
pub fn set_u64(&mut self, v: u64) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_u64)(uninit, v);
}
}
/// Replace the value with an f64, dropping the previous contents.
///
/// Returns `false` if the value is not representable by the underlying type.
pub fn set_f64(&mut self, v: f64) -> bool {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_f64)(uninit, v)
}
}
/// Replace the value with a string, dropping the previous contents.
pub fn set_str(&mut self, v: &str) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.set_str)(uninit, v);
}
}
/// Replace the value with a byte slice, dropping the previous contents.
///
/// Returns `false` if the underlying dynamic value type doesn't support bytes.
pub fn set_bytes(&mut self, v: &[u8]) -> bool {
let Some(set_bytes) = self.def.vtable.set_bytes else {
return false;
};
unsafe {
let uninit = self.drop_and_as_uninit();
set_bytes(uninit, v);
}
true
}
/// Replace the value with an empty array, dropping the previous contents.
pub fn set_array(&mut self) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.begin_array)(uninit);
}
}
/// Replace the value with an empty object, dropping the previous contents.
pub fn set_object(&mut self) {
unsafe {
let uninit = self.drop_and_as_uninit();
(self.def.vtable.begin_object)(uninit);
}
}
/// Push an element onto the array value.
///
/// The value must already be an array (use [`set_array`](Self::set_array) first if needed).
/// The element's shape must match this dynamic value's shape — a nested element is itself
/// a full dynamic value of the same kind (e.g. another `facet_value::Value`).
///
/// The element is moved into the array (the vtable does the `ptr::read`); the caller's
/// original ownership of `element` is consumed by this call.
pub fn push_array_element<T: Facet<'facet>>(&mut self, element: T) -> Result<(), ReflectError> {
if self.value.shape != T::SHAPE {
return Err(self.value.err(ReflectErrorKind::WrongShape {
expected: self.value.shape,
actual: T::SHAPE,
}));
}
let mut element = ManuallyDrop::new(element);
unsafe {
let elem_ptr = PtrMut::new(&mut element as *mut ManuallyDrop<T> as *mut u8);
(self.def.vtable.push_array_element)(self.value.data_mut(), elem_ptr);
}
Ok(())
}
/// Type-erased [`push_array_element`](Self::push_array_element).
///
/// Accepts a [`HeapValue`] whose shape must match this dynamic value's shape.
pub fn push_array_element_from_heap<const BORROW: bool>(
&mut self,
element: HeapValue<'facet, BORROW>,
) -> Result<(), ReflectError> {
if self.value.shape != element.shape() {
return Err(self.value.err(ReflectErrorKind::WrongShape {
expected: self.value.shape,
actual: element.shape(),
}));
}
let mut element = element;
let guard = element
.guard
.take()
.expect("HeapValue guard was already taken");
unsafe {
let elem_ptr = PtrMut::new(guard.ptr.as_ptr());
(self.def.vtable.push_array_element)(self.value.data_mut(), elem_ptr);
}
drop(guard);
Ok(())
}
/// Finalize an array value. No-op if the underlying dynamic-value type doesn't need it.
pub fn end_array(&mut self) {
if let Some(end_array) = self.def.vtable.end_array {
unsafe { end_array(self.value.data_mut()) };
}
}
/// Insert a key-value pair into the object value.
///
/// The value must already be an object (use [`set_object`](Self::set_object) first if needed).
/// The value's shape must match this dynamic value's shape — a nested value is itself a full
/// dynamic value of the same kind.
///
/// `value` is moved into the object (the vtable does the `ptr::read`).
pub fn insert_object_entry<T: Facet<'facet>>(
&mut self,
key: &str,
value: T,
) -> Result<(), ReflectError> {
if self.value.shape != T::SHAPE {
return Err(self.value.err(ReflectErrorKind::WrongShape {
expected: self.value.shape,
actual: T::SHAPE,
}));
}
let mut value = ManuallyDrop::new(value);
unsafe {
let value_ptr = PtrMut::new(&mut value as *mut ManuallyDrop<T> as *mut u8);
(self.def.vtable.insert_object_entry)(self.value.data_mut(), key, value_ptr);
}
Ok(())
}
/// Type-erased [`insert_object_entry`](Self::insert_object_entry).
///
/// Accepts a [`HeapValue`] whose shape must match this dynamic value's shape.
pub fn insert_object_entry_from_heap<const BORROW: bool>(
&mut self,
key: &str,
value: HeapValue<'facet, BORROW>,
) -> Result<(), ReflectError> {
if self.value.shape != value.shape() {
return Err(self.value.err(ReflectErrorKind::WrongShape {
expected: self.value.shape,
actual: value.shape(),
}));
}
let mut value = value;
let guard = value
.guard
.take()
.expect("HeapValue guard was already taken");
unsafe {
let value_ptr = PtrMut::new(guard.ptr.as_ptr());
(self.def.vtable.insert_object_entry)(self.value.data_mut(), key, value_ptr);
}
drop(guard);
Ok(())
}
/// Finalize an object value. No-op if the underlying dynamic-value type doesn't need it.
pub fn end_object(&mut self) {
if let Some(end_object) = self.def.vtable.end_object {
unsafe { end_object(self.value.data_mut()) };
}
}
/// Get a mutable `Poke` for the value at the given object key.
///
/// Returns `None` if the dynamic value is not an object, the key is missing, or
/// `object_get_mut` is not implemented for this type.
#[inline]
pub fn object_get_mut(&mut self, key: &str) -> Option<Poke<'_, 'facet>> {
let object_get_mut = self.def.vtable.object_get_mut?;
let inner_ptr = unsafe { object_get_mut(self.value.data_mut(), key)? };
// Nested dynamic values share the outer shape.
Some(unsafe { Poke::from_raw_parts(inner_ptr, self.value.shape) })
}
/// Converts this `PokeDynamicValue` back into a `Poke`.
#[inline]
pub const fn into_inner(self) -> Poke<'mem, 'facet> {
self.value
}
/// Returns a read-only `PeekDynamicValue` view.
#[inline]
pub fn as_peek_dynamic_value(&self) -> crate::PeekDynamicValue<'_, 'facet> {
crate::PeekDynamicValue {
value: self.value.as_peek(),
def: self.def,
}
}
}