• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

facet-rs / facet / 19770000397

28 Nov 2025 05:05PM UTC coverage: 60.41% (+1.0%) from 59.428%
19770000397

push

github

fasterthanlime
Add facet-assert crate for structural assertions without PartialEq

This crate provides `assert_same!` which compares values structurally
via Facet reflection, without requiring PartialEq or Debug.

Key features:
- No PartialEq required - uses Facet reflection
- Structural sameness - different types with same structure are "same"
- Smart diffs showing exactly which field at which path differs
- Opaque types fail with clear error messages

Example:
```rust
#[derive(Facet)]
struct Config { host: String, port: u16 }

let a = Config { host: "localhost".into(), port: 8080 };
let b = Config { host: "localhost".into(), port: 8080 };
assert_same!(a, b);  // No PartialEq needed!
```

185 of 342 new or added lines in 2 files covered. (54.09%)

541 existing lines in 7 files now uncovered.

15311 of 25345 relevant lines covered (60.41%)

160.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.52
/facet-reflect/src/partial/partial_api/misc.rs
1
use super::*;
2

3
////////////////////////////////////////////////////////////////////////////////////////////////////
4
// Misc.
5
////////////////////////////////////////////////////////////////////////////////////////////////////
6
impl<'facet> Partial<'facet> {
7
    /// Returns the current frame count (depth of nesting)
8
    ///
9
    /// The initial frame count is 1 — `begin_field` would push a new frame,
10
    /// bringing it to 2, then `end` would bring it back to `1`.
11
    ///
12
    /// This is an implementation detail of `Partial`, kinda, but deserializers
13
    /// might use this for debug assertions, to make sure the state is what
14
    /// they think it is.
15
    #[inline]
16
    pub fn frame_count(&self) -> usize {
28✔
17
        self.frames().len()
28✔
18
    }
28✔
19

20
    /// Returns the shape of the current frame.
21
    #[inline]
22
    pub fn shape(&self) -> &'static Shape {
13,648✔
23
        self.frames()
13,648✔
24
            .last()
13,648✔
25
            .expect("Partial always has at least one frame")
13,648✔
26
            .shape
13,648✔
27
    }
13,648✔
28

29
    /// Returns the current deferred resolution, if in deferred mode.
30
    #[inline]
31
    pub fn deferred_resolution(&self) -> Option<&Resolution> {
3✔
32
        self.resolution()
3✔
33
    }
3✔
34

35
    /// Returns the current path in deferred mode as a slice (for debugging/tracing).
36
    #[inline]
37
    pub fn current_path_slice(&self) -> Option<&[&'static str]> {
×
38
        self.current_path().map(|p| p.as_slice())
×
39
    }
×
40

41
    /// Enables deferred materialization mode with the given Resolution.
42
    ///
43
    /// When deferred mode is enabled:
44
    /// - `end()` stores frames instead of validating them
45
    /// - Re-entering a path restores the stored frame with its state intact
46
    /// - `finish_deferred()` performs final validation and materialization
47
    ///
48
    /// This allows deserializers to handle interleaved fields (e.g., TOML dotted
49
    /// keys, flattened structs) where nested fields aren't contiguous in the input.
50
    ///
51
    /// # Use Cases
52
    ///
53
    /// - TOML dotted keys: `inner.x = 1` followed by `count = 2` then `inner.y = 3`
54
    /// - Flattened structs where nested fields appear at the parent level
55
    /// - Any format where field order doesn't match struct nesting
56
    ///
57
    /// # Errors
58
    ///
59
    /// Returns an error if already in deferred mode.
60
    #[inline]
61
    pub fn begin_deferred(&mut self, resolution: Resolution) -> Result<&mut Self, ReflectError> {
420✔
62
        // Cannot enable deferred mode if already in deferred mode
63
        if self.is_deferred() {
420✔
64
            return Err(ReflectError::InvariantViolation {
1✔
65
                invariant: "begin_deferred() called but already in deferred mode",
1✔
66
            });
1✔
67
        }
419✔
68

69
        // Take the stack out of Strict mode and wrap in Deferred mode
70
        let FrameMode::Strict { stack } = core::mem::replace(
419✔
71
            &mut self.mode,
419✔
72
            FrameMode::Strict { stack: Vec::new() }, // temporary placeholder
419✔
73
        ) else {
419✔
74
            unreachable!("just checked we're not in deferred mode");
×
75
        };
76

77
        let start_depth = stack.len();
419✔
78
        self.mode = FrameMode::Deferred {
419✔
79
            stack,
419✔
80
            resolution,
419✔
81
            start_depth,
419✔
82
            current_path: Vec::new(),
419✔
83
            stored_frames: BTreeMap::new(),
419✔
84
        };
419✔
85
        Ok(self)
419✔
86
    }
420✔
87

88
    /// Finishes deferred mode: validates all stored frames and finalizes.
89
    ///
90
    /// This method:
91
    /// 1. Validates that all stored frames are fully initialized
92
    /// 2. Processes frames from deepest to shallowest, updating parent ISets
93
    /// 3. Validates the root frame
94
    ///
95
    /// # Errors
96
    ///
97
    /// Returns an error if any required fields are missing or if the partial is
98
    /// not in deferred mode.
