shape-value 0.2.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
//! 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);
        }
    }
}

// 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);
        }
    }
}