facet-core 0.46.0

Core reflection traits and types for the facet ecosystem - provides the Facet trait, Shape metadata, and type-erased pointers
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
#![cfg(feature = "lock_api")]

use alloc::boxed::Box;
use core::ptr::NonNull;

use lock_api::{Mutex, MutexGuard, RawMutex, RawRwLock, RwLock, RwLockReadGuard, RwLockWriteGuard};

use crate::{
    DeclId, Def, Facet, KnownPointer, LockGuardVTable, OxPtrMut, PointerDef, PointerFlags,
    PointerVTable, PtrConst, PtrMut, PtrUninit, ReadLockResult, Shape, ShapeBuilder, Type,
    TypeNameOpts, TypeOpsIndirect, TypeParam, UserType, VTableIndirect, Variance, VarianceDep,
    VarianceDesc, WriteLockResult, decl_id_hash,
};

// ============================================================================
// Mutex<R, T> Implementation
// ============================================================================

fn type_name_mutex<'a, T: Facet<'a>>(
    _shape: &'static Shape,
    f: &mut core::fmt::Formatter<'_>,
    opts: TypeNameOpts,
) -> core::fmt::Result {
    write!(f, "Mutex")?;
    if let Some(opts) = opts.for_children() {
        write!(f, "<")?;
        T::SHAPE.write_type_name(f, opts)?;
        write!(f, ">")?;
    } else {
        write!(f, "<\u{2026}>")?;
    }
    Ok(())
}

unsafe extern "C" fn mutex_new_into<R: RawMutex, T>(this: PtrUninit, value: PtrMut) -> PtrMut {
    unsafe {
        let t = value.read::<T>();
        this.put(Mutex::<R, T>::new(t))
    }
}

unsafe fn mutex_drop<R: RawMutex, T>(ox: OxPtrMut) {
    unsafe { core::ptr::drop_in_place(ox.ptr().as_ptr::<Mutex<R, T>>() as *mut Mutex<R, T>) }
}

unsafe fn mutex_lock<'a, R: RawMutex, T: Facet<'a>>(
    opaque: PtrConst,
) -> Result<WriteLockResult, ()> {
    unsafe {
        let mutex = &*opaque.as_ptr::<Mutex<R, T>>();
        let mut guard = mutex.lock();

        // Get pointer to the data through the guard (exclusive access)
        // Use &mut to get a valid mutable pointer
        let data_ptr = &mut *guard as *mut T;

        // Box the guard to keep it alive (type-erased)
        let guard_box = Box::new(guard);
        let guard_ptr = Box::into_raw(guard_box) as *const u8;

        Ok(WriteLockResult::new(
            PtrMut::new(data_ptr as *mut u8),
            PtrConst::new(guard_ptr),
            &const { mutex_guard_vtable::<R, T>() },
        ))
    }
}

const fn mutex_guard_vtable<R: RawMutex, T>() -> LockGuardVTable {
    unsafe fn drop_guard<R: RawMutex, T>(guard: PtrConst) {
        unsafe {
            drop(Box::from_raw(
                guard.as_ptr::<MutexGuard<'_, R, T>>() as *mut MutexGuard<'_, R, T>
            ));
        }
    }

    LockGuardVTable {
        drop_in_place: drop_guard::<R, T>,
    }
}

unsafe impl<'a, R: RawMutex + 'a, T: Facet<'a>> Facet<'a> for Mutex<R, T> {
    const SHAPE: &'static Shape = &const {
        ShapeBuilder::for_sized::<Self>("Mutex")
            .decl_id(DeclId::new(decl_id_hash("#lock_api#Mutex")))
            .type_name(type_name_mutex::<T>)
            .vtable_indirect(&VTableIndirect::EMPTY)
            .type_ops_indirect(
                &const {
                    TypeOpsIndirect {
                        drop_in_place: mutex_drop::<R, T>,
                        default_in_place: None,
                        clone_into: None,
                        is_truthy: None,
                    }
                },
            )
            .ty(Type::User(UserType::Opaque))
            .def(Def::Pointer(PointerDef {
                vtable: &const {
                    PointerVTable {
                        lock_fn: Some(mutex_lock::<R, T>),
                        new_into_fn: Some(mutex_new_into::<R, T>),
                        ..PointerVTable::new()
                    }
                },
                pointee: Some(T::SHAPE),
                weak: None,
                strong: None,
                flags: PointerFlags::LOCK,
                known: Some(KnownPointer::Mutex),
            }))
            .type_params(&[TypeParam {
                name: "T",
                shape: T::SHAPE,
            }])
            .inner(T::SHAPE)
            // Mutex<T> is invariant w.r.t. T because it provides interior mutability
            .variance(VarianceDesc {
                base: Variance::Bivariant,
                deps: &const { [VarianceDep::invariant(T::SHAPE)] },
            })
            .build()
    };
}