99
    pub fn finish_deferred(&mut self) -> Result<&mut Self, ReflectError> {
339✔
100
        // Check if we're in deferred mode first, before extracting state
101
        if !self.is_deferred() {
339✔
102
            return Err(ReflectError::InvariantViolation {
2✔
103
                invariant: "finish_deferred() called but deferred mode is not enabled",
2✔
104
            });
2✔
105
        }
337✔
106

107
        // Extract deferred state, transitioning back to Strict mode
108
        let FrameMode::Deferred {
109
            stack,
337✔
110
            start_depth,
337✔
111
            mut stored_frames,
337✔
112
            ..
113
        } = core::mem::replace(&mut self.mode, FrameMode::Strict { stack: Vec::new() })
337✔
114
        else {
115
            unreachable!("just checked is_deferred()");
×
116
        };
117

118
        // Restore the stack to self.mode
119
        self.mode = FrameMode::Strict { stack };
337✔
120

121
        // Sort paths by depth (deepest first) so we process children before parents
122
        let mut paths: Vec<_> = stored_frames.keys().cloned().collect();
337✔
123
        paths.sort_by_key(|b| core::cmp::Reverse(b.len()));
1,580✔
124

125
        trace!(
126
            "finish_deferred: Processing {} stored frames in order: {:?}",
127
            paths.len(),
128
            paths
129
        );
130

131
        // Process each stored frame from deepest to shallowest
132
        for path in paths {
1,079✔
133
            let mut frame = stored_frames.remove(&path).unwrap();
746✔
134

135
            trace!(
136
                "finish_deferred: Processing frame at {:?}, shape {}, tracker {:?}",
137
                path,
138
                frame.shape,
139
                frame.tracker.kind()
140
            );
141

142
            // Fill in defaults for unset fields that have defaults
143
            frame.fill_defaults();
746✔
144

145
            // Validate the frame is fully initialized
146
            if let Err(e) = frame.require_full_initialization() {
746✔
147
                // Clean up the current frame that failed validation.
148
                // We need to check if the parent will drop it.
149
                let parent_will_drop = if path.len() == 1 {
4✔
150
                    let field_name = path.first().unwrap();
3✔
151
                    self.frames()
3✔
152
                        .first()
3✔
153
                        .is_some_and(|parent| Self::is_field_marked_in_parent(parent, field_name))
3✔
154
                } else {
155
                    false
1✔
156
                };
157

158
                let mut frame = frame; // Make mutable for deinit
4✔
159
                if !parent_will_drop && !matches!(frame.tracker, Tracker::Uninit) {
4✔
160
                    frame.deinit();
4✔
161
                }
4✔
162

163
                // Clean up remaining stored frames before returning error.
164
                // When finish_deferred fails, the parent's iset was NEVER updated for any stored frame,
165
                // so we must deinit all initialized frames ourselves - the parent won't drop them.
166

167
                // Collect keys to remove (can't drain in no_std)
168
                let remaining_paths: Vec<_> = stored_frames.keys().cloned().collect();
4✔
169
                // Sort by depth (deepest first) for proper cleanup order
170
                let mut sorted_paths = remaining_paths;
4✔
171
                sorted_paths.sort_by_key(|p| core::cmp::Reverse(p.len()));
4✔
172

173
                for remaining_path in sorted_paths {
7✔
174
                    if let Some(mut remaining_frame) = stored_frames.remove(&remaining_path) {
3✔
175
                        // Check if this frame was re-entered (parent already has it marked as init).
176
                        // If so, the parent will drop it - we must NOT deinit (double-free).
177
                        // If not, we must deinit because the parent won't drop it.
178
                        let parent_will_drop = if remaining_path.len() == 1 {
3✔
179
                            // Parent is the root frame
180
                            let field_name = remaining_path.first().unwrap();
3✔
181
                            self.frames().first().is_some_and(|parent| {
3✔
182
                                Self::is_field_marked_in_parent(parent, field_name)
3✔
183
                            })
3✔
184
                        } else {
185
                            // Parent is a stored frame - but stored frames haven't been updated yet,
186
                            // so we need to check against what was already set before deferred mode.
187
                            // For now, conservatively assume parent won't drop nested frames.
UNCOV
188
                            false
×
189
                        };
190

191
                        if !parent_will_drop && !matches!(remaining_frame.tracker, Tracker::Uninit)
3✔
192
                        {
3✔
193
                            remaining_frame.deinit();
3✔
194
                        }
3✔
UNCOV
195
                    }
×
196
                }
197
                return Err(e);
4✔
198
            }
742✔
199

200
            // Update parent's ISet to mark this field as initialized.
201
            // The parent could be:
202
            // 1. On the frames stack (if path.len() == 1, parent is at start_depth - 1)
203
            // 2. On the frames stack (if parent was pushed but never ended)
204
            // 3. In stored_frames (if parent was ended during deferred mode)
205
            if let Some(field_name) = path.last() {
742✔
206
                let parent_path: Vec<_> = path[..path.len() - 1].to_vec();
742✔
207

208
                if parent_path.is_empty() {
742✔
209
                    // Parent is the frame that was current when deferred mode started.
210
                    // It's at index (start_depth - 1) because deferred mode stores frames
211
                    // relative to the position at start_depth.
212
                    let parent_index = start_depth.saturating_sub(1);
485✔
213
                    if let Some(root_frame) = self.frames_mut().get_mut(parent_index) {
485✔
214
                        Self::mark_field_initialized(root_frame, field_name);
485✔
215
                    }
485✔
216
                } else {
217
                    // Try stored_frames first
218
                    if let Some(parent_frame) = stored_frames.get_mut(&parent_path) {
257✔
219
                        Self::mark_field_initialized(parent_frame, field_name);
257✔
220
                    } else {
257✔
221
                        // Parent might still be on the frames stack (never ended).
222
                        // The frame at index (start_depth + parent_path.len() - 1) should be the parent.
223
                        let parent_frame_index = start_depth + parent_path.len() - 1;
×
UNCOV
224
                        if let Some(parent_frame) = self.frames_mut().get_mut(parent_frame_index) {
×
UNCOV
225
                            Self::mark_field_initialized(parent_frame, field_name);
×
226
                        }
×
227
                    }
228
                }
UNCOV
229
            }
×
230

231
            // Frame is validated and parent is updated - frame is no longer needed
232
            // (The actual data is already in place in memory, pointed to by parent)
233
            drop(frame);
742✔
234
        }
235

236
        // Fill defaults and validate the root frame is fully initialized
237
        if let Some(frame) = self.frames_mut().last_mut() {
333✔
238
            frame.fill_defaults();
333✔
239
            frame.require_full_initialization()?;
333✔
UNCOV
240
        }
×
241

242
        Ok(self)
329✔
243
    }
339✔
244

245
    /// Mark a field as initialized in a frame's tracker
