shape-value 0.3.0

NaN-boxed value representation and heap types for Shape
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
//! Typed contiguous array for v2 runtime.
//!
//! `TypedArray<T>` is a 24-byte `#[repr(C)]` heap object with a `HeapHeader`,
//! a pointer to a contiguous `T` buffer, length, and capacity. The compiler
//! monomorphizes: `Array<number>` and `Array<i32>` are different `TypedArray`
//! instantiations with no element-level type checking.
//!
//! ## Memory layout (24 bytes)
//!
//! ```text
//! Offset  Size  Field
//! ------  ----  -----
//!   0       8   header (HeapHeader — refcount at offset 0)
//!   8       8   data (*mut T — pointer to contiguous T buffer)
//!  16       4   len (element count)
//!  20       4   cap (allocated capacity)
//! ```

use super::heap_header::{HeapHeader, HEAP_KIND_V2_TYPED_ARRAY};
use std::alloc::{Layout, alloc, dealloc, realloc};
use std::ptr;

/// Typed contiguous array with refcounted header.
///
/// Allocated on the heap via raw allocator. The `data` pointer points to a
/// separate allocation holding `cap` elements of type `T`.
#[repr(C)]
pub struct TypedArray<T> {
    /// 8-byte v2 heap header (refcount at offset 0).
    pub header: HeapHeader,
    /// Pointer to contiguous T buffer.
    pub data: *mut T,
    /// Number of elements currently stored.
    pub len: u32,
    /// Allocated capacity in number of elements.
    pub cap: u32,
}

// Compile-time size assertion.
const _: () = {
    assert!(std::mem::size_of::<TypedArray<f64>>() == 24);
    assert!(std::mem::size_of::<TypedArray<i32>>() == 24);
    assert!(std::mem::size_of::<TypedArray<u8>>() == 24);
    // Wave 2 Agent A1 (2026-05-14) — F32 + Char scalar monomorphizations.
    assert!(std::mem::size_of::<TypedArray<f32>>() == 24);
    assert!(std::mem::size_of::<TypedArray<char>>() == 24);
};

impl<T: Copy> TypedArray<T> {
    /// Allocate a new empty TypedArray with capacity 0.
    ///
    /// Returns a raw pointer to the heap-allocated array. The caller is
    /// responsible for eventually calling `drop_array` to free it.
    pub fn new() -> *mut Self {
        Self::with_capacity(0)
    }

    /// Allocate a new TypedArray with the given capacity.
    ///
    /// Returns a raw pointer to the heap-allocated array.
    pub fn with_capacity(cap: u32) -> *mut Self {
        let layout = Layout::new::<Self>();
        let ptr = unsafe { alloc(layout) as *mut Self };
        assert!(!ptr.is_null(), "allocation failed for TypedArray");

        let data = if cap > 0 {
            let data_layout = Layout::array::<T>(cap as usize).expect("invalid array layout");
            let data_ptr = unsafe { alloc(data_layout) as *mut T };
            assert!(!data_ptr.is_null(), "allocation failed for TypedArray data");
            data_ptr
        } else {
            ptr::null_mut()
        };

        unsafe {
            ptr::write(
                ptr,
                Self {
                    header: HeapHeader::new(HEAP_KIND_V2_TYPED_ARRAY),
                    data,
                    len: 0,
                    cap,
                },
            );
        }

        ptr
    }

    /// Create a TypedArray from a slice, copying all elements.
    pub fn from_slice(slice: &[T]) -> *mut Self {
        let len = slice.len() as u32;
        let ptr = Self::with_capacity(len);
        unsafe {
            if len > 0 {
                ptr::copy_nonoverlapping(slice.as_ptr(), (*ptr).data, slice.len());
            }
            (*ptr).len = len;
        }
        ptr
    }