// ============================================================================
// RwLock<R, T> Implementation
// ============================================================================

fn type_name_rwlock<'a, T: Facet<'a>>(
    _shape: &'static Shape,
    f: &mut core::fmt::Formatter<'_>,
    opts: TypeNameOpts,
) -> core::fmt::Result {
    write!(f, "RwLock")?;
    if let Some(opts) = opts.for_children() {
        write!(f, "<")?;
        T::SHAPE.write_type_name(f, opts)?;
        write!(f, ">")?;
    } else {
        write!(f, "<\u{2026}>")?;
    }
    Ok(())
}

unsafe extern "C" fn rwlock_new_into<R: RawRwLock, T>(this: PtrUninit, value: PtrMut) -> PtrMut {
    unsafe {
        let t = value.read::<T>();
        this.put(RwLock::<R, T>::new(t))
    }
}

unsafe fn rwlock_drop<R: RawRwLock, T>(ox: OxPtrMut) {
    unsafe { core::ptr::drop_in_place(ox.ptr().as_ptr::<RwLock<R, T>>() as *mut RwLock<R, T>) }
}

const fn rwlock_read_guard_vtable<R: RawRwLock, T>() -> LockGuardVTable {
    unsafe fn drop_guard<R: RawRwLock, T>(guard: PtrConst) {
        unsafe {
            drop(Box::from_raw(
                guard.as_ptr::<RwLockReadGuard<'_, R, T>>() as *mut RwLockReadGuard<'_, R, T>
            ));
        }
    }

    LockGuardVTable {
        drop_in_place: drop_guard::<R, T>,
    }
}

const fn rwlock_write_guard_vtable<R: RawRwLock, T>() -> LockGuardVTable {
    unsafe fn drop_guard<R: RawRwLock, T>(guard: PtrConst) {
        unsafe {
            drop(Box::from_raw(
                guard.as_ptr::<RwLockWriteGuard<'_, R, T>>() as *mut RwLockWriteGuard<'_, R, T>
            ));
        }
    }

    LockGuardVTable {
        drop_in_place: drop_guard::<R, T>,
    }
}

unsafe fn rwlock_read<'a, R: RawRwLock, T: Facet<'a>>(
    opaque: PtrConst,
) -> Result<ReadLockResult, ()> {
    unsafe {
        let rwlock = &*opaque.as_ptr::<RwLock<R, T>>();
        let guard = rwlock.read();

        // SAFETY: Read lock only provides shared access - use PtrConst
        let data_ptr = &*guard as *const T;
        let guard_box = Box::new(guard);
        let guard_ptr = Box::into_raw(guard_box) as *const u8;

        Ok(ReadLockResult::new(
            PtrConst::new(data_ptr as *const u8),
            PtrConst::new(guard_ptr),
            &const { rwlock_read_guard_vtable::<R, T>() },
        ))
    }
}

unsafe fn rwlock_write<'a, R: RawRwLock, T: Facet<'a>>(
    opaque: PtrConst,
) -> Result<WriteLockResult, ()> {
    unsafe {
        let rwlock = &*opaque.as_ptr::<RwLock<R, T>>();
        let mut guard = rwlock.write();

        // Write lock provides exclusive access - use &mut to get a valid mutable pointer
        let data_ptr = &mut *guard as *mut T;
        let guard_box = Box::new(guard);
        let guard_ptr = Box::into_raw(guard_box) as *const u8;

        Ok(WriteLockResult::new(
            PtrMut::new(data_ptr as *mut u8),
            PtrConst::new(guard_ptr),
            &const { rwlock_write_guard_vtable::<R, T>() },
        ))
    }
}