246
    fn mark_field_initialized(frame: &mut Frame, field_name: &str) {
742✔
247
        if let Some(idx) = Self::find_field_index(frame, field_name) {
742✔
248
            match &mut frame.tracker {
740✔
249
                Tracker::Struct { iset, .. } => {
649✔
250
                    iset.set(idx);
649✔
251
                }
649✔
252
                Tracker::Enum { data, .. } => {
91✔
253
                    data.set(idx);
91✔
254
                }
91✔
UNCOV
255
                Tracker::Array { iset, .. } => {
×
UNCOV
256
                    iset.set(idx);
×
UNCOV
257
                }
×
UNCOV
258
                _ => {}
×
259
            }
260
        }
2✔
261
    }
742✔
262

263
    /// Find the field index for a given field name in a frame
264
    fn find_field_index(frame: &Frame, field_name: &str) -> Option<usize> {
762✔
265
        match frame.shape.ty {
762✔
266
            Type::User(UserType::Struct(struct_type)) => {
669✔
267
                struct_type.fields.iter().position(|f| f.name == field_name)
1,395✔
268
            }
269
            Type::User(UserType::Enum(_)) => {
270
                if let Tracker::Enum { variant, .. } = &frame.tracker {
93✔
271
                    variant
93✔
272
                        .data
93✔
273
                        .fields
93✔
274
                        .iter()
93✔
275
                        .position(|f| f.name == field_name)
112✔
276
                } else {
UNCOV
277
                    None
×
278
                }
279
            }
UNCOV
280
            _ => None,
×
281
        }
282
    }
762✔
283

284
    /// Check if a field is marked as initialized in the parent's iset/data tracker
285
    pub(crate) fn is_field_marked_in_parent(parent: &Frame, field_name: &str) -> bool {
16✔
286
        // First find the field index
287
        let idx = match Self::find_field_index(parent, field_name) {
16✔
288
            Some(idx) => idx,
16✔
UNCOV
289
            None => return false,
×
290
        };
291

292
        // Then check if it's marked in the parent's tracker
293
        match &parent.tracker {
16✔
294
            Tracker::Struct { iset, .. } => iset.get(idx),
16✔
UNCOV
295
            Tracker::Enum { data, .. } => data.get(idx),
×
UNCOV
296
            _ => false,
×
297
        }
298
    }
16✔
299

300
    /// Unmark a field from the parent's iset/data tracker
301
    /// Used when cleaning up stored frames to prevent double-free
302
    pub(crate) fn unmark_field_in_parent(parent: &mut Frame, field_name: &str) {
4✔
303
        // First find the field index
304
        let idx = match Self::find_field_index(parent, field_name) {
4✔
305
            Some(idx) => idx,
4✔
UNCOV
306
            None => return,
×
307
        };
308

309
        // Then unmark it in the parent's tracker
310
        match &mut parent.tracker {
4✔
311
            Tracker::Struct { iset, .. } => iset.unset(idx),
4✔
UNCOV
312
            Tracker::Enum { data, .. } => data.unset(idx),
×
UNCOV
313
            _ => {}
×
314
        }
315
    }
4✔
316

317
    /// Pops the current frame off the stack, indicating we're done initializing the current field