    /// Get an element by index, returning `None` if out of bounds.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn get(this: *const Self, index: u32) -> Option<T> {
        unsafe {
            if index >= (*this).len {
                None
            } else {
                Some(ptr::read((*this).data.add(index as usize)))
            }
        }
    }

    /// Get an element by index without bounds checking.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`, and `index` must
    /// be less than the array's length.
    #[inline]
    pub unsafe fn get_unchecked(this: *const Self, index: u32) -> T {
        unsafe { ptr::read((*this).data.add(index as usize)) }
    }

    /// Set an element by index. Panics if out of bounds.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn set(this: *mut Self, index: u32, val: T) {
        unsafe {
            assert!(
                index < (*this).len,
                "TypedArray::set index {} out of bounds (len {})",
                index,
                (*this).len
            );
            ptr::write((*this).data.add(index as usize), val);
        }
    }

    /// Push an element, growing the buffer if necessary (doubling strategy).
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    pub unsafe fn push(this: *mut Self, val: T) {
        unsafe {
            let arr = &mut *this;
            if arr.len == arr.cap {
                Self::grow(this);
            }
            let arr = &mut *this;
            ptr::write(arr.data.add(arr.len as usize), val);
            arr.len += 1;
        }
    }

    /// Pop the last element, returning `None` if empty.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    pub unsafe fn pop(this: *mut Self) -> Option<T> {
        unsafe {
            let arr = &mut *this;
            if arr.len == 0 {
                None
            } else {
                arr.len -= 1;
                Some(ptr::read(arr.data.add(arr.len as usize)))
            }
        }
    }

    /// Get the number of elements.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn len(this: *const Self) -> u32 {
        unsafe { (*this).len }
    }

    /// Get the allocated capacity.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn capacity(this: *const Self) -> u32 {
        unsafe { (*this).cap }
    }

    /// Check if the array is empty.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn is_empty(this: *const Self) -> bool {
        unsafe { (*this).len == 0 }
    }

    /// Get the elements as a slice.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn as_slice<'a>(this: *const Self) -> &'a [T] {
        unsafe {
            if (*this).len == 0 {
                &[]
            } else {
                std::slice::from_raw_parts((*this).data, (*this).len as usize)
            }
        }
    }

    /// Get the elements as a mutable slice.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn as_mut_slice<'a>(this: *mut Self) -> &'a mut [T] {
        unsafe {
            if (*this).len == 0 {
                &mut []
            } else {
                std::slice::from_raw_parts_mut((*this).data, (*this).len as usize)
            }
        }
    }

    /// Deallocate the array and its data buffer.
    ///
    /// # Safety
    /// `ptr` must point to a `TypedArray<T>` that was allocated by this module.
    /// After calling this, `ptr` is invalid.
    pub unsafe fn drop_array(ptr: *mut Self) {
        unsafe {
            let arr = &*ptr;
            // Free the data buffer if it was allocated.
            if arr.cap > 0 && !arr.data.is_null() {
                let data_layout =
                    Layout::array::<T>(arr.cap as usize).expect("invalid array layout");
                dealloc(arr.data as *mut u8, data_layout);
            }
            // Free the TypedArray struct itself.
            let layout = Layout::new::<Self>();
            dealloc(ptr as *mut u8, layout);
        }
    }

    /// Grow the data buffer (doubling strategy, minimum 4).
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    unsafe fn grow(this: *mut Self) {
        unsafe {
            let arr = &mut *this;
            let new_cap = if arr.cap == 0 {
                4
            } else {
                arr.cap.checked_mul(2).expect("capacity overflow")
            };
            let new_layout = Layout::array::<T>(new_cap as usize).expect("invalid array layout");

            let new_data = if arr.cap == 0 || arr.data.is_null() {
                alloc(new_layout) as *mut T
            } else {
                let old_layout =
                    Layout::array::<T>(arr.cap as usize).expect("invalid array layout");
                realloc(arr.data as *mut u8, old_layout, new_layout.size()) as *mut T
            };
            assert!(!new_data.is_null(), "reallocation failed for TypedArray");

            arr.data = new_data;
            arr.cap = new_cap;
        }
    }
}

/// Heap-element-aware drop dispatch for `TypedArray<*const T>` where `T:
/// HeapElement`.
///
/// Per ADR-006 §2.7.24 Q25.A SUPERSEDED + R20 S2-prime audit deliverable (b)
/// §4.1.B decision: `drop_array_heap` walks the element buffer and calls
/// `T::release_elem(elem_ptr)` for each stored pointer, then frees the data
/// buffer + the TypedArray struct itself. Per-T dispatch is monomorphized at
/// compile time via the `HeapElement` trait — no runtime `NativeKind` probe.
///
/// Pairs with the POD-element `drop_array` for `T: Copy` (above). Callers
/// pick at compile time based on whether the element type is POD (plain
/// scalar like f64/i64) or HeapHeader-equipped (`*const StringObj` /
/// `*const DecimalObj` / ...).
impl<T: super::heap_element::HeapElement> TypedArray<*const T> {
    /// Deallocate the array, releasing per-element shares via
    /// `T::release_elem`, then freeing the data buffer + the struct.
    ///
    /// # Safety
    /// `ptr` must point to a `TypedArray<*const T>` that was allocated by
    /// this module. Each stored `*const T` must be a valid pointer to a
    /// live `T` allocation with at least one refcount share owned by this
    /// array. After this call, `ptr` is invalid.
    pub unsafe fn drop_array_heap(ptr: *mut Self) {
        unsafe {
            let arr = &*ptr;
            if arr.cap > 0 && !arr.data.is_null() {
                // Walk element buffer; release per-element shares.
                for i in 0..arr.len {
                    let elem_ptr = ptr::read(arr.data.add(i as usize));
                    T::release_elem(elem_ptr);
                }
                // Free the data buffer.
                let data_layout = Layout::array::<*const T>(arr.cap as usize)
                    .expect("invalid array layout");
                dealloc(arr.data as *mut u8, data_layout);
            }
            // Free the TypedArray struct itself.
            let layout = Layout::new::<Self>();
            dealloc(ptr as *mut u8, layout);
        }
    }
}