unsafe impl<'a, R: RawRwLock + 'a, T: Facet<'a>> Facet<'a> for RwLock<R, T> {
    const SHAPE: &'static Shape = &const {
        ShapeBuilder::for_sized::<Self>("RwLock")
            .decl_id(DeclId::new(decl_id_hash("#lock_api#RwLock")))
            .type_name(type_name_rwlock::<T>)
            .vtable_indirect(&VTableIndirect::EMPTY)
            .type_ops_indirect(
                &const {
                    TypeOpsIndirect {
                        drop_in_place: rwlock_drop::<R, T>,
                        default_in_place: None,
                        clone_into: None,
                        is_truthy: None,
                    }
                },
            )
            .ty(Type::User(UserType::Opaque))
            .def(Def::Pointer(PointerDef {
                vtable: &const {
                    PointerVTable {
                        read_fn: Some(rwlock_read::<R, T>),
                        write_fn: Some(rwlock_write::<R, T>),
                        new_into_fn: Some(rwlock_new_into::<R, T>),
                        ..PointerVTable::new()
                    }
                },
                pointee: Some(T::SHAPE),
                weak: None,
                strong: None,
                flags: PointerFlags::LOCK,
                known: Some(KnownPointer::RwLock),
            }))
            .type_params(&[TypeParam {
                name: "T",
                shape: T::SHAPE,
            }])
            .inner(T::SHAPE)
            // RwLock<T> is invariant w.r.t. T because it provides interior mutability
            .variance(VarianceDesc {
                base: Variance::Bivariant,
                deps: &const { [VarianceDep::invariant(T::SHAPE)] },
            })
            .build()
    };
}

// ============================================================================
// MutexGuard<'a, R, T> Implementation
// ============================================================================

fn type_name_mutex_guard<'a, T: Facet<'a>>(
    _shape: &'static Shape,
    f: &mut core::fmt::Formatter<'_>,
    opts: TypeNameOpts,
) -> core::fmt::Result {
    write!(f, "MutexGuard")?;
    if let Some(opts) = opts.for_children() {
        write!(f, "<")?;
        T::SHAPE.write_type_name(f, opts)?;
        write!(f, ">")?;
    } else {
        write!(f, "<\u{2026}>")?;
    }
    Ok(())
}

unsafe extern "C" fn mutex_guard_borrow<'a, R: RawMutex, T: Facet<'a>>(this: PtrConst) -> PtrConst {
    unsafe {
        let guard = this.get::<MutexGuard<'_, R, T>>();
        let data: &T = guard;
        PtrConst::new(NonNull::from(data).as_ptr())
    }
}

unsafe fn mutex_guard_drop_impl<R: RawMutex, T>(ox: OxPtrMut) {
    unsafe {
        core::ptr::drop_in_place(
            ox.ptr().as_ptr::<MutexGuard<'_, R, T>>() as *mut MutexGuard<'_, R, T>
        )
    }
}

unsafe impl<'a, R: RawMutex + 'a, T: Facet<'a>> Facet<'a> for MutexGuard<'a, R, T> {
    const SHAPE: &'static Shape = &const {
        ShapeBuilder::for_sized::<Self>("MutexGuard")
            .decl_id(DeclId::new(decl_id_hash("#lock_api#MutexGuard")))
            .type_name(type_name_mutex_guard::<T>)
            .vtable_indirect(&VTableIndirect::EMPTY)
            .type_ops_indirect(
                &const {
                    TypeOpsIndirect {
                        drop_in_place: mutex_guard_drop_impl::<R, T>,
                        default_in_place: None,
                        clone_into: None,
                        is_truthy: None,
                    }
                },
            )
            .ty(Type::User(UserType::Opaque))
            .def(Def::Pointer(PointerDef {
                vtable: &const {
                    PointerVTable {
                        borrow_fn: Some(mutex_guard_borrow::<R, T>),
                        ..PointerVTable::new()
                    }
                },
                pointee: Some(T::SHAPE),
                weak: None,
                strong: None,
                flags: PointerFlags::EMPTY,
                known: None,
            }))
            .type_params(&[TypeParam {
                name: "T",
                shape: T::SHAPE,
            }])
            .inner(T::SHAPE)
            // MutexGuard<T> is invariant w.r.t. T (provides mutable access)
            .variance(VarianceDesc {
                base: Variance::Bivariant,
                deps: &const { [VarianceDep::invariant(T::SHAPE)] },
            })
            .build()
    };
}