318
    pub fn end(&mut self) -> Result<&mut Self, ReflectError> {
3,261✔
319
        crate::trace!("end() called");
320
        self.require_active()?;
3,261✔
321

322
        // Special handling for SmartPointerSlice - convert builder to Arc
323
        if self.frames().len() == 1 {
3,261✔
324
            let frames = self.frames_mut();
14✔
325
            if let Tracker::SmartPointerSlice {
326
                vtable,
13✔
327
                building_item,
13✔
328
            } = &frames[0].tracker
14✔
329
            {
330
                if *building_item {
13✔
UNCOV
331
                    return Err(ReflectError::OperationFailed {
×
UNCOV
332
                        shape: frames[0].shape,
×
UNCOV
333
                        operation: "still building an item, finish it first",
×
UNCOV
334
                    });
×
335
                }
13✔
336

337
                // Convert the builder to Arc<[T]>
338
                let vtable = *vtable;
13✔
339
                let builder_ptr = unsafe { frames[0].data.assume_init() };
13✔
340
                let arc_ptr = unsafe { (vtable.convert_fn)(builder_ptr) };
13✔
341

342
                // Update the frame to store the Arc
343
                frames[0].data = PtrUninit::new(unsafe {
13✔
344
                    NonNull::new_unchecked(arc_ptr.as_byte_ptr() as *mut u8)
13✔
345
                });
13✔
346
                frames[0].tracker = Tracker::Init;
13✔
347
                // The builder memory has been consumed by convert_fn, so we no longer own it
348
                frames[0].ownership = FrameOwnership::ManagedElsewhere;
13✔
349

350
                return Ok(self);
13✔
351
            }
1✔
352
        }
3,247✔
353

354
        if self.frames().len() <= 1 {
3,248✔
355
            // Never pop the last/root frame.
356
            return Err(ReflectError::InvariantViolation {
1✔
357
                invariant: "Partial::end() called with only one frame on the stack",
1✔
358
            });
1✔
359
        }
3,247✔
360

361
        // In deferred mode, cannot pop below the start depth
362
        if let Some(start_depth) = self.start_depth() {
3,247✔
363
            if self.frames().len() <= start_depth {
1,182✔
UNCOV
364
                return Err(ReflectError::InvariantViolation {
×
UNCOV
365
                    invariant: "Partial::end() called but would pop below deferred start depth",
×
UNCOV
366
                });
×
367
            }
1,182✔
368
        }
2,065✔
369

370
        // Require that the top frame is fully initialized before popping.
371
        // Skip this check in deferred mode - validation happens in finish_deferred().
372
        // EXCEPT for collection items (map, list, set, option) which must be fully
373
        // initialized before insertion/completion.
374
        let requires_full_init = if !self.is_deferred() {
3,247✔
375
            true
2,065✔
376
        } else {
377
            // In deferred mode, check if parent is a collection that requires
378
            // fully initialized items (map, list, set, option)
379
            if self.frames().len() >= 2 {
1,182✔
380
                let frame_len = self.frames().len();
1,182✔
381
                let parent_frame = &self.frames()[frame_len - 2];
1,182✔
382
                matches!(
931✔
383
                    parent_frame.tracker,
1,182✔
384
                    Tracker::Map { .. }
385
                        | Tracker::List { .. }
386
                        | Tracker::Set { .. }
387
                        | Tracker::Option { .. }
388
                )
389
            } else {
UNCOV
390
                false
×
391
            }
392
        };
393

394
        if requires_full_init {
3,247✔
395
            let frame = self.frames().last().unwrap();
2,316✔
396
            trace!(
397
                "end(): Checking full initialization for frame with shape {} and tracker {:?}",
398
                frame.shape,
399
                frame.tracker.kind()
400
            );
401
            frame.require_full_initialization()?
2,316✔
402
        }
931✔
403

404
        // Pop the frame and save its data pointer for SmartPointer handling
405
        let mut popped_frame = self.frames_mut().pop().unwrap();
3,232✔
406

407
        // In deferred mode, store the frame for potential re-entry and skip
408
        // the normal parent-updating logic. The frame will be finalized later
409
        // in finish_deferred().
410
        //
411
        // We only store if the path depth matches the frame depth, meaning we're
412
        // ending a tracked struct/enum field, not something like begin_some()
413
        // or a field inside a collection item.
414
        if let FrameMode::Deferred {
415
            stack,
1,182✔
416
            start_depth,
1,182✔
417
            current_path,
1,182✔
418
            stored_frames,
1,182✔
419
            ..
420
        } = &mut self.mode
3,232✔
421
        {
422
            // Path depth should match the relative frame depth for a tracked field.
423
            // After popping: frames.len() - start_depth + 1 should equal path.len()
424
            // for fields entered via begin_field (not begin_some/begin_inner).
425
            let relative_depth = stack.len() - *start_depth + 1;
1,182✔
426
            let is_tracked_field = !current_path.is_empty() && current_path.len() == relative_depth;
1,182✔
427

428
            if is_tracked_field {
1,182✔
429
                trace!(
430
                    "end(): Storing frame for deferred path {:?}, shape {}",
431
                    current_path, popped_frame.shape
432
                );
433

434
                // Store the frame at the current path
435
                let path = current_path.clone();
830✔
436
                stored_frames.insert(path, popped_frame);
830✔
437

438
                // Pop from current_path
439
                current_path.pop();
830✔
440

441
                // Clear parent's current_child tracking
442
                if let Some(parent_frame) = stack.last_mut() {
830✔
443
                    parent_frame.tracker.clear_current_child();
830✔
444
                }
830✔
445

446
                return Ok(self);
830✔
447
            }
352✔
448
        }
2,050✔
449

450
        // check if this needs deserialization from a different shape
451
        if popped_frame.using_custom_deserialization {
2,402✔
452
            if let Some(deserialize_with) = self
19✔
453
                .parent_field()
19✔
454
                .and_then(|field| field.vtable.deserialize_with)
19✔
455
            {
456
                let parent_frame = self.frames_mut().last_mut().unwrap();
19✔
457

458
                trace!(
459
                    "Detected custom conversion needed from {} to {}",
460
                    popped_frame.shape, parent_frame.shape
461
                );
462

463
                unsafe {
464
                    let res = {
19✔
465
                        let inner_value_ptr = popped_frame.data.assume_init().as_const();
19✔
466
                        (deserialize_with)(inner_value_ptr, parent_frame.data)
19✔
467
                    };
468
                    let popped_frame_shape = popped_frame.shape;
19✔
469

470
                    // we need to do this before any error handling to avoid leaks
471
                    popped_frame.deinit();
19✔
472
                    popped_frame.dealloc();
19✔
473
                    let rptr = res.map_err(|message| ReflectError::CustomDeserializationError {
19✔
474
                        message,
2✔
475
                        src_shape: popped_frame_shape,
2✔
476
                        dst_shape: parent_frame.shape,
2✔
477
                    })?;
2✔
478
                    if rptr.as_uninit() != parent_frame.data {
17✔
479
                        return Err(ReflectError::CustomDeserializationError {
×
UNCOV
480
                            message: "deserialize_with did not return the expected pointer".into(),
×
UNCOV
481
                            src_shape: popped_frame_shape,
×
UNCOV
482
                            dst_shape: parent_frame.shape,
×
UNCOV
483
                        });
×
484
                    }
17✔
485
                    parent_frame.mark_as_init();
17✔
486
                }
487
                return Ok(self);
17✔
UNCOV
488
            }
×
489
        }
2,383✔
490

491
        // Update parent frame's tracking when popping from a child
492
        let parent_frame = self.frames_mut().last_mut().unwrap();
2,383✔
493

494
        trace!(
495
            "end(): Popped {} (tracker {:?}), Parent {} (tracker {:?})",
496
            popped_frame.shape,
497
            popped_frame.tracker.kind(),
498
            parent_frame.shape,
499
            parent_frame.tracker.kind()
500
        );
501

502
        // Check if we need to do a conversion - this happens when:
503
        // 1. The parent frame has an inner type that matches the popped frame's shape
504
        // 2. The parent frame has try_from
505
        // 3. The parent frame is not yet initialized
506
        let needs_conversion = matches!(parent_frame.tracker, Tracker::Uninit)
2,383✔
507
            && parent_frame.shape.inner.is_some()
42✔
508
            && parent_frame.shape.inner.unwrap() == popped_frame.shape
42✔
509
            && parent_frame.shape.vtable.try_from.is_some();
35✔
510

511
        if needs_conversion {
2,383✔
512
            trace!(
513
                "Detected implicit conversion needed from {} to {}",
514
                popped_frame.shape, parent_frame.shape
515
            );
516

517
            // The conversion requires the source frame to be fully initialized
518
            // (we're about to call assume_init() and pass to try_from)
519
            if let Err(e) = popped_frame.require_full_initialization() {
35✔
520
                // Deallocate the memory since the frame wasn't fully initialized
UNCOV
521
                if let FrameOwnership::Owned = popped_frame.ownership {
×
UNCOV
522
                    if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
×
UNCOV
523
                        if layout.size() > 0 {
×
524
                            trace!(
525
                                "Deallocating uninitialized conversion frame memory: size={}, align={}",
526
                                layout.size(),
527
                                layout.align()
528
                            );
529
                            unsafe {
×
530
                                ::alloc::alloc::dealloc(
×
531
                                    popped_frame.data.as_mut_byte_ptr(),
×
532
                                    layout,
×
533
                                );
×
534
                            }
×
UNCOV
535
                        }
×
UNCOV
536
                    }
×
UNCOV
537
                }
×
UNCOV
538
                return Err(e);
×
539
            }
35✔
540

541
            // Perform the conversion
542
            if let Some(try_from_fn) = parent_frame.shape.vtable.try_from {
35✔
543
                let inner_ptr = unsafe { popped_frame.data.assume_init().as_const() };
35✔
544
                let inner_shape = popped_frame.shape;
35✔
545

546
                trace!("Converting from {} to {}", inner_shape, parent_frame.shape);
547
                let result = unsafe { try_from_fn(inner_ptr, inner_shape, parent_frame.data) };
35✔
548

549
                if let Err(e) = result {
35✔
550
                    trace!("Conversion failed: {e:?}");
551

552
                    // Deallocate the inner value's memory since conversion failed
553
                    if let FrameOwnership::Owned = popped_frame.ownership {
2✔
554
                        if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
2✔
555
                            if layout.size() > 0 {
2✔
556
                                trace!(
557
                                    "Deallocating conversion frame memory after failure: size={}, align={}",
558
                                    layout.size(),
559
                                    layout.align()
560
                                );
561
                                unsafe {
2✔
562
                                    ::alloc::alloc::dealloc(
2✔
563
                                        popped_frame.data.as_mut_byte_ptr(),
2✔
564
                                        layout,
2✔
565
                                    );
2✔
566
                                }
2✔
UNCOV
567
                            }
×
UNCOV
568
                        }
×
UNCOV
569
                    }
×
570

571
                    return Err(ReflectError::TryFromError {
2✔
572
                        src_shape: inner_shape,
2✔
573
                        dst_shape: parent_frame.shape,
2✔
574
                        inner: e,
2✔
575
                    });
2✔
576
                }
33✔
577

578
                trace!("Conversion succeeded, marking parent as initialized");
579
                parent_frame.tracker = Tracker::Init;
33✔
580

581
                // Deallocate the inner value's memory since try_from consumed it
582
                if let FrameOwnership::Owned = popped_frame.ownership {
33✔
583
                    if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
33✔
584
                        if layout.size() > 0 {
33✔
585
                            trace!(
586
                                "Deallocating conversion frame memory: size={}, align={}",
587
                                layout.size(),
588
                                layout.align()
589
                            );
590
                            unsafe {
33✔
591
                                ::alloc::alloc::dealloc(
33✔
592
                                    popped_frame.data.as_mut_byte_ptr(),
33✔
593
                                    layout,
33✔
594
                                );
33✔
595
                            }
33✔
UNCOV
596
                        }
×
597
                    }
×
UNCOV
598
                }