// ── Element-type discriminants — canonical home ──────────────────────────────
//
// The compile-time element type `T` of a `TypedArray<T>` is preserved at
// runtime in the `_pad` byte (offset 7) of the `HeapHeader`. The bytecode
// compiler / VM allocation handlers stamp this byte immediately after
// `with_capacity`; `retain_v2_typed_array` / `release_v2_typed_array` below
// (and the `shape-vm` consumer paths in `v2_handlers/v2_array_detect.rs`,
// re-exporting these constants) read it to pick the monomorphized
// `drop_array` / `drop_array_heap`.
//
// This is the *canonical* definition; `shape-vm::executor::v2_handlers::
// v2_array_detect` re-exports it via `pub use`. r5c-2-β-δ-(α): moved here
// from `v2_array_detect` so the kind-blind release function below — needed
// by the 4 `Ptr(HeapKind::TypedArray)` lockstep dispatch tables, two of
// which live in this `shape-value` crate (`kinded_slot.rs`, `closure_layout.
// rs`, `heap_value.rs`) — can dispatch without a constant duplicated across
// the `shape-vm` crate boundary.

/// `_pad`-byte discriminant for an unstamped / unknown element type.
pub const ELEM_TYPE_UNKNOWN: u8 = 0;
/// `_pad`-byte discriminant for `TypedArray<f64>`.
pub const ELEM_TYPE_F64: u8 = 1;
/// `_pad`-byte discriminant for `TypedArray<i64>`.
pub const ELEM_TYPE_I64: u8 = 2;
/// `_pad`-byte discriminant for `TypedArray<i32>`.
pub const ELEM_TYPE_I32: u8 = 3;
/// `_pad`-byte discriminant for `TypedArray<u8>` carrying `bool` elements.
pub const ELEM_TYPE_BOOL: u8 = 4;
/// `_pad`-byte discriminant for `TypedArray<i8>`.
pub const ELEM_TYPE_I8: u8 = 5;
/// `_pad`-byte discriminant for `TypedArray<u8>` carrying `u8` elements.
pub const ELEM_TYPE_U8: u8 = 6;
/// `_pad`-byte discriminant for `TypedArray<i16>`.
pub const ELEM_TYPE_I16: u8 = 7;
/// `_pad`-byte discriminant for `TypedArray<u16>`.
pub const ELEM_TYPE_U16: u8 = 8;
/// `_pad`-byte discriminant for `TypedArray<u32>`.
pub const ELEM_TYPE_U32: u8 = 9;
// Discriminant 10 reserved for `Array<u64>` (deferred — see v2_array_detect).
/// `_pad`-byte discriminant for `TypedArray<f32>`.
pub const ELEM_TYPE_F32: u8 = 11;
/// `_pad`-byte discriminant for `TypedArray<char>`.
pub const ELEM_TYPE_CHAR: u8 = 12;
/// `_pad`-byte discriminant for `TypedArray<*const StringObj>`.
pub const ELEM_TYPE_STRING: u8 = 13;
/// `_pad`-byte discriminant for `TypedArray<*const DecimalObj>`.
pub const ELEM_TYPE_DECIMAL: u8 = 14;
/// `_pad`-byte discriminant for `TypedArray<*const TypedObjectStorage>`.
pub const ELEM_TYPE_TYPED_OBJECT: u8 = 15;

/// Read the element-type discriminant stamped in the `_pad` byte (offset 7).
///
/// # Safety
/// `ptr` must point to a live `TypedArray<T>` (HeapHeader at offset 0).
#[inline]
pub unsafe fn read_elem_type(ptr: *const u8) -> u8 {
    unsafe { *ptr.add(7) }
}

/// Retain (bump the refcount of) a v2-raw `*mut TypedArray<T>` carrier.
///
/// This is the retain half of the `NativeKind::Ptr(HeapKind::TypedArray)`
/// dispatch arm shared by the four lockstep clone/drop tables (VM stack
/// `clone_with_kind`, `KindedSlot::clone`, `SharedCell::clone`,
/// `TypedObjectStorage` field clone). The element type is irrelevant for a
/// retain — only the `HeapHeader` refcount at offset 0 is touched.
///
/// # Safety
/// `ptr` must be a non-null `*mut TypedArray<T>` produced by this module's
/// allocator (`with_capacity` / `with_capacity_generic` / `from_slice`).
#[inline]
pub unsafe fn retain_v2_typed_array(ptr: *mut u8) {
    unsafe { super::refcount::v2_retain(ptr as *const HeapHeader) };
}