// ============================================================================
// RwLockReadGuard<'a, R, T> Implementation
// ============================================================================

fn type_name_rwlock_read_guard<'a, T: Facet<'a>>(
    _shape: &'static Shape,
    f: &mut core::fmt::Formatter<'_>,
    opts: TypeNameOpts,
) -> core::fmt::Result {
    write!(f, "RwLockReadGuard")?;
    if let Some(opts) = opts.for_children() {
        write!(f, "<")?;
        T::SHAPE.write_type_name(f, opts)?;
        write!(f, ">")?;
    } else {
        write!(f, "<\u{2026}>")?;
    }
    Ok(())
}

unsafe extern "C" fn rwlock_read_guard_borrow<'a, R: RawRwLock, T: Facet<'a>>(
    this: PtrConst,
) -> PtrConst {
    unsafe {
        let guard = this.get::<RwLockReadGuard<'_, R, T>>();
        let data: &T = guard;
        PtrConst::new(NonNull::from(data).as_ptr())
    }
}

unsafe fn rwlock_read_guard_drop_impl<R: RawRwLock, T>(ox: OxPtrMut) {
    unsafe {
        core::ptr::drop_in_place(
            ox.ptr().as_ptr::<RwLockReadGuard<'_, R, T>>() as *mut RwLockReadGuard<'_, R, T>
        )
    }
}

unsafe impl<'a, R: RawRwLock + 'a, T: Facet<'a>> Facet<'a> for RwLockReadGuard<'a, R, T> {
    const SHAPE: &'static Shape = &const {
        ShapeBuilder::for_sized::<Self>("RwLockReadGuard")
            .decl_id(DeclId::new(decl_id_hash("#lock_api#RwLockReadGuard")))
            .type_name(type_name_rwlock_read_guard::<T>)
            .vtable_indirect(&VTableIndirect::EMPTY)
            .type_ops_indirect(
                &const {
                    TypeOpsIndirect {
                        drop_in_place: rwlock_read_guard_drop_impl::<R, T>,
                        default_in_place: None,
                        clone_into: None,
                        is_truthy: None,
                    }
                },
            )
            .ty(Type::User(UserType::Opaque))
            .def(Def::Pointer(PointerDef {
                vtable: &const {
                    PointerVTable {
                        borrow_fn: Some(rwlock_read_guard_borrow::<R, T>),
                        ..PointerVTable::new()
                    }
                },
                pointee: Some(T::SHAPE),
                weak: None,
                strong: None,
                flags: PointerFlags::EMPTY,
                known: None,
            }))
            .type_params(&[TypeParam {
                name: "T",
                shape: T::SHAPE,
            }])
            .inner(T::SHAPE)
            // RwLockReadGuard<T> is covariant w.r.t. T (only provides shared access)
            .variance(VarianceDesc {
                base: Variance::Bivariant,
                deps: &const { [VarianceDep::covariant(T::SHAPE)] },
            })
            .build()
    };
}

// ============================================================================
// RwLockWriteGuard<'a, R, T> Implementation
// ============================================================================

fn type_name_rwlock_write_guard<'a, T: Facet<'a>>(
    _shape: &'static Shape,
    f: &mut core::fmt::Formatter<'_>,
    opts: TypeNameOpts,
) -> core::fmt::Result {
    write!(f, "RwLockWriteGuard")?;
    if let Some(opts) = opts.for_children() {
        write!(f, "<")?;
        T::SHAPE.write_type_name(f, opts)?;
        write!(f, ">")?;
    } else {
        write!(f, "<\u{2026}>")?;
    }
    Ok(())
}