×
599

600
                return Ok(self);
33✔
UNCOV
601
            }
×
602
        }
2,348✔
603

604
        match &mut parent_frame.tracker {
2,348✔
605
            Tracker::Struct {
606
                iset,
1,137✔
607
                current_child,
1,137✔
608
            } => {
609
                if let Some(idx) = *current_child {
1,137✔
610
                    iset.set(idx);
1,137✔
611
                    *current_child = None;
1,137✔
612
                }
1,137✔
613
            }
614
            Tracker::Array {
615
                iset,
92✔
616
                current_child,
92✔
617
            } => {
618
                if let Some(idx) = *current_child {
92✔
619
                    iset.set(idx);
92✔
620
                    *current_child = None;
92✔
621
                }
92✔
622
            }
623
            Tracker::SmartPointer { is_initialized } => {
26✔
624
                // We just popped the inner value frame, so now we need to create the smart pointer
625
                if let Def::Pointer(smart_ptr_def) = parent_frame.shape.def {
26✔
626
                    let Some(new_into_fn) = smart_ptr_def.vtable.new_into_fn else {
26✔
UNCOV
627
                        return Err(ReflectError::OperationFailed {
×
UNCOV
628
                            shape: parent_frame.shape,
×
UNCOV
629
                            operation: "SmartPointer missing new_into_fn",
×
UNCOV
630
                        });
×
631
                    };
632

633
                    // The child frame contained the inner value
634
                    let inner_ptr = PtrMut::new(unsafe {
26✔
635
                        NonNull::new_unchecked(popped_frame.data.as_mut_byte_ptr())
26✔
636
                    });
637

638
                    // Use new_into_fn to create the Box
639
                    unsafe {
26✔
640
                        new_into_fn(parent_frame.data, inner_ptr);
26✔
641
                    }
26✔
642

643
                    // We just moved out of it
644
                    popped_frame.tracker = Tracker::Uninit;
26✔
645

646
                    // Deallocate the inner value's memory since new_into_fn moved it
647
                    popped_frame.dealloc();
26✔
648

649
                    *is_initialized = true;
26✔
UNCOV
650
                }
×
651
            }
652
            Tracker::Enum {
653
                data,
110✔
654
                current_child,
110✔
655
                ..
656
            } => {
657
                if let Some(idx) = *current_child {
110✔
658
                    data.set(idx);
110✔
659
                    *current_child = None;
110✔
660
                }
110✔
661
            }
662
            Tracker::List {
663
                is_initialized: true,
664
                current_child,
617✔
665
            } => {
666
                if *current_child {
617✔
667
                    // We just popped an element frame, now push it to the list
668
                    if let Def::List(list_def) = parent_frame.shape.def {
617✔
669
                        let Some(push_fn) = list_def.vtable.push else {
617✔
UNCOV
670
                            return Err(ReflectError::OperationFailed {
×
UNCOV
671
                                shape: parent_frame.shape,
×
UNCOV
672
                                operation: "List missing push function",
×
UNCOV
673
                            });
×
674
                        };
675

676
                        // The child frame contained the element value
677
                        let element_ptr = PtrMut::new(unsafe {
617✔
678
                            NonNull::new_unchecked(popped_frame.data.as_mut_byte_ptr())
617✔
679
                        });
680

681
                        // Use push to add element to the list
682
                        unsafe {
617✔
683
                            push_fn(
617✔
684
                                PtrMut::new(NonNull::new_unchecked(
617✔
685
                                    parent_frame.data.as_mut_byte_ptr(),
617✔
686
                                )),
617✔
687
                                element_ptr,
617✔
688
                            );
617✔
689
                        }
617✔
690

691
                        // Push moved out of popped_frame
692
                        popped_frame.tracker = Tracker::Uninit;
617✔
693
                        popped_frame.dealloc();
617✔
694

695
                        *current_child = false;
617✔
UNCOV
696
                    }
×
UNCOV
697
                }
×
698
            }
699
            Tracker::Map {
700
                is_initialized: true,
701
                insert_state,
180✔
702
            } => {
703
                match insert_state {
180✔
704
                    MapInsertState::PushingKey { key_ptr, .. } => {
93✔
705
                        // We just popped the key frame - mark key as initialized and transition
93✔
706
                        // to PushingValue state
93✔
707
                        *insert_state = MapInsertState::PushingValue {
93✔
708
                            key_ptr: *key_ptr,
93✔
709
                            value_ptr: None,
93✔
710
                            value_initialized: false,
93✔
711
                        };
93✔
712
                    }
93✔
713
                    MapInsertState::PushingValue {
714
                        key_ptr, value_ptr, ..
87✔
715
                    } => {
716
                        // We just popped the value frame, now insert the pair
717
                        if let (Some(value_ptr), Def::Map(map_def)) =
87✔
718
                            (value_ptr, parent_frame.shape.def)
87✔
719
                        {
720
                            let insert_fn = map_def.vtable.insert_fn;
87✔
721

722
                            // Use insert to add key-value pair to the map
723
                            unsafe {
87✔
724
                                insert_fn(
87✔
725
                                    PtrMut::new(NonNull::new_unchecked(
87✔
726
                                        parent_frame.data.as_mut_byte_ptr(),
87✔
727
                                    )),
87✔
728
                                    PtrMut::new(NonNull::new_unchecked(key_ptr.as_mut_byte_ptr())),
87✔
729
                                    PtrMut::new(NonNull::new_unchecked(
87✔
730
                                        value_ptr.as_mut_byte_ptr(),
87✔
731
                                    )),
87✔
732
                                );
87✔
733
                            }
87✔
734

735
                            // Note: We don't deallocate the key and value memory here.
736
                            // The insert function has semantically moved the values into the map,
737
                            // but we still need to deallocate the temporary buffers.
738
                            // However, since we don't have frames for them anymore (they were popped),
739
                            // we need to handle deallocation here.
740
                            if let Ok(key_shape) = map_def.k().layout.sized_layout() {
87✔
741
                                if key_shape.size() > 0 {
87✔
742
                                    unsafe {
87✔
743
                                        ::alloc::alloc::dealloc(
87✔
744
                                            key_ptr.as_mut_byte_ptr(),
87✔
745
                                            key_shape,
87✔
746
                                        );
87✔
747
                                    }
87✔
UNCOV
748
                                }
×
UNCOV
749
                            }
×
750
                            if let Ok(value_shape) = map_def.v().layout.sized_layout() {
87✔
751
                                if value_shape.size() > 0 {
87✔
752
                                    unsafe {
87✔
753
                                        ::alloc::alloc::dealloc(
87✔
754
                                            value_ptr.as_mut_byte_ptr(),
87✔
755
                                            value_shape,
87✔
756
                                        );
87✔
757
                                    }
87✔
UNCOV
758
                                }
×
759
                            }
×
760

761
                            // Reset to idle state
762
                            *insert_state = MapInsertState::Idle;
87✔
763
                        }
×
764
                    }
UNCOV
765
                    MapInsertState::Idle => {
×
UNCOV
766
                        // Nothing to do
×
UNCOV
767
                    }
×
768
                }
769
            }
770
            Tracker::Set {
771
                is_initialized: true,
772
                current_child,
33✔
773
            } => {
774
                if *current_child {
33✔
775
                    // We just popped an element frame, now insert it into the set
776
                    if let Def::Set(set_def) = parent_frame.shape.def {
33✔
777
                        let insert_fn = set_def.vtable.insert_fn;
33✔
778

33✔
779
                        // The child frame contained the element value
33✔
780
                        let element_ptr = PtrMut::new(unsafe {
33✔
781
                            NonNull::new_unchecked(popped_frame.data.as_mut_byte_ptr())
33✔
782
                        });
33✔
783

33✔
784
                        // Use insert to add element to the set
33✔
785
                        unsafe {
33✔
786
                            insert_fn(
33✔
787
                                PtrMut::new(NonNull::new_unchecked(
33✔
788
                                    parent_frame.data.as_mut_byte_ptr(),
33✔
789
                                )),
33✔
790
                                element_ptr,
33✔
791
                            );
33✔
792
                        }
33✔
793

33✔
794
                        // Insert moved out of popped_frame
33✔
795
                        popped_frame.tracker = Tracker::Uninit;
33✔
796
                        popped_frame.dealloc();
33✔
797

33✔
798
                        *current_child = false;
33✔
799
                    }
33✔
UNCOV
800
                }
×
801
            }
802
            Tracker::Option { building_inner } => {
112✔
803
                // We just popped the inner value frame for an Option's Some variant
804
                if *building_inner {
112✔
805
                    if let Def::Option(option_def) = parent_frame.shape.def {
112✔
806
                        // Use the Option vtable to initialize Some(inner_value)
807
                        let init_some_fn = option_def.vtable.init_some_fn;
112✔
808

809
                        // The popped frame contains the inner value
810
                        let inner_value_ptr = unsafe { popped_frame.data.assume_init().as_const() };
112✔
811

812
                        // Initialize the Option as Some(inner_value)
813
                        unsafe {
112✔
814
                            init_some_fn(parent_frame.data, inner_value_ptr);
112✔
815
                        }
112✔
816

817
                        // Deallocate the inner value's memory since init_some_fn moved it
818
                        if let FrameOwnership::Owned = popped_frame.ownership {
112✔
819
                            if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
112✔
820
                                if layout.size() > 0 {
112✔
821
                                    unsafe {
112✔
822
                                        ::alloc::alloc::dealloc(
112✔
823
                                            popped_frame.data.as_mut_byte_ptr(),
112✔
824
                                            layout,
112✔
825
                                        );
112✔
826
                                    }
112✔
UNCOV
827
                                }
×
UNCOV
828
                            }
×
UNCOV
829
                        }
×
830

831
                        // Mark that we're no longer building the inner value
832
                        *building_inner = false;
112✔
833
                    } else {
UNCOV
834
                        return Err(ReflectError::OperationFailed {
×
UNCOV
835
                            shape: parent_frame.shape,
×
UNCOV
836
                            operation: "Option frame without Option definition",
×
UNCOV
837
                        });
×
838
                    }
839
                } else {
840
                    // building_inner is false - the Option was already initialized but
841
                    // begin_some was called again. The popped frame was not used to
842
                    // initialize the Option, so we need to clean it up.
843
                    popped_frame.deinit();
×
844
                    if let FrameOwnership::Owned = popped_frame.ownership {
×
845
                        if let Ok(layout) = popped_frame.shape.layout.sized_layout() {
×
846
                            if layout.size() > 0 {
×
847
                                unsafe {
×
848
                                    ::alloc::alloc::dealloc(
×
849
                                        popped_frame.data.as_mut_byte_ptr(),
×
850
                                        layout,
×
851
                                    );
×
UNCOV
852
                                }
×
UNCOV
853
                            }
×
UNCOV
854
                        }
×
UNCOV
855
                    }
×
856
                }
857
            }