/// Release one refcount share of a v2-raw `*mut TypedArray<T>` carrier; on
/// the last share, read the stamped element type and free the array via the
/// matching monomorphized `drop_array` / `drop_array_heap`.
///
/// This is the release half of the `NativeKind::Ptr(HeapKind::TypedArray)`
/// dispatch arm. POD element kinds (`f64` / `i64` / `i32` / `i8` / `u8` /
/// `i16` / `u16` / `u32` / `f32` / `char` / `bool`) route to `drop_array`;
/// the heap-element kinds (`String` / `Decimal` / `TypedObject`) route to
/// `drop_array_heap`, which walks the buffer releasing per-element shares.
///
/// # Safety
/// `ptr` must be a non-null `*mut TypedArray<T>` produced by this module's
/// allocator, with `T` matching the stamped `_pad` discriminant, and the
/// caller must own exactly one refcount share being retired here. After the
/// last share is retired the pointer is invalid.
pub unsafe fn release_v2_typed_array(ptr: *mut u8) {
    unsafe {
        if !super::refcount::v2_release(ptr as *const HeapHeader) {
            return;
        }
        // Refcount reached zero — this thread owns the deallocation.
        match read_elem_type(ptr) {
            ELEM_TYPE_F64 => TypedArray::<f64>::drop_array(ptr as *mut TypedArray<f64>),
            ELEM_TYPE_I64 => TypedArray::<i64>::drop_array(ptr as *mut TypedArray<i64>),
            ELEM_TYPE_I32 => TypedArray::<i32>::drop_array(ptr as *mut TypedArray<i32>),
            ELEM_TYPE_BOOL | ELEM_TYPE_U8 => {
                TypedArray::<u8>::drop_array(ptr as *mut TypedArray<u8>)
            }
            ELEM_TYPE_I8 => TypedArray::<i8>::drop_array(ptr as *mut TypedArray<i8>),
            ELEM_TYPE_I16 => TypedArray::<i16>::drop_array(ptr as *mut TypedArray<i16>),
            ELEM_TYPE_U16 => TypedArray::<u16>::drop_array(ptr as *mut TypedArray<u16>),
            ELEM_TYPE_U32 => TypedArray::<u32>::drop_array(ptr as *mut TypedArray<u32>),
            ELEM_TYPE_F32 => TypedArray::<f32>::drop_array(ptr as *mut TypedArray<f32>),
            ELEM_TYPE_CHAR => TypedArray::<char>::drop_array(ptr as *mut TypedArray<char>),
            ELEM_TYPE_STRING => {
                TypedArray::<*const super::string_obj::StringObj>::drop_array_heap(
                    ptr as *mut TypedArray<*const super::string_obj::StringObj>,
                )
            }
            ELEM_TYPE_DECIMAL => {
                TypedArray::<*const super::decimal_obj::DecimalObj>::drop_array_heap(
                    ptr as *mut TypedArray<*const super::decimal_obj::DecimalObj>,
                )
            }
            ELEM_TYPE_TYPED_OBJECT => {
                TypedArray::<*const crate::heap_value::TypedObjectStorage>::drop_array_heap(
                    ptr as *mut TypedArray<*const crate::heap_value::TypedObjectStorage>,
                )
            }
            // An unstamped (`ELEM_TYPE_UNKNOWN`) or unrecognised discriminant
            // at refcount-0 means the producer-side stamp contract was
            // violated. The element-buffer monomorphization is unknown so a
            // typed `drop_array` cannot run; free only the 24-byte struct
            // header (leaking the element buffer is strictly preferable to
            // a misaligned `dealloc` / use-after-free). This is a hard bug
            // upstream — surface it loudly in debug builds.
            other => {
                debug_assert!(
                    false,
                    "release_v2_typed_array: TypedArray at {:p} has unstamped \
                     element-type discriminant {} — producer-side stamp_elem_type \
                     contract violated (ADR-006 §2.7.7)",
                    ptr, other
                );
                let layout = Layout::new::<TypedArray<u8>>();
                dealloc(ptr, layout);
            }
        }
    }
}

// Allocation + size-only operations available for non-Copy element types
// (e.g. `TypedObjectPtr` with manual `Drop`). Per ADR-006 §2.7.24 Q25.B
// SUPERSEDED + Wave 2 Round 3b C2-joint ckpt-1 — `HashMapData<V>` (in
// `crates/shape-value/src/heap_value.rs`) instantiates `TypedArray<V>` for
// `V = TypedObjectPtr` / `TraitObjectPtr` (transparent newtypes with manual
// Drop), which are not `Copy`. The methods here are size/allocation only —
// no `ptr::read` / `ptr::write` that would require `T: Copy` for soundness.
//
// Methods needing element copy semantics (`get_unchecked`, `set`, `push`,
// `pop`, `from_slice`) remain bounded by `T: Copy` in the impl block above;
// non-Copy element types use the per-element-Drop-aware paths in
// `HashMapValueElem::release_typed_array`.
impl<T> TypedArray<T> {
    /// Allocate a new empty TypedArray with capacity 0 — non-Copy variant.
    ///
    /// Returns a raw pointer to the heap-allocated array. The caller is
    /// responsible for eventually freeing it via `HashMapValueElem::
    /// release_typed_array` (for `HashMapData<V>` value buffers) or the
    /// equivalent per-T release path.
    #[doc(alias = "new")]
    pub fn new_generic() -> *mut Self {
        Self::with_capacity_generic(0)
    }

    /// Allocate a new TypedArray with the given capacity — non-Copy variant.
    ///
    /// Returns a raw pointer to the heap-allocated array. No elements are
    /// written; the data buffer is uninitialized memory of length `cap *
    /// size_of::<T>()`.
    #[doc(alias = "with_capacity")]
    pub fn with_capacity_generic(cap: u32) -> *mut Self {
        let layout = Layout::new::<Self>();
        let ptr = unsafe { alloc(layout) as *mut Self };
        assert!(!ptr.is_null(), "allocation failed for TypedArray");

        let data = if cap > 0 {
            let data_layout = Layout::array::<T>(cap as usize).expect("invalid array layout");
            let data_ptr = unsafe { alloc(data_layout) as *mut T };
            assert!(!data_ptr.is_null(), "allocation failed for TypedArray data");
            data_ptr
        } else {
            ptr::null_mut()
        };

        unsafe {
            ptr::write(
                ptr,
                Self {
                    header: HeapHeader::new(HEAP_KIND_V2_TYPED_ARRAY),
                    data,
                    len: 0,
                    cap,
                },
            );
        }

        ptr
    }