unsafe extern "C" fn rwlock_write_guard_borrow<'a, R: RawRwLock, T: Facet<'a>>(
    this: PtrConst,
) -> PtrConst {
    unsafe {
        let guard = this.get::<RwLockWriteGuard<'_, R, T>>();
        let data: &T = guard;
        PtrConst::new(NonNull::from(data).as_ptr())
    }
}

unsafe fn rwlock_write_guard_drop_impl<R: RawRwLock, T>(ox: OxPtrMut) {
    unsafe {
        core::ptr::drop_in_place(
            ox.ptr().as_ptr::<RwLockWriteGuard<'_, R, T>>() as *mut RwLockWriteGuard<'_, R, T>
        )
    }
}

unsafe impl<'a, R: RawRwLock + 'a, T: Facet<'a>> Facet<'a> for RwLockWriteGuard<'a, R, T> {
    const SHAPE: &'static Shape = &const {
        ShapeBuilder::for_sized::<Self>("RwLockWriteGuard")
            .decl_id(DeclId::new(decl_id_hash("#lock_api#RwLockWriteGuard")))
            .type_name(type_name_rwlock_write_guard::<T>)
            .vtable_indirect(&VTableIndirect::EMPTY)
            .type_ops_indirect(
                &const {
                    TypeOpsIndirect {
                        drop_in_place: rwlock_write_guard_drop_impl::<R, T>,
                        default_in_place: None,
                        clone_into: None,
                        is_truthy: None,
                    }
                },
            )
            .ty(Type::User(UserType::Opaque))
            .def(Def::Pointer(PointerDef {
                vtable: &const {
                    PointerVTable {
                        borrow_fn: Some(rwlock_write_guard_borrow::<R, T>),
                        ..PointerVTable::new()
                    }
                },
                pointee: Some(T::SHAPE),
                weak: None,
                strong: None,
                flags: PointerFlags::EMPTY,
                known: None,
            }))
            .type_params(&[TypeParam {
                name: "T",
                shape: T::SHAPE,
            }])
            .inner(T::SHAPE)
            // RwLockWriteGuard<T> is invariant w.r.t. T (provides mutable access)
            .variance(VarianceDesc {
                base: Variance::Bivariant,
                deps: &const { [VarianceDep::invariant(T::SHAPE)] },
            })
            .build()
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::String;
    use parking_lot::{RawMutex as ParkingLotRawMutex, RawRwLock as ParkingLotRawRwLock};

    // Type aliases for testing with parking_lot's raw lock implementations
    type TestMutex<T> = Mutex<ParkingLotRawMutex, T>;
    type TestRwLock<T> = RwLock<ParkingLotRawRwLock, T>;

    // ========================================================================
    // Shape verification tests
    // ========================================================================

    #[test]
    fn test_mutex_shape() {
        facet_testhelpers::setup();

        let shape = <TestMutex<i32>>::SHAPE;
        assert_eq!(shape.type_identifier, "Mutex");

        // Verify type params
        let [type_param] = shape.type_params else {
            panic!("Mutex should have 1 type param");
        };
        assert_eq!(type_param.name, "T");
        assert_eq!(type_param.shape, i32::SHAPE);
    }

    #[test]
    fn test_rwlock_shape() {
        facet_testhelpers::setup();

        let shape = <TestRwLock<String>>::SHAPE;
        assert_eq!(shape.type_identifier, "RwLock");

        // Verify type params
        let [type_param] = shape.type_params else {
            panic!("RwLock should have 1 type param");
        };
        assert_eq!(type_param.name, "T");
        assert_eq!(type_param.shape, String::SHAPE);
    }

    #[test]
    fn test_mutex_guard_shape() {
        facet_testhelpers::setup();

        let shape = <MutexGuard<'_, ParkingLotRawMutex, i32>>::SHAPE;
        assert_eq!(shape.type_identifier, "MutexGuard");

        let [type_param] = shape.type_params else {
            panic!("MutexGuard should have 1 type param");
        };
        assert_eq!(type_param.name, "T");
    }

    #[test]
    fn test_rwlock_read_guard_shape() {
        facet_testhelpers::setup();

        let shape = <RwLockReadGuard<'_, ParkingLotRawRwLock, i32>>::SHAPE;
        assert_eq!(shape.type_identifier, "RwLockReadGuard");

        let [type_param] = shape.type_params else {
            panic!("RwLockReadGuard should have 1 type param");
        };
        assert_eq!(type_param.name, "T");
    }

    #[test]
    fn test_rwlock_write_guard_shape() {
        facet_testhelpers::setup();

        let shape = <RwLockWriteGuard<'_, ParkingLotRawRwLock, i32>>::SHAPE;
        assert_eq!(shape.type_identifier, "RwLockWriteGuard");

        let [type_param] = shape.type_params else {
            panic!("RwLockWriteGuard should have 1 type param");
        };
        assert_eq!(type_param.name, "T");
    }

    // ========================================================================
    // VTable presence tests
    // ========================================================================

    #[test]
    fn test_mutex_vtable() {
        facet_testhelpers::setup();

        let shape = <TestMutex<i32>>::SHAPE;
        let pointer_def = shape
            .def
            .into_pointer()
            .expect("Mutex should be a pointer type");

        // Mutex should have lock_fn and new_into_fn
        assert!(
            pointer_def.vtable.lock_fn.is_some(),
            "Mutex should have lock_fn"
        );
        assert!(
            pointer_def.vtable.new_into_fn.is_some(),
            "Mutex should have new_into_fn"
        );

        // Mutex should NOT have read_fn or write_fn (those are for RwLock)
        assert!(
            pointer_def.vtable.read_fn.is_none(),
            "Mutex should not have read_fn"
        );
        assert!(
            pointer_def.vtable.write_fn.is_none(),
            "Mutex should not have write_fn"
        );

        // Verify flags
        assert!(
            pointer_def.flags.contains(PointerFlags::LOCK),
            "Mutex should have LOCK flag"
        );
        assert_eq!(pointer_def.known, Some(KnownPointer::Mutex));
    }

    #[test]
    fn test_rwlock_vtable() {
        facet_testhelpers::setup();

        let shape = <TestRwLock<i32>>::SHAPE;
        let pointer_def = shape
            .def
            .into_pointer()
            .expect("RwLock should be a pointer type");

        // RwLock should have read_fn, write_fn, and new_into_fn
        assert!(
            pointer_def.vtable.read_fn.is_some(),
            "RwLock should have read_fn"
        );
        assert!(
            pointer_def.vtable.write_fn.is_some(),
            "RwLock should have write_fn"
        );
        assert!(
            pointer_def.vtable.new_into_fn.is_some(),
            "RwLock should have new_into_fn"
        );

        // RwLock should NOT have lock_fn (that's for Mutex)
        assert!(
            pointer_def.vtable.lock_fn.is_none(),
            "RwLock should not have lock_fn"
        );

        // Verify flags
        assert!(
            pointer_def.flags.contains(PointerFlags::LOCK),
            "RwLock should have LOCK flag"
        );
        assert_eq!(pointer_def.known, Some(KnownPointer::RwLock));
    }

    #[test]
    fn test_guard_vtables_have_borrow_fn() {
        facet_testhelpers::setup();

        // MutexGuard
        let mutex_guard_shape = <MutexGuard<'_, ParkingLotRawMutex, i32>>::SHAPE;
        let mutex_guard_def = mutex_guard_shape
            .def
            .into_pointer()
            .expect("MutexGuard should be a pointer type");
        assert!(
            mutex_guard_def.vtable.borrow_fn.is_some(),
            "MutexGuard should have borrow_fn"
        );

        // RwLockReadGuard
        let read_guard_shape = <RwLockReadGuard<'_, ParkingLotRawRwLock, i32>>::SHAPE;
        let read_guard_def = read_guard_shape
            .def
            .into_pointer()
            .expect("RwLockReadGuard should be a pointer type");
        assert!(
            read_guard_def.vtable.borrow_fn.is_some(),
            "RwLockReadGuard should have borrow_fn"
        );

        // RwLockWriteGuard
        let write_guard_shape = <RwLockWriteGuard<'_, ParkingLotRawRwLock, i32>>::SHAPE;
        let write_guard_def = write_guard_shape
            .def
            .into_pointer()
            .expect("RwLockWriteGuard should be a pointer type");
        assert!(
            write_guard_def.vtable.borrow_fn.is_some(),
            "RwLockWriteGuard should have borrow_fn"
        );
    }

    // ========================================================================
    // Functional tests
    // ========================================================================

    #[test]
    fn test_mutex_lock_and_access() {
        facet_testhelpers::setup();

        let mutex = TestMutex::new(42i32);

        // Get the shape and pointer def
        let shape = <TestMutex<i32>>::SHAPE;
        let pointer_def = shape.def.into_pointer().unwrap();
        let lock_fn = pointer_def.vtable.lock_fn.unwrap();

        // Lock the mutex using the vtable
        let mutex_ptr = PtrConst::new(&mutex as *const _ as *const u8);
        let lock_result = unsafe { lock_fn(mutex_ptr) }.expect("Lock should succeed");

        // Access the data through the lock result
        let data_ptr = lock_result.data();
        let value = unsafe { data_ptr.as_const().get::<i32>() };
        assert_eq!(*value, 42);

        // Lock is released when lock_result is dropped
        drop(lock_result);

        // Verify we can lock again (proves the lock was released)
        let lock_result2 = unsafe { lock_fn(mutex_ptr) }.expect("Second lock should succeed");
        drop(lock_result2);
    }

    #[test]
    fn test_rwlock_read_access() {
        facet_testhelpers::setup();

        let rwlock = TestRwLock::new(String::from("hello"));

        let shape = <TestRwLock<String>>::SHAPE;
        let pointer_def = shape.def.into_pointer().unwrap();
        let read_fn = pointer_def.vtable.read_fn.unwrap();

        let rwlock_ptr = PtrConst::new(&rwlock as *const _ as *const u8);

        // Acquire read lock
        let read_result = unsafe { read_fn(rwlock_ptr) }.expect("Read lock should succeed");

        // Access the data - ReadLockResult::data() returns &PtrConst directly
        let data_ptr = read_result.data();
        let value = unsafe { data_ptr.get::<String>() };
        assert_eq!(value.as_str(), "hello");

        drop(read_result);
    }

    #[test]
    fn test_rwlock_write_access() {
        facet_testhelpers::setup();

        let rwlock = TestRwLock::new(100i32);

        let shape = <TestRwLock<i32>>::SHAPE;
        let pointer_def = shape.def.into_pointer().unwrap();
        let write_fn = pointer_def.vtable.write_fn.unwrap();

        let rwlock_ptr = PtrConst::new(&rwlock as *const _ as *const u8);

        // Acquire write lock
        let write_result = unsafe { write_fn(rwlock_ptr) }.expect("Write lock should succeed");

        // Modify the data through the lock
        let data_ptr = write_result.data();
        unsafe {
            *data_ptr.as_mut_ptr::<i32>() = 200;
        }

        drop(write_result);

        // Verify the modification persisted
        let read_fn = pointer_def.vtable.read_fn.unwrap();
        let read_result = unsafe { read_fn(rwlock_ptr) }.expect("Read lock should succeed");
        // ReadLockResult::data() returns &PtrConst directly
        let value = unsafe { read_result.data().get::<i32>() };
        assert_eq!(*value, 200);
    }

    #[test]
    fn test_mutex_multiple_read_locks_blocked() {
        facet_testhelpers::setup();

        // This test verifies the basic mutex behavior (exclusive access)
        let mutex = TestMutex::new(42i32);

        let shape = <TestMutex<i32>>::SHAPE;
        let pointer_def = shape.def.into_pointer().unwrap();
        let lock_fn = pointer_def.vtable.lock_fn.unwrap();

        let mutex_ptr = PtrConst::new(&mutex as *const _ as *const u8);

        // First lock
        let lock1 = unsafe { lock_fn(mutex_ptr) }.expect("First lock should succeed");

        // The mutex is now held - in a single-threaded test, we can't test blocking,
        // but we can verify the lock was acquired and data is accessible
        let value = unsafe { lock1.data().as_const().get::<i32>() };
        assert_eq!(*value, 42);

        // Release the lock
        drop(lock1);
    }
}