858
            Tracker::Uninit | Tracker::Init => {
859
                // the main case here is: the popped frame was a `String` and the
860
                // parent frame is an `Arc<str>`, `Box<str>` etc.
861
                match &parent_frame.shape.def {
8✔
862
                    Def::Pointer(smart_ptr_def) => {
8✔
863
                        let pointee =
8✔
864
                            smart_ptr_def
8✔
865
                                .pointee()
8✔
866
                                .ok_or(ReflectError::InvariantViolation {
8✔
867
                                    invariant: "pointer type doesn't have a pointee",
8✔
868
                                })?;
8✔
869

870
                        if !pointee.is_shape(str::SHAPE) {
8✔
UNCOV
871
                            return Err(ReflectError::InvariantViolation {
×
UNCOV
872
                                invariant: "only T=str is supported when building SmartPointer<T> and T is unsized",
×
873
                            });
×
874
                        }
8✔
875

876
                        if !popped_frame.shape.is_shape(String::SHAPE) {
8✔
UNCOV
877
                            return Err(ReflectError::InvariantViolation {
×
UNCOV
878
                                invariant: "the popped frame should be String when building a SmartPointer<T>",
×
UNCOV
879
                            });
×
880
                        }
8✔
881

882
                        popped_frame.require_full_initialization()?;
8✔
883

884
                        // if the just-popped frame was a SmartPointerStr, we have some conversion to do:
885
                        // Special-case: SmartPointer<str> (Box<str>, Arc<str>, Rc<str>) via SmartPointerStr tracker
886
                        // Here, popped_frame actually contains a value for String that should be moved into the smart pointer.
887
                        // We convert the String into Box<str>, Arc<str>, or Rc<str> as appropriate and write it to the parent frame.
888
                        use ::alloc::{rc::Rc, string::String, sync::Arc};
889
                        let parent_shape = parent_frame.shape;
8✔
890

891
                        let Some(known) = smart_ptr_def.known else {
8✔
UNCOV
892
                            return Err(ReflectError::OperationFailed {
×
UNCOV
893
                                shape: parent_shape,
×
UNCOV
894
                                operation: "SmartPointerStr for unknown smart pointer kind",
×
UNCOV
895
                            });
×
896
                        };
897

898
                        parent_frame.deinit();
8✔
899

900
                        // Interpret the memory as a String, then convert and write.
901
                        let string_ptr = popped_frame.data.as_mut_byte_ptr() as *mut String;
8✔
902
                        let string_value = unsafe { core::ptr::read(string_ptr) };
8✔
903

904
                        match known {
8✔
905
                            KnownPointer::Box => {
906
                                let boxed: Box<str> = string_value.into_boxed_str();
2✔
907
                                unsafe {
2✔
908
                                    core::ptr::write(
2✔
909
                                        parent_frame.data.as_mut_byte_ptr() as *mut Box<str>,
2✔
910
                                        boxed,
2✔
911
                                    );
2✔
912
                                }
2✔
913
                            }
914
                            KnownPointer::Arc => {
915
                                let arc: Arc<str> = Arc::from(string_value.into_boxed_str());
2✔
916
                                unsafe {
2✔
917
                                    core::ptr::write(
2✔
918
                                        parent_frame.data.as_mut_byte_ptr() as *mut Arc<str>,
2✔
919
                                        arc,
2✔
920
                                    );
2✔
921
                                }
2✔
922
                            }
923
                            KnownPointer::Rc => {
924
                                let rc: Rc<str> = Rc::from(string_value.into_boxed_str());
4✔
925
                                unsafe {
4✔
926
                                    core::ptr::write(
4✔
927
                                        parent_frame.data.as_mut_byte_ptr() as *mut Rc<str>,
4✔
928
                                        rc,
4✔
929
                                    );
4✔
930
                                }
4✔
931
                            }
932
                            _ => {
UNCOV
933
                                return Err(ReflectError::OperationFailed {
×
UNCOV
934
                                    shape: parent_shape,
×
UNCOV
935
                                    operation: "Don't know how to build this pointer type",
×
UNCOV
936
                                });
×
937
                            }
938
                        }
939

940
                        parent_frame.tracker = Tracker::Init;
8✔
941

942
                        popped_frame.tracker = Tracker::Uninit;
8✔
943
                        popped_frame.dealloc();
8✔
944
                    }
945
                    _ => {
946
                        // This can happen if begin_inner() was called on a type that
947
                        // has shape.inner but isn't a SmartPointer (e.g., Option).
948
                        // In this case, we can't complete the conversion, so return error.
UNCOV
949
                        return Err(ReflectError::OperationFailed {
×
UNCOV
950
                            shape: parent_frame.shape,
×
UNCOV
951
                            operation: "end() called but parent has Uninit/Init tracker and isn't a SmartPointer",
×
UNCOV
952
                        });
×
953
                    }
954
                }
955
            }