    /// Get the number of elements — non-Copy variant.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn len_generic(this: *const Self) -> u32 {
        unsafe { (*this).len }
    }

    /// Get the allocated capacity — non-Copy variant.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn capacity_generic(this: *const Self) -> u32 {
        unsafe { (*this).cap }
    }

    /// Check if the array is empty — non-Copy variant.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn is_empty_generic(this: *const Self) -> bool {
        unsafe { (*this).len == 0 }
    }

    /// Get the elements as a slice — non-Copy variant.
    ///
    /// # Safety
    /// `this` must point to a valid, live `TypedArray<T>`.
    #[inline]
    pub unsafe fn as_slice_generic<'a>(this: *const Self) -> &'a [T] {
        unsafe {
            if (*this).len == 0 {
                &[]
            } else {
                std::slice::from_raw_parts((*this).data, (*this).len as usize)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_size_of_typed_array() {
        assert_eq!(std::mem::size_of::<TypedArray<f64>>(), 24);
        assert_eq!(std::mem::size_of::<TypedArray<i32>>(), 24);
        assert_eq!(std::mem::size_of::<TypedArray<i64>>(), 24);
        assert_eq!(std::mem::size_of::<TypedArray<u8>>(), 24);
    }

    #[test]
    fn test_field_offsets() {
        let arr = TypedArray::<f64>::with_capacity(0);
        unsafe {
            let base = arr as *const u8 as usize;
            let header_offset = &(*arr).header as *const _ as usize - base;
            let data_offset = &(*arr).data as *const _ as usize - base;
            let len_offset = &(*arr).len as *const _ as usize - base;
            let cap_offset = &(*arr).cap as *const _ as usize - base;

            assert_eq!(header_offset, 0);
            assert_eq!(data_offset, 8);
            assert_eq!(len_offset, 16);
            assert_eq!(cap_offset, 20);

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_new_empty() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            assert_eq!(TypedArray::len(arr), 0);
            assert_eq!(TypedArray::capacity(arr), 0);
            assert!(TypedArray::is_empty(arr));
            assert_eq!((*arr).header.kind(), HEAP_KIND_V2_TYPED_ARRAY);
            assert_eq!((*arr).header.get_refcount(), 1);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_with_capacity() {
        let arr = TypedArray::<f64>::with_capacity(16);
        unsafe {
            assert_eq!(TypedArray::len(arr), 0);
            assert_eq!(TypedArray::capacity(arr), 16);
            assert!(TypedArray::is_empty(arr));
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_push_and_get_f64() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            TypedArray::push(arr, 1.0);
            TypedArray::push(arr, 2.5);
            TypedArray::push(arr, 3.14);

            assert_eq!(TypedArray::len(arr), 3);
            assert!(!TypedArray::is_empty(arr));

            assert_eq!(TypedArray::get(arr, 0), Some(1.0));
            assert_eq!(TypedArray::get(arr, 1), Some(2.5));
            assert_eq!(TypedArray::get(arr, 2), Some(3.14));
            assert_eq!(TypedArray::get(arr, 3), None); // out of bounds

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_push_and_get_i32() {
        let arr = TypedArray::<i32>::new();
        unsafe {
            TypedArray::push(arr, 42);
            TypedArray::push(arr, -7);
            TypedArray::push(arr, 0);

            assert_eq!(TypedArray::len(arr), 3);
            assert_eq!(TypedArray::get(arr, 0), Some(42));
            assert_eq!(TypedArray::get(arr, 1), Some(-7));
            assert_eq!(TypedArray::get(arr, 2), Some(0));
            assert_eq!(TypedArray::get(arr, 3), None);

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_push_and_get_i64() {
        let arr = TypedArray::<i64>::new();
        unsafe {
            TypedArray::push(arr, i64::MAX);
            TypedArray::push(arr, i64::MIN);

            assert_eq!(TypedArray::get(arr, 0), Some(i64::MAX));
            assert_eq!(TypedArray::get(arr, 1), Some(i64::MIN));

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_push_and_get_u8_bool() {
        let arr = TypedArray::<u8>::new();
        unsafe {
            TypedArray::push(arr, 1u8); // true
            TypedArray::push(arr, 0u8); // false
            TypedArray::push(arr, 1u8); // true

            assert_eq!(TypedArray::len(arr), 3);
            assert_eq!(TypedArray::get(arr, 0), Some(1));
            assert_eq!(TypedArray::get(arr, 1), Some(0));
            assert_eq!(TypedArray::get(arr, 2), Some(1));

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_get_unchecked() {
        let arr = TypedArray::<f64>::from_slice(&[10.0, 20.0, 30.0]);
        unsafe {
            assert_eq!(TypedArray::get_unchecked(arr, 0), 10.0);
            assert_eq!(TypedArray::get_unchecked(arr, 1), 20.0);
            assert_eq!(TypedArray::get_unchecked(arr, 2), 30.0);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_set() {
        let arr = TypedArray::<f64>::from_slice(&[1.0, 2.0, 3.0]);
        unsafe {
            TypedArray::set(arr, 1, 99.0);
            assert_eq!(TypedArray::get(arr, 1), Some(99.0));

            // Other elements unchanged
            assert_eq!(TypedArray::get(arr, 0), Some(1.0));
            assert_eq!(TypedArray::get(arr, 2), Some(3.0));

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    #[should_panic(expected = "out of bounds")]
    fn test_set_out_of_bounds() {
        let arr = TypedArray::<f64>::from_slice(&[1.0, 2.0]);
        unsafe {
            TypedArray::set(arr, 5, 99.0);
            // Leak is fine in a panic test
        }
    }

    #[test]
    fn test_pop() {
        let arr = TypedArray::<i32>::from_slice(&[10, 20, 30]);
        unsafe {
            assert_eq!(TypedArray::pop(arr), Some(30));
            assert_eq!(TypedArray::len(arr), 2);

            assert_eq!(TypedArray::pop(arr), Some(20));
            assert_eq!(TypedArray::len(arr), 1);

            assert_eq!(TypedArray::pop(arr), Some(10));
            assert_eq!(TypedArray::len(arr), 0);

            assert_eq!(TypedArray::pop(arr), None);
            assert!(TypedArray::is_empty(arr));

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_from_slice() {
        let data = [1.0f64, 2.0, 3.0, 4.0, 5.0];
        let arr = TypedArray::from_slice(&data);
        unsafe {
            assert_eq!(TypedArray::len(arr), 5);
            assert_eq!(TypedArray::capacity(arr), 5);

            for (i, &expected) in data.iter().enumerate() {
                assert_eq!(TypedArray::get(arr, i as u32), Some(expected));
            }

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_from_empty_slice() {
        let arr = TypedArray::<f64>::from_slice(&[]);
        unsafe {
            assert_eq!(TypedArray::len(arr), 0);
            assert_eq!(TypedArray::capacity(arr), 0);
            assert!(TypedArray::is_empty(arr));
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_as_slice() {
        let arr = TypedArray::from_slice(&[10i32, 20, 30]);
        unsafe {
            let s = TypedArray::as_slice(arr);
            assert_eq!(s, &[10, 20, 30]);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_as_mut_slice() {
        let arr = TypedArray::from_slice(&[1.0f64, 2.0, 3.0]);
        unsafe {
            let s = TypedArray::as_mut_slice(arr);
            s[1] = 99.0;
            assert_eq!(TypedArray::get(arr, 1), Some(99.0));
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_as_slice_empty() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            let s = TypedArray::as_slice(arr);
            assert!(s.is_empty());
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_capacity_growth() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            // Start with cap 0, first push should grow to 4
            TypedArray::push(arr, 1.0);
            assert!(TypedArray::capacity(arr) >= 1);

            // Push enough to trigger several doublings
            for i in 2..=20 {
                TypedArray::push(arr, i as f64);
            }
            assert_eq!(TypedArray::len(arr), 20);

            // Verify all values
            for i in 0..20 {
                assert_eq!(TypedArray::get(arr, i), Some((i + 1) as f64));
            }

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_header_kind() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            assert_eq!((*arr).header.kind(), HEAP_KIND_V2_TYPED_ARRAY);
            assert_eq!((*arr).header.get_refcount(), 1);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_drop_safety() {
        // Create and drop many arrays to verify no leaks (under Miri/valgrind).
        unsafe {
            for _ in 0..100 {
                let arr = TypedArray::<f64>::new();
                for i in 0..50 {
                    TypedArray::push(arr, i as f64);
                }
                TypedArray::drop_array(arr);
            }
            // Empty arrays
            for _ in 0..100 {
                let arr = TypedArray::<i32>::new();
                TypedArray::drop_array(arr);
            }
        }
    }

    #[test]
    fn test_get_out_of_bounds_returns_none() {
        let arr = TypedArray::<f64>::new();
        unsafe {
            // Empty array: any index is out of bounds
            assert_eq!(TypedArray::get(arr, 0), None);
            assert_eq!(TypedArray::get(arr, 100), None);
            assert_eq!(TypedArray::get(arr, u32::MAX), None);

            TypedArray::push(arr, 1.0);
            assert_eq!(TypedArray::get(arr, 0), Some(1.0));
            assert_eq!(TypedArray::get(arr, 1), None);

            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_refcount_with_typed_array() {
        use crate::v2::refcount::{v2_get_refcount, v2_retain, v2_release};

        let arr = TypedArray::<f64>::from_slice(&[1.0, 2.0]);
        unsafe {
            let header_ptr = arr as *const HeapHeader;

            assert_eq!(v2_get_refcount(header_ptr), 1);

            v2_retain(header_ptr);
            assert_eq!(v2_get_refcount(header_ptr), 2);

            assert!(!v2_release(header_ptr)); // 2 -> 1
            assert_eq!(v2_get_refcount(header_ptr), 1);

            // Don't call v2_release to 0 here since we use drop_array for cleanup
            TypedArray::drop_array(arr);
        }
    }

    // ──────────────────────────────────────────────────────────────────────
    // drop_array_heap tests per ADR-006 §2.7.24 Q25.A SUPERSEDED + R20
    // S2-prime audit deliverable (b) §4.1.B.
    // ──────────────────────────────────────────────────────────────────────

    #[test]
    fn test_drop_array_heap_string_obj() {
        use crate::v2::string_obj::StringObj;
        unsafe {
            // Allocate a TypedArray<*const StringObj> with capacity 4.
            let arr: *mut TypedArray<*const StringObj> = TypedArray::with_capacity(4);
            // Push 3 StringObj pointers.
            let s1 = StringObj::new("hello");
            let s2 = StringObj::new("world");
            let s3 = StringObj::new("!");
            TypedArray::push(arr, s1 as *const StringObj);
            TypedArray::push(arr, s2 as *const StringObj);
            TypedArray::push(arr, s3 as *const StringObj);
            assert_eq!(TypedArray::len(arr), 3);
            // drop_array_heap releases per-element shares then dealloc the
            // buffer + struct.
            TypedArray::<*const StringObj>::drop_array_heap(arr);
        }
    }

    #[test]
    fn test_drop_array_heap_decimal_obj() {
        use crate::v2::decimal_obj::DecimalObj;
        use rust_decimal::Decimal;
        use rust_decimal::prelude::FromPrimitive;
        unsafe {
            let arr: *mut TypedArray<*const DecimalObj> = TypedArray::with_capacity(4);
            let d1 = DecimalObj::new(Decimal::from_f64(1.5).unwrap());
            let d2 = DecimalObj::new(Decimal::from_f64(2.5).unwrap());
            let d3 = DecimalObj::new(Decimal::ZERO);
            TypedArray::push(arr, d1 as *const DecimalObj);
            TypedArray::push(arr, d2 as *const DecimalObj);
            TypedArray::push(arr, d3 as *const DecimalObj);
            assert_eq!(TypedArray::len(arr), 3);
            TypedArray::<*const DecimalObj>::drop_array_heap(arr);
        }
    }

    #[test]
    fn test_drop_array_heap_empty() {
        use crate::v2::string_obj::StringObj;
        unsafe {
            // Empty TypedArray (no allocated buffer).
            let arr: *mut TypedArray<*const StringObj> = TypedArray::new();
            TypedArray::<*const StringObj>::drop_array_heap(arr);
        }
    }

    // ──────────────────────────────────────────────────────────────────────
    // Wave 2 Agent A1 (2026-05-14) — F32 + Char monomorphization smokes.
    // ──────────────────────────────────────────────────────────────────────

    #[test]
    fn test_size_of_typed_array_f32_char() {
        assert_eq!(std::mem::size_of::<TypedArray<f32>>(), 24);
        assert_eq!(std::mem::size_of::<TypedArray<char>>(), 24);
    }

    #[test]
    fn test_push_and_get_f32() {
        let arr = TypedArray::<f32>::new();
        unsafe {
            TypedArray::push(arr, 1.5_f32);
            TypedArray::push(arr, 2.25_f32);
            TypedArray::push(arr, std::f32::consts::PI);
            assert_eq!(TypedArray::len(arr), 3);
            assert_eq!(TypedArray::get(arr, 0), Some(1.5_f32));
            assert_eq!(TypedArray::get(arr, 1), Some(2.25_f32));
            assert_eq!(TypedArray::get(arr, 2), Some(std::f32::consts::PI));
            assert_eq!(TypedArray::get(arr, 3), None);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_push_and_get_char() {
        let arr = TypedArray::<char>::new();
        unsafe {
            TypedArray::push(arr, 'a');
            TypedArray::push(arr, '');
            TypedArray::push(arr, '👋');
            assert_eq!(TypedArray::len(arr), 3);
            assert_eq!(TypedArray::get(arr, 0), Some('a'));
            assert_eq!(TypedArray::get(arr, 1), Some(''));
            assert_eq!(TypedArray::get(arr, 2), Some('👋'));
            assert_eq!(TypedArray::get(arr, 3), None);
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_from_slice_f32() {
        let data: [f32; 5] = [1.0, 2.0, 3.0, 4.0, 5.0];
        let arr = TypedArray::from_slice(&data);
        unsafe {
            assert_eq!(TypedArray::len(arr), 5);
            for (i, &expected) in data.iter().enumerate() {
                assert_eq!(TypedArray::get(arr, i as u32), Some(expected));
            }
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_from_slice_char() {
        let data = ['h', 'i', '!'];
        let arr = TypedArray::from_slice(&data);
        unsafe {
            assert_eq!(TypedArray::len(arr), 3);
            for (i, &expected) in data.iter().enumerate() {
                assert_eq!(TypedArray::get(arr, i as u32), Some(expected));
            }
            TypedArray::drop_array(arr);
        }
    }

    #[test]
    fn test_drop_array_heap_with_held_share() {
        use crate::v2::refcount::{v2_get_refcount, v2_retain};
        use crate::v2::string_obj::StringObj;
        unsafe {
            // Allocate one StringObj with refcount 2 (one for the array, one held
            // externally). drop_array_heap should decrement to 1, not deallocate.
            let arr: *mut TypedArray<*const StringObj> = TypedArray::with_capacity(2);
            let s = StringObj::new("shared");
            v2_retain(&(*s).header); // refcount = 2
            TypedArray::push(arr, s as *const StringObj);

            TypedArray::<*const StringObj>::drop_array_heap(arr);

            // External share still valid; refcount should be 1.
            assert_eq!(v2_get_refcount(&(*s).header), 1);
            assert_eq!(StringObj::as_str(s), "shared");
            // Clean up.
            StringObj::drop(s);
        }
    }

    // ── r5c-2-β-δ-(α): kind-blind retain / release regression tests ─────────

    /// `retain_v2_typed_array` bumps the on-header refcount; a paired
    /// `release_v2_typed_array` retires it. A POD-element array at refcount
    /// 1 is freed by the single release that drives the count to zero.
    #[test]
    fn release_v2_typed_array_pod_drop_balance() {
        use crate::v2::refcount::v2_get_refcount;
        unsafe {
            let arr = TypedArray::<i64>::with_capacity(4);
            TypedArray::push(arr, 10);
            TypedArray::push(arr, 20);
            TypedArray::push(arr, 30);
            super::stamp_elem_type_for_test(arr as *mut u8, ELEM_TYPE_I64);
            let hdr = arr as *const HeapHeader;
            assert_eq!(v2_get_refcount(hdr), 1);

            // Retain (mirror of the `Ptr(HeapKind::TypedArray)` clone arm).
            retain_v2_typed_array(arr as *mut u8);
            assert_eq!(v2_get_refcount(hdr), 2);

            // Release once — back to 1, NOT freed.
            release_v2_typed_array(arr as *mut u8);
            assert_eq!(v2_get_refcount(hdr), 1);
            // The array is still live and readable.
            assert_eq!(TypedArray::get(arr, 1), Some(20));

            // Final release drives the count to 0 → free (no leak, no
            // double-free; ASAN/miri would flag a misaligned dealloc).
            release_v2_typed_array(arr as *mut u8);
        }
    }

    /// A heap-element array (`TypedArray<*const StringObj>`) released at
    /// refcount 0 must route through `drop_array_heap`, retiring each
    /// element's per-pointer share. An externally-held element share
    /// survives the array's free.
    #[test]
    fn release_v2_typed_array_heap_elem_drop_balance() {
        use crate::v2::refcount::{v2_get_refcount, v2_retain};
        use crate::v2::string_obj::StringObj;
        unsafe {
            let arr = TypedArray::<*const StringObj>::with_capacity(2);
            super::stamp_elem_type_for_test(arr as *mut u8, ELEM_TYPE_STRING);
            let s = StringObj::new("kept");
            v2_retain(&(*s).header); // refcount 2: one for the array, one external.
            TypedArray::push(arr, s as *const StringObj);

            retain_v2_typed_array(arr as *mut u8); // array refcount 2.
            release_v2_typed_array(arr as *mut u8); // → 1, array still live.
            assert_eq!(StringObj::as_str(s), "kept");

            // Final release → array refcount 0 → drop_array_heap walks the
            // buffer, releasing the element's per-pointer share (2 → 1).
            release_v2_typed_array(arr as *mut u8);
            assert_eq!(v2_get_refcount(&(*s).header), 1);
            StringObj::drop(s);
        }
    }

    /// A repeated retain/release cycle (mirror of a closure-captured array
    /// read many times) leaves the refcount balanced — no drift.
    #[test]
    fn release_v2_typed_array_repeated_cycle_balances() {
        use crate::v2::refcount::v2_get_refcount;
        unsafe {
            let arr = TypedArray::<i64>::with_capacity(1);
            TypedArray::push(arr, 99);
            super::stamp_elem_type_for_test(arr as *mut u8, ELEM_TYPE_I64);
            let hdr = arr as *const HeapHeader;
            for _ in 0..1000 {
                retain_v2_typed_array(arr as *mut u8);
                release_v2_typed_array(arr as *mut u8);
            }
            assert_eq!(v2_get_refcount(hdr), 1);
            assert_eq!(TypedArray::get(arr, 0), Some(99));
            release_v2_typed_array(arr as *mut u8);
        }
    }
}

/// Test-only `_pad`-byte element-type stamp. The production stamp lives in
/// `shape-vm`'s `v2_array_detect::stamp_elem_type`; this mirror lets the
/// `shape-value` crate's own unit tests exercise `release_v2_typed_array`'s
/// stamped-element-type dispatch without a `shape-vm` dependency.
#[cfg(test)]
pub(crate) unsafe fn stamp_elem_type_for_test(ptr: *mut u8, elem_type: u8) {
    if ptr.is_null() {
        return;
    }
    unsafe {
        *ptr.add(7) = elem_type;
    }
}