956
            Tracker::SmartPointerSlice {
957
                vtable,
33✔
958
                building_item,
33✔
959
            } => {
960
                if *building_item {
33✔
961
                    // We just popped an element frame, now push it to the slice builder
962
                    let element_ptr = PtrMut::new(unsafe {
33✔
963
                        NonNull::new_unchecked(popped_frame.data.as_mut_byte_ptr())
33✔
964
                    });
965

966
                    // Use the slice builder's push_fn to add the element
967
                    crate::trace!("Pushing element to slice builder");
968
                    unsafe {
33✔
969
                        let parent_ptr = parent_frame.data.assume_init();
33✔
970
                        (vtable.push_fn)(parent_ptr, element_ptr);
33✔
971
                    }
33✔
972

973
                    popped_frame.tracker = Tracker::Uninit;
33✔
974
                    popped_frame.dealloc();
33✔
975

976
                    if let Tracker::SmartPointerSlice {
977
                        building_item: bi, ..
33✔
978
                    } = &mut parent_frame.tracker
33✔
979
                    {
33✔
980
                        *bi = false;
33✔
981
                    }
33✔
UNCOV
982
                }
×
983
            }
UNCOV
984
            _ => {}
×
985
        }
986

987
        Ok(self)
2,348✔
988
    }
3,261✔
989

990
    /// Returns a human-readable path representing the current traversal in the builder,
991
    /// e.g., `RootStruct.fieldName[index].subfield`.
992
    pub fn path(&self) -> String {
364✔
993
        let mut out = String::new();
364✔
994

995
        let mut path_components = Vec::new();
364✔
996
        // The stack of enum/struct/sequence names currently in context.
997
        // Start from root and build upwards.
998
        for (i, frame) in self.frames().iter().enumerate() {
718✔
999
            match frame.shape.ty {
718✔
1000
                Type::User(user_type) => match user_type {
600✔
1001
                    UserType::Struct(struct_type) => {
351✔
1002
                        // Try to get currently active field index
1003
                        let mut field_str = None;
351✔
1004
                        if let Tracker::Struct {
1005
                            current_child: Some(idx),
216✔
1006
                            ..
1007
                        } = &frame.tracker
220✔
1008
                        {
1009
                            if let Some(field) = struct_type.fields.get(*idx) {
216✔
1010
                                field_str = Some(field.name);
216✔
1011
                            }
216✔
1012
                        }
135✔
1013
                        if i == 0 {
351✔
1014
                            // Use Display for the root struct shape
272✔
1015
                            path_components.push(format!("{}", frame.shape));
272✔
1016
                        }
272✔
1017
                        if let Some(field_name) = field_str {
351✔
1018
                            path_components.push(format!(".{field_name}"));
216✔
1019
                        }
216✔
1020
                    }
1021
                    UserType::Enum(_enum_type) => {
15✔
1022
                        // Try to get currently active variant and field
1023
                        if let Tracker::Enum {
1024
                            variant,
4✔
1025
                            current_child,
4✔
1026
                            ..
1027
                        } = &frame.tracker
15✔
1028
                        {
1029
                            if i == 0 {
4✔
1030
                                // Use Display for the root enum shape
4✔
1031
                                path_components.push(format!("{}", frame.shape));
4✔
1032
                            }
4✔
1033
                            path_components.push(format!("::{}", variant.name));
4✔
1034
                            if let Some(idx) = *current_child {
4✔
1035
                                if let Some(field) = variant.data.fields.get(idx) {
4✔
1036
                                    path_components.push(format!(".{}", field.name));
4✔
1037
                                }
4✔
UNCOV
1038
                            }
×
1039
                        } else if i == 0 {
11✔
1040
                            // just the enum display
×
1041
                            path_components.push(format!("{}", frame.shape));
×
1042
                        }
11✔
1043
                    }
UNCOV
1044
                    UserType::Union(_union_type) => {
×
UNCOV
1045
                        path_components.push(format!("{}", frame.shape));
×
UNCOV
1046
                    }
×
1047
                    UserType::Opaque => {
234✔
1048
                        path_components.push("<opaque>".to_string());
234✔
1049
                    }
234✔
1050
                },
1051
                Type::Sequence(seq_type) => match seq_type {
×
UNCOV
1052
                    facet_core::SequenceType::Array(_array_def) => {
×
1053
                        // Try to show current element index
1054
                        if let Tracker::Array {
1055
                            current_child: Some(idx),
×
1056
                            ..
UNCOV
1057
                        } = &frame.tracker
×
UNCOV
1058
                        {
×
1059
                            path_components.push(format!("[{idx}]"));
×
1060
                        }
×
1061
                    }
1062
                    // You can add more for Slice, Vec, etc., if applicable
UNCOV
1063
                    _ => {
×
1064
                        // just indicate "[]" for sequence
×
1065
                        path_components.push("[]".to_string());
×
1066
                    }
×
1067
                },
UNCOV
1068
                Type::Pointer(_) => {
×
UNCOV
1069
                    // Indicate deref
×
UNCOV
1070
                    path_components.push("*".to_string());
×
UNCOV
1071
                }
×
1072
                _ => {
118✔
1073
                    // No structural path
118✔
1074
                }
118✔
1075
            }
1076
        }
1077
        // Merge the path_components into a single string
1078
        for component in path_components {
1,098✔
1079
            out.push_str(&component);
734✔
1080
        }
734✔
1081
        out
364✔
1082
    }
364✔
1083

1084
    /// Get the field for the parent frame
1085
    pub fn parent_field(&self) -> Option<&Field> {
145✔
1086
        self.frames()
145✔
1087
            .iter()
145✔
1088
            .rev()
145✔
1089
            .nth(1)
145✔
1090
            .and_then(|f| f.get_field())
145✔
1091
    }
145✔
1092

1093
    /// Gets the field for the current frame
UNCOV
1094
    pub fn current_field(&self) -> Option<&Field> {
×
UNCOV
1095
        self.frames().last().and_then(|f| f.get_field())
×
UNCOV
1096
    }
×
1097
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc