1
//! Core FFI-safe types used across crate boundaries.
2
//!
3
//! This module defines the fundamental types for FFI interop: [`AzString`] (an FFI-safe
4
//! string backed by [`U8Vec`] with destructor-based memory management), [`EmptyStruct`] (a
5
//! non-zero-size unit type), and various `Vec`/`Option` wrappers generated by the
6
//! `impl_vec!` and `impl_option!` macros.
7

            
8
use alloc::{
9
    string::{String, ToString},
10
    vec::Vec,
11
};
12

            
13
use crate::props::basic::ColorU;
14

            
15
// ============================================================================
16
// EmptyStruct type - FFI-safe replacement for ()
17
// ============================================================================
18

            
19
/// FFI-safe void type to replace `()` in Result types.
20
///
21
/// Since `()` (unit type) has zero size, it's not FFI-safe.
22
/// This type provides a minimal 1-byte representation that can be
23
/// safely passed across the C ABI boundary.
24
///
25
/// # Usage
26
/// Instead of `Result<(), Error>`, use `Result<EmptyStruct, Error>`.
27
///
28
/// # Example
29
/// ```ignore
30
/// fn do_something() -> Result<EmptyStruct, MyError> {
31
///     // ... do work ...
32
///     Ok(EmptyStruct::default())
33
/// }
34
/// ```
35
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
36
#[repr(C)]
37
#[derive(Default)]
38
// `_reserved` is a deliberate padding-field name (C-ABI / api.json); cannot rename.
39
#[allow(clippy::pub_underscore_fields)]
40
pub struct EmptyStruct {
41
    /// Reserved byte to ensure the struct has non-zero size.
42
    /// Always initialized to 0.
43
    pub _reserved: u8,
44
}
45

            
46
impl EmptyStruct {
47
    /// Create a new `EmptyStruct` value (equivalent to `()`)
48
    #[must_use]
49
4
    pub const fn new() -> Self {
50
4
        Self { _reserved: 0 }
51
4
    }
52
}
53

            
54
impl From<()> for EmptyStruct {
55
1
    fn from((): ()) -> Self {
56
1
        Self::default()
57
1
    }
58
}
59

            
60
impl From<EmptyStruct> for () {
61
1
    fn from(_: EmptyStruct) -> Self {}
62
}
63

            
64
// ============================================================================
65
// Debug message types
66
// ============================================================================
67

            
68
/// Debug message severity or category for layout diagnostics.
69
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
70
#[repr(C)]
71
#[derive(Default)]
72
pub enum LayoutDebugMessageType {
73
    #[default]
74
    Info,
75
    Warning,
76
    Error,
77
    // Layout-specific categories for filtering
78
    BoxProps,
79
    CssGetter,
80
    /// Block Formatting Context layout
81
    BfcLayout,
82
    /// Inline Formatting Context layout
83
    IfcLayout,
84
    TableLayout,
85
    DisplayType,
86
    PositionCalculation,
87
}
88

            
89
/// A debug message emitted during layout, with severity, text, and source location.
90
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd)]
91
#[repr(C)]
92
pub struct LayoutDebugMessage {
93
    pub message_type: LayoutDebugMessageType,
94
    pub message: AzString,
95
    pub location: AzString,
96
}
97

            
98
impl LayoutDebugMessage {
99
    /// Create a new debug message with automatic caller location tracking
100
    #[track_caller]
101
14945057
    pub fn new(message_type: LayoutDebugMessageType, message: impl Into<String>) -> Self {
102
14945057
        let location = core::panic::Location::caller();
103
14945057
        Self {
104
14945057
            message_type,
105
14945057
            message: AzString::from_string(message.into()),
106
14945057
            location: AzString::from_string(format!(
107
14945057
                "{}:{}:{}",
108
14945057
                location.file(),
109
14945057
                location.line(),
110
14945057
                location.column()
111
14945057
            )),
112
14945057
        }
113
14945057
    }
114

            
115
    /// Helper for Info messages
116
    #[track_caller]
117
12833198
    pub fn info(message: impl Into<String>) -> Self {
118
12833198
        Self::new(LayoutDebugMessageType::Info, message)
119
12833198
    }
120

            
121
    /// Helper for Warning messages
122
    #[track_caller]
123
71907
    pub fn warning(message: impl Into<String>) -> Self {
124
71907
        Self::new(LayoutDebugMessageType::Warning, message)
125
71907
    }
126

            
127
    /// Helper for Error messages
128
    #[track_caller]
129
6
    pub fn error(message: impl Into<String>) -> Self {
130
6
        Self::new(LayoutDebugMessageType::Error, message)
131
6
    }
132

            
133
    /// Helper for `BoxProps` debug messages
134
    #[track_caller]
135
457937
    pub fn box_props(message: impl Into<String>) -> Self {
136
457937
        Self::new(LayoutDebugMessageType::BoxProps, message)
137
457937
    }
138

            
139
    /// Helper for CSS Getter debug messages
140
    #[track_caller]
141
14
    pub fn css_getter(message: impl Into<String>) -> Self {
142
14
        Self::new(LayoutDebugMessageType::CssGetter, message)
143
14
    }
144

            
145
    /// Helper for BFC Layout debug messages
146
    #[track_caller]
147
4
    pub fn bfc_layout(message: impl Into<String>) -> Self {
148
4
        Self::new(LayoutDebugMessageType::BfcLayout, message)
149
4
    }
150

            
151
    /// Helper for IFC Layout debug messages
152
    #[track_caller]
153
1499187
    pub fn ifc_layout(message: impl Into<String>) -> Self {
154
1499187
        Self::new(LayoutDebugMessageType::IfcLayout, message)
155
1499187
    }
156

            
157
    /// Helper for Table Layout debug messages
158
    #[track_caller]
159
15024
    pub fn table_layout(message: impl Into<String>) -> Self {
160
15024
        Self::new(LayoutDebugMessageType::TableLayout, message)
161
15024
    }
162

            
163
    /// Helper for Display Type debug messages
164
    #[track_caller]
165
4
    pub fn display_type(message: impl Into<String>) -> Self {
166
4
        Self::new(LayoutDebugMessageType::DisplayType, message)
167
4
    }
168
}
169

            
170
/// FFI-safe string type backed by [`U8Vec`] with destructor-based memory management.
171
///
172
/// Contents are guaranteed to be valid UTF-8 by all safe constructors.
173
/// Memory ownership is tracked via the inner `U8Vec`'s destructor field.
174
#[repr(C)]
175
pub struct AzString {
176
    pub vec: U8Vec,
177
}
178

            
179
impl_option!(
180
    AzString,
181
    OptionString,
182
    copy = false,
183
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
184
);
185

            
186
static DEFAULT_STR: &str = "";
187

            
188
impl Default for AzString {
189
174387
    fn default() -> Self {
190
174387
        DEFAULT_STR.into()
191
174387
    }
192
}
193

            
194
impl<'a> From<&'a str> for AzString {
195
9603695
    fn from(s: &'a str) -> Self {
196
9603695
        s.to_string().into()
197
9603695
    }
198
}
199

            
200
impl AsRef<str> for AzString {
201
319
    fn as_ref(&self) -> &str {
202
319
        self.as_str()
203
319
    }
204
}
205

            
206
impl core::fmt::Debug for AzString {
207
1103582
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
208
1103582
        self.as_str().fmt(f)
209
1103582
    }
210
}
211

            
212
impl core::fmt::Display for AzString {
213
34871
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
214
34871
        self.as_str().fmt(f)
215
34871
    }
216
}
217

            
218
impl AzString {
219
    #[inline]
220
    #[must_use]
221
2166165
    pub const fn from_const_str(s: &'static str) -> Self {
222
2166165
        Self {
223
2166165
            vec: U8Vec::from_const_slice(s.as_bytes()),
224
2166165
        }
225
2166165
    }
226

            
227
    /// Creates a new `AzString` from a null-terminated C string (const char*).
228
    /// This copies the string data into a new allocation.
229
    ///
230
    /// # Safety
231
    /// - `ptr` must be a valid pointer to a null-terminated UTF-8 string
232
    /// - The string must remain valid for the duration of this call
233
    ///
234
    /// Note: `ptr` is `*const i8` rather than `*const core::ffi::c_char`
235
    /// so the auto-generated FFI signature in `dll_api_internal.rs`
236
    /// (which uses a literal `i8`) matches on every target —
237
    /// `c_char` is `i8` on x86/ARM Apple/Windows/Linux but `u8` on
238
    /// Android, which would otherwise produce a `*const u8 vs *const i8`
239
    /// mismatch at codegen-call sites. We cast internally before
240
    /// handing the pointer to `CStr::from_ptr`.
241
    #[inline]
242
    #[must_use]
243
10
    pub unsafe fn from_c_str(ptr: *const i8) -> Self {
244
        unsafe {
245
10
            if ptr.is_null() {
246
1
                return Self::default();
247
9
            }
248
9
            let c_str = core::ffi::CStr::from_ptr(ptr as *const core::ffi::c_char);
249
9
            let bytes = c_str.to_bytes();
250
9
            Self::copy_from_bytes(bytes.as_ptr(), 0, bytes.len())
251
        }
252
10
    }
253

            
254
    /// Copies bytes from a pointer into a new `AzString`.
255
    /// This is useful for C FFI where you have a char* buffer.
256
    ///
257
    /// Invalid UTF-8 sequences are replaced with U+FFFD to maintain
258
    /// the UTF-8 invariant required by [`as_str()`](Self::as_str).
259
    ///
260
    /// `#[inline]` (2026-06-03 web-lift FIX): forces inlining into the
261
    /// `extern "C" AzString_copyFromBytes` wrapper so there is NO separate
262
    /// C-ABI(X8-sret) → Rust-ABI(X0-sret) boundary call. The lift mis-threads
263
    /// %state across that sret-in-X0 shift (X1/ptr 0x13f80→garbage, X3/len 5→0,
264
    /// empty `AzString`); inlining lets the wrapper do the alloc/memcpy directly
265
    /// with the standard X8-sret ABI the cascade proves works.
266
    #[inline]
267
    #[must_use]
268
21
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
269
21
        let raw = U8Vec::copy_from_bytes(ptr, start, len);
270
        // web-lift FIX (2026-06-03): FAST PATH for already-valid UTF-8 (the common case, incl. all
271
        // ASCII like "Hello") — wrap the U8Vec directly, avoiding the `String::from_utf8_lossy()
272
        // .into_owned()` std sret-in-X0 call that the lift mis-threads (the returned String comes
273
        // back with len=0 → empty AzString). `core::str::from_utf8` returns a `Result<&str,_>` (a
274
        // slice, NOT a by-value struct) so it has no sret to mis-thread. Also a real perf win (no
275
        // 2nd alloc+copy for valid input). Slow path (rare, invalid UTF-8) keeps the lossy replace.
276
21
        if core::str::from_utf8(raw.as_ref()).is_ok() {
277
19
            return Self { vec: raw };
278
2
        }
279
2
        let s = String::from_utf8_lossy(raw.as_ref()).into_owned();
280
2
        Self::from_string(s)
281
21
    }
282

            
283
    #[inline] // web-lift: inline through the sret-in-X0 chain (see copy_from_bytes)
284
    #[must_use]
285
54967249
    pub const fn from_string(s: String) -> Self {
286
54967249
        Self {
287
54967249
            vec: U8Vec::from_vec(s.into_bytes()),
288
54967249
        }
289
54967249
    }
290

            
291
    #[inline]
292
    #[must_use]
293
39540220
    pub fn as_str(&self) -> &str {
294
39540220
        unsafe { core::str::from_utf8_unchecked(self.vec.as_ref()) }
295
39540220
    }
296

            
297
    /// NOTE: CLONES the memory if the memory is external or &'static
298
    /// Moves the memory out if the memory is library-allocated
299
    #[inline]
300
    #[must_use]
301
7527960
    pub fn clone_self(&self) -> Self {
302
7527960
        Self {
303
7527960
            vec: self.vec.clone_self(),
304
7527960
        }
305
7527960
    }
306

            
307
    #[inline]
308
    #[must_use]
309
17477
    pub fn into_library_owned_string(self) -> String {
310
17477
        match self.vec.destructor {
311
            U8VecDestructor::NoDestructor
312
            | U8VecDestructor::External(_)
313
3
            | U8VecDestructor::AlreadyDestroyed => self.as_str().to_string(),
314
            U8VecDestructor::DefaultRust => {
315
17474
                let m = core::mem::ManuallyDrop::new(self);
316
17474
                unsafe { String::from_raw_parts(m.vec.ptr.cast_mut(), m.vec.len, m.vec.cap) }
317
            }
318
        }
319
17477
    }
320

            
321
    #[inline]
322
    #[must_use]
323
54
    pub fn as_bytes(&self) -> &[u8] {
324
54
        self.vec.as_ref()
325
54
    }
326

            
327
    #[inline]
328
    #[must_use]
329
3
    pub fn into_bytes(self) -> U8Vec {
330
3
        let m = core::mem::ManuallyDrop::new(self);
331
3
        U8Vec {
332
3
            ptr: m.vec.ptr,
333
3
            len: m.vec.len,
334
3
            cap: m.vec.cap,
335
3
            destructor: m.vec.destructor,
336
3
        }
337
3
    }
338

            
339
    /// Returns the length of the string in bytes (not including null terminator)
340
    #[inline]
341
    #[must_use]
342
314
    pub const fn len(&self) -> usize {
343
314
        self.vec.len
344
314
    }
345

            
346
    /// Returns true if the string is empty
347
    #[inline]
348
    #[must_use]
349
99
    pub const fn is_empty(&self) -> bool {
350
99
        self.vec.len == 0
351
99
    }
352

            
353
    /// Creates a null-terminated copy of the string for C FFI usage.
354
    /// Returns a new `U8Vec` that contains the string data followed by a null byte.
355
    /// The caller is responsible for freeing this memory.
356
    ///
357
    /// Use this when you need to pass a string to C code that expects `const char*`.
358
    #[inline]
359
    #[must_use]
360
8
    pub fn to_c_str(&self) -> U8Vec {
361
8
        let bytes = self.as_bytes();
362
8
        let mut result = Vec::with_capacity(bytes.len() + 1);
363
8
        result.extend_from_slice(bytes);
364
8
        result.push(0); // null terminator
365
8
        U8Vec::from_vec(result)
366
8
    }
367

            
368
    /// Shared implementation for UTF-16 decoding with a caller-supplied byte-order function.
369
    ///
370
    /// # Safety
371
    /// - `ptr` must be valid for reading `len` bytes
372
    /// - `len` must be even (UTF-16 uses 2 bytes per code unit)
373
19
    unsafe fn from_utf16_with_byte_order(
374
19
        ptr: *const u8,
375
19
        len: usize,
376
19
        from_bytes: fn([u8; 2]) -> u16,
377
19
    ) -> Self {
378
        unsafe {
379
19
            if ptr.is_null() || len == 0 {
380
5
                return Self::default();
381
14
            }
382

            
383
            // UTF-16 requires pairs of bytes
384
14
            if !len.is_multiple_of(2) {
385
4
                return Self::default();
386
10
            }
387

            
388
10
            let byte_slice = core::slice::from_raw_parts(ptr, len);
389
10
            let code_units: Vec<u16> = byte_slice
390
10
                .chunks_exact(2)
391
100029
                .map(|chunk| from_bytes([chunk[0], chunk[1]]))
392
10
                .collect();
393

            
394
10
            String::from_utf16(&code_units).map_or_else(|_| Self::default(), Self::from_string)
395
        }
396
19
    }
397

            
398
    /// Creates a new `AzString` from UTF-16 encoded bytes (little-endian).
399
    /// Returns an empty string if the input is invalid UTF-16 or has odd length.
400
    ///
401
    /// # Arguments
402
    /// * `ptr` - Pointer to UTF-16 encoded bytes
403
    /// * `len` - Length in bytes (not code units) - must be even
404
    ///
405
    /// # Safety
406
    /// - `ptr` must be valid for reading `len` bytes
407
    /// - `len` must be even (UTF-16 uses 2 bytes per code unit)
408
    #[inline]
409
10
    pub unsafe fn from_utf16_le(ptr: *const u8, len: usize) -> Self {
410
10
        unsafe { Self::from_utf16_with_byte_order(ptr, len, u16::from_le_bytes) }
411
10
    }
412

            
413
    /// Creates a new `AzString` from UTF-16 encoded bytes (big-endian).
414
    /// Returns an empty string if the input is invalid UTF-16 or has odd length.
415
    ///
416
    /// # Arguments
417
    /// * `ptr` - Pointer to UTF-16 encoded bytes
418
    /// * `len` - Length in bytes (not code units) - must be even
419
    ///
420
    /// # Safety
421
    /// - `ptr` must be valid for reading `len` bytes
422
    /// - `len` must be even (UTF-16 uses 2 bytes per code unit)
423
    #[inline]
424
5
    pub unsafe fn from_utf16_be(ptr: *const u8, len: usize) -> Self {
425
5
        unsafe { Self::from_utf16_with_byte_order(ptr, len, u16::from_be_bytes) }
426
5
    }
427

            
428
    /// Creates a new `AzString` from UTF-8 bytes with lossy conversion.
429
    /// Invalid UTF-8 sequences are replaced with the Unicode replacement character (U+FFFD).
430
    ///
431
    /// # Safety
432
    /// - `ptr` must be valid for reading `len` bytes
433
    #[inline]
434
    #[must_use]
435
8
    pub unsafe fn from_utf8_lossy(ptr: *const u8, len: usize) -> Self {
436
        unsafe {
437
8
            if ptr.is_null() || len == 0 {
438
2
                return Self::default();
439
6
            }
440

            
441
6
            let byte_slice = core::slice::from_raw_parts(ptr, len);
442
6
            let s = String::from_utf8_lossy(byte_slice).into_owned();
443
6
            Self::from_string(s)
444
        }
445
8
    }
446

            
447
    /// Creates a new `AzString` from UTF-8 bytes.
448
    /// Returns an empty string if the input is not valid UTF-8.
449
    ///
450
    /// # Safety
451
    /// - `ptr` must be valid for reading `len` bytes
452
    #[inline]
453
    #[must_use]
454
12
    pub unsafe fn from_utf8(ptr: *const u8, len: usize) -> Self {
455
        unsafe {
456
12
            if ptr.is_null() || len == 0 {
457
2
                return Self::default();
458
10
            }
459

            
460
10
            let byte_slice = core::slice::from_raw_parts(ptr, len);
461
10
            core::str::from_utf8(byte_slice)
462
10
                .map_or_else(|_| Self::default(), |s| Self::from_string(s.to_string()))
463
        }
464
12
    }
465
}
466

            
467
impl From<String> for AzString {
468
13701202
    fn from(input: String) -> Self {
469
13701202
        Self::from_string(input)
470
13701202
    }
471
}
472

            
473
impl PartialOrd for AzString {
474
103
    fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
475
103
        self.as_str().partial_cmp(rhs.as_str())
476
103
    }
477
}
478

            
479
impl Ord for AzString {
480
674
    fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
481
674
        self.as_str().cmp(rhs.as_str())
482
674
    }
483
}
484

            
485
impl Clone for AzString {
486
7336542
    fn clone(&self) -> Self {
487
7336542
        self.clone_self()
488
7336542
    }
489
}
490

            
491
impl PartialEq for AzString {
492
12768275
    fn eq(&self, rhs: &Self) -> bool {
493
12768275
        self.as_str().eq(rhs.as_str())
494
12768275
    }
495
}
496

            
497
impl Eq for AzString {}
498

            
499
impl core::hash::Hash for AzString {
500
795337
    fn hash<H>(&self, state: &mut H)
501
795337
    where
502
795337
        H: core::hash::Hasher,
503
    {
504
795337
        self.as_str().hash(state);
505
795337
    }
506
}
507

            
508
impl core::ops::Deref for AzString {
509
    type Target = str;
510

            
511
172488
    fn deref(&self) -> &str {
512
172488
        self.as_str()
513
172488
    }
514
}
515

            
516
impl_option!(
517
    u8,
518
    OptionU8,
519
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
520
);
521

            
522
impl_vec!(
523
    u8,
524
    U8Vec,
525
    U8VecDestructor,
526
    U8VecDestructorType,
527
    U8VecSlice,
528
    OptionU8
529
);
530
impl_vec_mut!(u8, U8Vec);
531
impl_vec_debug!(u8, U8Vec);
532
impl_vec_partialord!(u8, U8Vec);
533
impl_vec_ord!(u8, U8Vec);
534
impl_vec_clone!(u8, U8Vec, U8VecDestructor);
535
impl_vec_partialeq!(u8, U8Vec);
536
impl_vec_eq!(u8, U8Vec);
537
impl_vec_hash!(u8, U8Vec);
538

            
539
impl U8Vec {
540
    /// Copies bytes from a pointer into a new Vec.
541
    /// This is useful for C FFI where you have a `uint8_t`* buffer.
542
    ///
543
    /// # Safety contract (caller must ensure)
544
    /// - `ptr` must be valid for reading `start + len` bytes
545
    /// - `start + len` must not overflow
546
    #[inline] // web-lift: inline through the sret-in-X0 chain (see AzString::copy_from_bytes)
547
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
548
    // SAFETY/FFI: `*const T` is the C-ABI signature; the fn null-checks then derefs under the
549
    // documented caller contract (C guarantees a valid ptr/len). Marking it `unsafe fn` would force
550
    // unsafe blocks into the generated dll bindings.
551
    #[must_use]
552
28
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
553
28
        if ptr.is_null() || len == 0 {
554
11
            return Self::new();
555
17
        }
556
17
        debug_assert!(
557
            start.checked_add(len).is_some(),
558
            "U8Vec::copy_from_bytes: start + len overflows"
559
        );
560
17
        let slice = unsafe { core::slice::from_raw_parts(ptr.add(start), len) };
561
17
        Self::from_vec(slice.to_vec())
562
28
    }
563
}
564

            
565
impl_option!(
566
    U8Vec,
567
    OptionU8Vec,
568
    copy = false,
569
    [Debug, Clone, PartialEq, Ord, PartialOrd, Eq, Hash]
570
);
571

            
572
impl_vec!(
573
    u16,
574
    U16Vec,
575
    U16VecDestructor,
576
    U16VecDestructorType,
577
    U16VecSlice,
578
    OptionU16
579
);
580
impl_vec_debug!(u16, U16Vec);
581
impl_vec_partialord!(u16, U16Vec);
582
impl_vec_ord!(u16, U16Vec);
583
impl_vec_clone!(u16, U16Vec, U16VecDestructor);
584
impl_vec_partialeq!(u16, U16Vec);
585
impl_vec_eq!(u16, U16Vec);
586
impl_vec_hash!(u16, U16Vec);
587

            
588
impl_vec!(
589
    f32,
590
    F32Vec,
591
    F32VecDestructor,
592
    F32VecDestructorType,
593
    F32VecSlice,
594
    OptionF32
595
);
596
impl_vec_debug!(f32, F32Vec);
597
impl_vec_partialord!(f32, F32Vec);
598
impl_vec_clone!(f32, F32Vec, F32VecDestructor);
599
impl_vec_partialeq!(f32, F32Vec);
600

            
601
// Vec<char>
602
impl_vec!(
603
    u32,
604
    U32Vec,
605
    U32VecDestructor,
606
    U32VecDestructorType,
607
    U32VecSlice,
608
    OptionU32
609
);
610
impl_vec_mut!(u32, U32Vec);
611
impl_option!(
612
    U32Vec,
613
    OptionU32Vec,
614
    copy = false,
615
    [Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Hash]
616
);
617
impl_vec_debug!(u32, U32Vec);
618
impl_vec_partialord!(u32, U32Vec);
619
impl_vec_ord!(u32, U32Vec);
620
impl_vec_clone!(u32, U32Vec, U32VecDestructor);
621
impl_vec_partialeq!(u32, U32Vec);
622
impl_vec_eq!(u32, U32Vec);
623
impl_vec_hash!(u32, U32Vec);
624

            
625
impl_vec!(
626
    AzString,
627
    StringVec,
628
    StringVecDestructor,
629
    StringVecDestructorType,
630
    StringVecSlice,
631
    OptionString
632
);
633
impl_vec_debug!(AzString, StringVec);
634
impl_vec_partialord!(AzString, StringVec);
635
impl_vec_ord!(AzString, StringVec);
636
impl_vec_clone!(AzString, StringVec, StringVecDestructor);
637
impl_vec_partialeq!(AzString, StringVec);
638
impl_vec_eq!(AzString, StringVec);
639
impl_vec_hash!(AzString, StringVec);
640

            
641
impl From<Vec<String>> for StringVec {
642
    fn from(v: Vec<String>) -> Self {
643
        let new_v: Vec<AzString> = v.into_iter().map(Into::into).collect();
644
        new_v.into()
645
    }
646
}
647

            
648
impl_option!(
649
    StringVec,
650
    OptionStringVec,
651
    copy = false,
652
    [Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash]
653
);
654

            
655
impl_option!(
656
    u16,
657
    OptionU16,
658
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
659
);
660
impl_option!(
661
    u32,
662
    OptionU32,
663
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
664
);
665
impl_option!(
666
    u64,
667
    OptionU64,
668
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
669
);
670
impl_option!(
671
    usize,
672
    OptionUsize,
673
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
674
);
675
impl_option!(
676
    i16,
677
    OptionI16,
678
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
679
);
680
impl_option!(
681
    i32,
682
    OptionI32,
683
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
684
);
685
impl_option!(
686
    bool,
687
    OptionBool,
688
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
689
);
690
impl_option!(f32, OptionF32, [Debug, Copy, Clone, PartialEq]);
691
impl_option!(f64, OptionF64, [Debug, Copy, Clone, PartialEq, PartialOrd]);
692

            
693
// Manual implementations for Hash and Ord on OptionF32 (since f32 doesn't implement these traits)
694
impl core::hash::Hash for OptionF32 {
695
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
696
        match self {
697
            Self::None => 0u8.hash(state),
698
            Self::Some(v) => {
699
                1u8.hash(state);
700
                v.to_bits().hash(state);
701
            }
702
        }
703
    }
704
}
705

            
706
impl Eq for OptionF32 {}
707

            
708
// Manual PartialOrd delegating to Ord keeps the two consistent (the derived
709
// PartialOrd would diverge from the manual Ord — see derive_ord_xor_partial_ord).
710
impl PartialOrd for OptionF32 {
711
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
712
        Some(self.cmp(other))
713
    }
714
}
715

            
716
impl Ord for OptionF32 {
717
29
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
718
29
        match (self, other) {
719
17
            (Self::None, Self::None) => core::cmp::Ordering::Equal,
720
            (Self::None, Self::Some(_)) => core::cmp::Ordering::Less,
721
            (Self::Some(_), Self::None) => core::cmp::Ordering::Greater,
722
12
            (Self::Some(a), Self::Some(b)) => {
723
12
                a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal)
724
            }
725
        }
726
29
    }
727
}
728

            
729
// ============================================================================
730
// StringArena — bump allocator for AzString bytes
731
// ============================================================================
732
//
733
// Consolidates thousands of small AzString allocations (tag names,
734
// attribute values, text content) into a handful of 64 KiB chunks.
735
// Each arena-backed AzString uses `U8VecDestructor::External` and stashes
736
// a cloned `Arc<StringArenaInner>` pointer in the `cap` field — dropping
737
// the AzString decrements the refcount, and the backing bytes are freed
738
// only when the last reference goes away. This works across FFI without
739
// changing any public struct layout.
740

            
741
use alloc::sync::Arc;
742
use core::cell::UnsafeCell;
743

            
744
/// Shared interior of a [`StringArena`]. Refcounted via `Arc<Self>`;
745
/// never accessed through its `Arc` for mutation — only the owning
746
/// `StringArena` (with `&mut self`) mutates the chunks.
747
struct StringArenaInner {
748
    /// Pre-allocated byte chunks. Pointers into a chunk stay valid
749
    /// because we never push past `Vec::capacity()` — no reallocation.
750
    chunks: UnsafeCell<Vec<Vec<u8>>>,
751
    /// Remaining unused bytes in the last chunk; `0` when a fresh
752
    /// chunk is needed.
753
    current_remaining: UnsafeCell<usize>,
754
}
755

            
756
// Safety:
757
// - Mutation through `UnsafeCell` only happens via `&mut StringArena`, which owns the sole external
758
//   reference to `Arc<StringArenaInner>` held in a `StringArena`. Other `Arc` references live
759
//   inside AzString destructors and never touch chunks — they only drop the Arc.
760
// - `Arc<T>` itself needs `T: Send + Sync` to cross threads; since the destructor can run on any
761
//   thread, we claim Send+Sync and rely on the single-writer invariant for mutation safety.
762
unsafe impl Send for StringArenaInner {}
763
unsafe impl Sync for StringArenaInner {}
764

            
765
/// Bump allocator backing arena-owned `AzString` instances.
766
///
767
/// Every `AzString` returned by [`StringArena::intern`] holds a cloned
768
/// `Arc` to this arena; the backing bytes stay alive until the last
769
/// such `AzString` (and the arena handle itself) is dropped.
770
///
771
/// Intended use: create one arena per XML/HTML parse pass, intern all
772
/// tag names / attribute values / text content through it, then drop the
773
/// handle. The `AzStrings` embedded in the resulting `StyledDom` keep the
774
/// arena alive for as long as they need the bytes.
775
pub struct StringArena {
776
    inner: Arc<StringArenaInner>,
777
}
778

            
779
impl core::fmt::Debug for StringArena {
780
    // StringArenaInner holds UnsafeCell chunks (not Debug) — opaque by design.
781
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
782
        f.debug_struct("StringArena").finish_non_exhaustive()
783
    }
784
}
785

            
786
impl StringArena {
787
    /// Size of a freshly allocated chunk. Large enough that a typical
788
    /// DOM parse fits in 1-2 chunks, small enough to not over-allocate
789
    /// for small documents.
790
    pub const CHUNK_SIZE: usize = 64 * 1024;
791

            
792
    #[must_use]
793
4677
    pub fn new() -> Self {
794
4677
        Self {
795
4677
            inner: Arc::new(StringArenaInner {
796
4677
                chunks: UnsafeCell::new(Vec::new()),
797
4677
                current_remaining: UnsafeCell::new(0),
798
4677
            }),
799
4677
        }
800
4677
    }
801

            
802
    /// Returns `(chunk_count, total_bytes_used)` for metrics.
803
    #[must_use]
804
9
    pub fn metrics(&self) -> (usize, usize) {
805
        // Safety: metrics is read-only; the caller holds &self so no
806
        // concurrent mutation via &mut self is possible.
807
        unsafe {
808
9
            let chunks = &*self.inner.chunks.get();
809
9
            let total: usize = chunks.iter().map(Vec::len).sum();
810
9
            (chunks.len(), total)
811
        }
812
9
    }
813

            
814
    /// Intern `s` into the arena and return an `AzString` whose backing
815
    /// bytes live inside the arena. The returned `AzString` owns a cloned
816
    /// `Arc` reference; dropping it decrements the refcount, and the
817
    /// arena frees its chunks when the final reference is released.
818
    ///
819
    /// # Panics
820
    ///
821
    /// Panics if the arena's internal chunk list is unexpectedly empty when
822
    /// appending a non-oversized string (an invariant violation that cannot
823
    /// occur through the public API, since a chunk is allocated on demand).
824
29124
    pub fn intern(&mut self, s: &str) -> AzString {
825
29124
        let bytes = s.as_bytes();
826
29124
        let len = bytes.len();
827

            
828
29124
        let ptr: *const u8 = if len == 0 {
829
            // Empty strings don't need arena storage; a non-null dangling
830
            // pointer is fine because `len == 0` means nobody will deref.
831
2
            core::ptr::NonNull::<u8>::dangling().as_ptr()
832
        } else {
833
            // Safety: `&mut self` ⇒ exclusive access to inner chunks.
834
            unsafe {
835
29122
                let chunks: &mut Vec<Vec<u8>> = &mut *self.inner.chunks.get();
836
29122
                let remaining: &mut usize = &mut *self.inner.current_remaining.get();
837

            
838
                // Oversized strings get their own dedicated chunk so we
839
                // don't waste the tail of the current chunk.
840
29122
                if len > Self::CHUNK_SIZE / 2 {
841
17
                    let mut v = Vec::with_capacity(len);
842
17
                    v.extend_from_slice(bytes);
843
17
                    let p = v.as_ptr();
844
17
                    chunks.push(v);
845
                    // This dedicated chunk is FULL (len == cap). `remaining` must not
846
                    // keep describing the previous chunk, or the next small intern
847
                    // below would see a stale positive `remaining`, skip allocating,
848
                    // and `extend_from_slice` into THIS chunk — reallocating it and
849
                    // dangling the `p` we just handed out.
850
17
                    *remaining = 0;
851
17
                    p
852
                } else {
853
29105
                    if *remaining < len {
854
2907
                        chunks.push(Vec::with_capacity(Self::CHUNK_SIZE));
855
2907
                        *remaining = Self::CHUNK_SIZE;
856
26198
                    }
857
                    // Safety: chunk was allocated with capacity ≥ len and
858
                    // `remaining` tracks unused capacity — no realloc.
859
29105
                    let chunk = chunks.last_mut().unwrap();
860
29105
                    let offset = chunk.len();
861
29105
                    chunk.extend_from_slice(bytes);
862
29105
                    *remaining -= len;
863
29105
                    chunk.as_ptr().add(offset)
864
                }
865
            }
866
        };
867

            
868
        // Each AzString carries its own Arc reference count. Stash the
869
        // raw Arc pointer in `cap` so the External destructor can decrement.
870
29124
        let arc_raw = Arc::into_raw(Arc::clone(&self.inner));
871

            
872
29124
        AzString {
873
29124
            vec: U8Vec {
874
29124
                ptr,
875
29124
                len,
876
29124
                // NOTE: `cap` stores an Arc pointer, not a capacity. This
877
29124
                // works because the `External` destructor path never calls
878
29124
                // `Vec::from_raw_parts(ptr, len, cap)` — only `DefaultRust`
879
29124
                // does that.
880
29124
                cap: arc_raw as usize,
881
29124
                destructor: U8VecDestructor::External(arena_string_destructor),
882
29124
            },
883
29124
        }
884
29124
    }
885
}
886

            
887
impl Default for StringArena {
888
1
    fn default() -> Self {
889
1
        Self::new()
890
1
    }
891
}
892

            
893
/// Destructor installed on every arena-backed `AzString`. Reads the Arc
894
/// pointer out of `cap` and drops one Arc reference; when the count
895
/// reaches zero the `StringArenaInner` is freed.
896
29128
extern "C" fn arena_string_destructor(vec: *mut U8Vec) {
897
    // Safety: called at most once per AzString drop. `cap` was set by
898
    // `StringArena::intern` to `Arc::into_raw(Arc<StringArenaInner>)`.
899
    unsafe {
900
29128
        let v = &mut *vec;
901
29128
        let arc_raw = v.cap as *const StringArenaInner;
902
29128
        if !arc_raw.is_null() {
903
29125
            drop(Arc::from_raw(arc_raw));
904
29125
            // Prevent a hypothetical double-drop from dereferencing
905
29125
            // freed memory.
906
29125
            v.cap = 0;
907
29125
        }
908
    }
909
29128
}
910

            
911
#[cfg(test)]
912
mod string_arena_tests {
913
    use super::*;
914

            
915
    #[test]
916
1
    fn intern_round_trip() {
917
1
        let mut arena = StringArena::new();
918
1
        let a = arena.intern("hello");
919
1
        let b = arena.intern("world");
920
1
        let c = arena.intern("");
921
1
        assert_eq!(a.as_str(), "hello");
922
1
        assert_eq!(b.as_str(), "world");
923
1
        assert_eq!(c.as_str(), "");
924
1
    }
925

            
926
    #[test]
927
1
    fn strings_outlive_arena_handle() {
928
1
        let a = {
929
1
            let mut arena = StringArena::new();
930
1
            arena.intern("survives drop of arena handle")
931
        };
932
1
        assert_eq!(a.as_str(), "survives drop of arena handle");
933
1
    }
934

            
935
    #[test]
936
1
    fn oversized_string_gets_dedicated_chunk() {
937
1
        let mut arena = StringArena::new();
938
1
        let big = "x".repeat(StringArena::CHUNK_SIZE);
939
1
        let s = arena.intern(&big);
940
1
        assert_eq!(s.len(), big.len());
941
1
        assert_eq!(s.as_str(), big.as_str());
942
1
    }
943

            
944
    #[test]
945
1
    fn many_small_strings_share_chunk() {
946
1
        let mut arena = StringArena::new();
947
1
        let mut strings = Vec::new();
948
101
        for i in 0..100 {
949
100
            strings.push(arena.intern(&format!("s{i}")));
950
100
        }
951
1
        let (chunks, _bytes) = arena.metrics();
952
1
        assert!(
953
1
            chunks <= 2,
954
            "expected ≤2 chunks for 100 small strings, got {chunks}"
955
        );
956
100
        for (i, s) in strings.iter().enumerate() {
957
100
            assert_eq!(s.as_str(), format!("s{i}"));
958
        }
959
1
    }
960

            
961
    #[test]
962
1
    fn clone_deep_copies_and_is_independent() {
963
        // Cloning an External AzString deep-copies into DefaultRust, so
964
        // the clone doesn't depend on the arena at all.
965
1
        let clone = {
966
1
            let mut arena = StringArena::new();
967

            
968
1
            arena.intern("deep-copy test")
969
        };
970
1
        assert_eq!(clone.as_str(), "deep-copy test");
971
1
    }
972
}
973

            
974
#[cfg(test)]
975
#[allow(clippy::all, clippy::pedantic, clippy::nursery)]
976
mod autotest_generated {
977
    use super::*;
978

            
979
    // ------------------------------------------------------------------
980
    // helpers
981
    // ------------------------------------------------------------------
982

            
983
    /// Minimal FNV-1a hasher so the Hash-consistency tests don't depend on
984
    /// `std` being linked (the crate keeps a `#![no_std]` line commented out).
985
    struct Fnv(u64);
986

            
987
    impl core::hash::Hasher for Fnv {
988
        fn finish(&self) -> u64 {
989
            self.0
990
        }
991
        fn write(&mut self, bytes: &[u8]) {
992
            for b in bytes {
993
                self.0 ^= u64::from(*b);
994
                self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
995
            }
996
        }
997
    }
998

            
999
    fn hash_of<T: core::hash::Hash>(t: &T) -> u64 {
        use core::hash::{Hash, Hasher};
        let mut h = Fnv(0xcbf2_9ce4_8422_2325);
        Hash::hash(t, &mut h);
        h.finish()
    }
    /// UTF-16 code units of `s`, serialized to bytes with the given byte order.
    fn utf16_bytes(s: &str, little_endian: bool) -> Vec<u8> {
        s.encode_utf16()
            .flat_map(|u| {
                let b = if little_endian {
                    u.to_le_bytes()
                } else {
                    u.to_be_bytes()
                };
                [b[0], b[1]]
            })
            .collect()
    }
    // ==================================================================
    // EmptyStruct
    // ==================================================================
    #[test]
    fn empty_struct_new_invariants() {
        let e = EmptyStruct::new();
        assert_eq!(e._reserved, 0, "_reserved must always be initialized to 0");
        assert_eq!(e, EmptyStruct::default(), "new() must equal default()");
    }
    #[test]
    fn empty_struct_is_ffi_safe_non_zero_size() {
        // The whole point of the type: `()` is zero-sized and not FFI-safe.
        assert_eq!(size_of::<EmptyStruct>(), 1);
        assert_eq!(align_of::<EmptyStruct>(), 1);
    }
    #[test]
    fn empty_struct_unit_conversions_round_trip() {
        let from_unit = EmptyStruct::from(());
        assert_eq!(from_unit, EmptyStruct::new());
        let back: () = EmptyStruct::new().into();
        assert_eq!(back, ());
    }
    #[test]
    fn empty_struct_total_order_is_trivial() {
        // Every EmptyStruct is equal to every other one, so Ord/Hash must agree.
        let a = EmptyStruct::new();
        let b = EmptyStruct::default();
        assert_eq!(a.cmp(&b), core::cmp::Ordering::Equal);
        assert_eq!(hash_of(&a), hash_of(&b));
    }
    // ==================================================================
    // LayoutDebugMessage
    // ==================================================================
    #[test]
    fn debug_message_new_records_fields_and_caller_location() {
        let m = LayoutDebugMessage::new(LayoutDebugMessageType::Warning, "disk on fire");
        assert_eq!(m.message_type, LayoutDebugMessageType::Warning);
        assert_eq!(m.message.as_str(), "disk on fire");
        assert!(
            m.location.as_str().contains("corety.rs"),
            "#[track_caller] must record THIS file, got {:?}",
            m.location.as_str()
        );
        // location is "file:line:column" — the last two segments must be numbers.
        let parts: Vec<&str> = m.location.as_str().rsplitn(3, ':').collect();
        assert_eq!(parts.len(), 3, "location must be file:line:column");
        assert!(parts[0].parse::<u32>().is_ok(), "column must parse as u32");
        assert!(parts[1].parse::<u32>().is_ok(), "line must parse as u32");
    }
    #[test]
    fn debug_message_track_caller_propagates_through_helpers() {
        // If #[track_caller] were missing on the helpers, both locations would
        // collapse to the same line inside LayoutDebugMessage::new().
        let a = LayoutDebugMessage::info("a");
        let b = LayoutDebugMessage::info("b");
        assert_ne!(
            a.location.as_str(),
            b.location.as_str(),
            "two call sites on different lines must record different locations"
        );
        assert!(a.location.as_str().contains("corety.rs"));
    }
    #[test]
    fn debug_message_helpers_set_the_right_type() {
        assert_eq!(
            LayoutDebugMessage::info("x").message_type,
            LayoutDebugMessageType::Info
        );
        assert_eq!(
            LayoutDebugMessage::warning("x").message_type,
            LayoutDebugMessageType::Warning
        );
        assert_eq!(
            LayoutDebugMessage::error("x").message_type,
            LayoutDebugMessageType::Error
        );
        assert_eq!(
            LayoutDebugMessage::box_props("x").message_type,
            LayoutDebugMessageType::BoxProps
        );
        assert_eq!(
            LayoutDebugMessage::css_getter("x").message_type,
            LayoutDebugMessageType::CssGetter
        );
        assert_eq!(
            LayoutDebugMessage::bfc_layout("x").message_type,
            LayoutDebugMessageType::BfcLayout
        );
        assert_eq!(
            LayoutDebugMessage::ifc_layout("x").message_type,
            LayoutDebugMessageType::IfcLayout
        );
        assert_eq!(
            LayoutDebugMessage::table_layout("x").message_type,
            LayoutDebugMessageType::TableLayout
        );
        assert_eq!(
            LayoutDebugMessage::display_type("x").message_type,
            LayoutDebugMessageType::DisplayType
        );
    }
    #[test]
    fn debug_message_helpers_preserve_the_message_verbatim() {
        // Every helper must forward the payload untouched, including empty
        // and unicode payloads.
        for m in [
            LayoutDebugMessage::info(""),
            LayoutDebugMessage::warning(""),
            LayoutDebugMessage::error(""),
            LayoutDebugMessage::box_props(""),
            LayoutDebugMessage::css_getter(""),
            LayoutDebugMessage::bfc_layout(""),
            LayoutDebugMessage::ifc_layout(""),
            LayoutDebugMessage::table_layout(""),
            LayoutDebugMessage::display_type(""),
        ] {
            assert!(m.message.is_empty());
            assert!(!m.location.is_empty(), "location is always filled in");
        }
        let weird = "ünïcødé \u{1F600}\n\t\"quoted\" \u{0}nul";
        assert_eq!(LayoutDebugMessage::error(weird).message.as_str(), weird);
    }
    #[test]
    fn debug_message_handles_huge_message_without_panicking() {
        let huge = "m".repeat(1_000_000);
        let m = LayoutDebugMessage::new(LayoutDebugMessageType::PositionCalculation, huge.clone());
        assert_eq!(m.message.len(), 1_000_000);
        assert_eq!(m.message.as_str(), huge.as_str());
        assert_eq!(
            m.message_type,
            LayoutDebugMessageType::PositionCalculation,
            "the variant with no helper must still be constructible via new()"
        );
    }
    #[test]
    fn debug_message_default_is_empty_info() {
        let m = LayoutDebugMessage::default();
        assert_eq!(m.message_type, LayoutDebugMessageType::Info);
        assert!(m.message.is_empty());
        assert!(m.location.is_empty(), "default() does not track a caller");
        assert_eq!(
            LayoutDebugMessageType::default(),
            LayoutDebugMessageType::Info
        );
    }
    #[test]
    fn debug_message_accepts_string_and_str_via_into() {
        // `impl Into<String>` must work for both &str and String.
        let from_str = LayoutDebugMessage::info("borrowed");
        let from_string = LayoutDebugMessage::info(String::from("owned"));
        assert_eq!(from_str.message.as_str(), "borrowed");
        assert_eq!(from_string.message.as_str(), "owned");
    }
    #[test]
    fn debug_message_clone_is_a_deep_equal_copy() {
        let m = LayoutDebugMessage::error("clone me \u{1F600}");
        let c = m.clone();
        assert_eq!(c, m);
        assert_ne!(
            c.message.as_bytes().as_ptr(),
            m.message.as_bytes().as_ptr(),
            "clone must deep-copy the library-owned message bytes"
        );
    }
    // ==================================================================
    // AzString — constructors
    // ==================================================================
    #[test]
    fn azstring_default_is_empty_and_readable() {
        let s = AzString::default();
        assert_eq!(s.as_str(), "");
        assert_eq!(s.len(), 0);
        assert!(s.is_empty());
        assert_eq!(s.as_bytes(), b"");
    }
    #[test]
    fn azstring_from_const_str_borrows_the_static_and_never_frees_it() {
        // One binding, used for both the construction and the pointer check —
        // rustc is not obliged to dedupe two identical string literals.
        const TEXT: &str = "static text";
        let s = AzString::from_const_str(TEXT);
        assert_eq!(s.as_str(), TEXT);
        assert_eq!(s.len(), 11);
        assert!(
            matches!(s.vec.destructor, U8VecDestructor::NoDestructor),
            "a &'static str must not get a freeing destructor"
        );
        assert_eq!(
            s.vec.ptr,
            TEXT.as_bytes().as_ptr(),
            "from_const_str must alias the static, not copy it"
        );
    }
    #[test]
    fn azstring_from_const_str_empty_and_unicode() {
        let empty = AzString::from_const_str("");
        assert!(empty.is_empty());
        assert_eq!(empty.as_str(), "");
        assert_eq!(empty.len(), 0);
        let uni = AzString::from_const_str("héllo \u{1F600}");
        assert_eq!(uni.as_str(), "héllo \u{1F600}");
        // len() is BYTES, not chars: 5 ASCII-ish + 1 extra for é + space + 4 for the emoji
        assert_eq!(uni.len(), "héllo \u{1F600}".len());
        assert_ne!(
            uni.len(),
            uni.as_str().chars().count(),
            "len() must be a byte length, not a char count"
        );
    }
    #[test]
    fn azstring_from_string_round_trips_edge_values() {
        for input in [
            String::new(),
            String::from(" "),
            String::from("\t\n\r"),
            String::from("0"),
            String::from("-0"),
            String::from("9223372036854775807"), // i64::MAX
            String::from("NaN"),
            String::from("inf"),
            String::from("  valid  "),
            String::from("valid;garbage"),
            String::from("\u{1F600}\u{0301}\u{0}"), // emoji + combining mark + NUL
            "{".repeat(10_000),                     // deeply "nested" junk: no parser, no overflow
        ] {
            let s = AzString::from_string(input.clone());
            assert_eq!(s.as_str(), input.as_str(), "from_string must be verbatim");
            assert_eq!(s.len(), input.len());
            assert_eq!(s.is_empty(), input.is_empty());
            // round-trip back out
            assert_eq!(s.into_library_owned_string(), input);
        }
    }
    #[test]
    fn azstring_from_string_handles_a_megabyte() {
        let huge = "x".repeat(1_000_000);
        let s = AzString::from_string(huge.clone());
        assert_eq!(s.len(), 1_000_000);
        assert_eq!(s.as_str().len(), huge.len());
        assert!(s.as_str().bytes().all(|b| b == b'x'));
    }
    #[test]
    fn azstring_from_string_preserves_the_original_capacity() {
        // into_library_owned_string rebuilds the String via from_raw_parts(ptr, len, cap).
        // If `cap` were not carried through faithfully, this would corrupt the heap.
        let mut owned = String::with_capacity(4096);
        owned.push_str("hi");
        let s = AzString::from_string(owned);
        assert!(matches!(s.vec.destructor, U8VecDestructor::DefaultRust));
        let back = s.into_library_owned_string();
        assert_eq!(back, "hi");
        assert!(
            back.capacity() >= 4096,
            "capacity must survive the AzString round-trip, got {}",
            back.capacity()
        );
    }
    // ==================================================================
    // AzString::copy_from_bytes  (numeric / pointer edge cases)
    // ==================================================================
    #[test]
    fn azstring_copy_from_bytes_zero_len_is_empty() {
        let buf = b"hello";
        let s = AzString::copy_from_bytes(buf.as_ptr(), 0, 0);
        assert!(s.is_empty());
        assert_eq!(s.as_str(), "");
    }
    #[test]
    fn azstring_copy_from_bytes_null_ptr_is_empty() {
        let s = AzString::copy_from_bytes(core::ptr::null(), 0, 16);
        assert!(s.is_empty());
        assert_eq!(s.as_str(), "");
    }
    #[test]
    fn azstring_copy_from_bytes_honours_the_start_offset() {
        let buf = b"0123456789";
        let s = AzString::copy_from_bytes(buf.as_ptr(), 3, 4);
        assert_eq!(s.as_str(), "3456");
        assert_eq!(s.len(), 4);
    }
    #[test]
    fn azstring_copy_from_bytes_start_at_end_with_zero_len_is_empty() {
        // start == buf.len() is only legal because len == 0 short-circuits
        // before the pointer is ever offset.
        let buf = b"abc";
        let s = AzString::copy_from_bytes(buf.as_ptr(), buf.len(), 0);
        assert!(s.is_empty());
    }
    #[test]
    fn azstring_copy_from_bytes_zero_len_wins_over_start_overflow() {
        // start + len overflows usize, but len == 0 must short-circuit BEFORE
        // the debug_assert / ptr.add() — no panic, no UB.
        let buf = b"abc";
        let s = AzString::copy_from_bytes(buf.as_ptr(), usize::MAX, 0);
        assert!(s.is_empty());
    }
    #[test]
    fn azstring_copy_from_bytes_null_wins_over_max_len() {
        // The null check must precede everything, even for absurd start/len.
        let s = AzString::copy_from_bytes(core::ptr::null(), usize::MAX, usize::MAX);
        assert!(s.is_empty());
        assert_eq!(s.as_str(), "");
    }
    #[test]
    fn azstring_copy_from_bytes_replaces_invalid_utf8_lossily() {
        // Slicing "héllo" mid-codepoint leaves a stray continuation byte (0xA9),
        // which must become U+FFFD so the as_str() UTF-8 invariant still holds.
        let buf = "héllo".as_bytes();
        assert_eq!(buf[1], 0xC3);
        assert_eq!(buf[2], 0xA9);
        let s = AzString::copy_from_bytes(buf.as_ptr(), 2, 2);
        assert_eq!(s.as_str(), "\u{FFFD}l");
        // The UTF-8 invariant as_str() relies on must actually hold:
        assert!(core::str::from_utf8(s.as_bytes()).is_ok());
    }
    #[test]
    fn azstring_copy_from_bytes_keeps_valid_utf8_byte_for_byte() {
        let buf = "héllo \u{1F600}".as_bytes();
        let s = AzString::copy_from_bytes(buf.as_ptr(), 0, buf.len());
        assert_eq!(s.as_str(), "héllo \u{1F600}");
        assert_eq!(s.as_bytes(), buf);
    }
    #[test]
    fn azstring_copy_from_bytes_preserves_interior_nul() {
        let buf = b"a\0b";
        let s = AzString::copy_from_bytes(buf.as_ptr(), 0, 3);
        assert_eq!(s.len(), 3, "an interior NUL is data, not a terminator");
        assert_eq!(s.as_bytes(), b"a\0b");
    }
    // ==================================================================
    // U8Vec::copy_from_bytes  (numeric / pointer edge cases)
    // ==================================================================
    #[test]
    fn u8vec_copy_from_bytes_zero_len_is_empty() {
        let buf = b"hello";
        let v = U8Vec::copy_from_bytes(buf.as_ptr(), 0, 0);
        assert!(v.is_empty());
        assert_eq!(v.as_ref(), b"");
    }
    #[test]
    fn u8vec_copy_from_bytes_null_ptr_is_empty() {
        let v = U8Vec::copy_from_bytes(core::ptr::null(), 0, 8);
        assert!(v.is_empty());
        assert_eq!(v.len(), 0);
    }
    #[test]
    fn u8vec_copy_from_bytes_null_wins_over_max_start_and_len() {
        // Neither the debug_assert nor ptr.add() may be reached for a null ptr.
        let v = U8Vec::copy_from_bytes(core::ptr::null(), usize::MAX, usize::MAX);
        assert!(v.is_empty());
    }
    #[test]
    fn u8vec_copy_from_bytes_zero_len_wins_over_start_overflow() {
        // start + len overflows, but len == 0 short-circuits first.
        let buf = b"abc";
        let v = U8Vec::copy_from_bytes(buf.as_ptr(), usize::MAX, 0);
        assert!(v.is_empty());
    }
    #[test]
    fn u8vec_copy_from_bytes_copies_the_requested_window() {
        let buf: Vec<u8> = (0u8..=255).collect();
        let v = U8Vec::copy_from_bytes(buf.as_ptr(), 250, 6);
        assert_eq!(v.as_ref(), &[250, 251, 252, 253, 254, 255]);
        assert_eq!(v.len(), 6);
    }
    #[test]
    fn u8vec_copy_from_bytes_owns_its_copy() {
        // The copy must survive the source buffer being dropped.
        let v = {
            let buf = vec![1u8, 2, 3, 4];
            U8Vec::copy_from_bytes(buf.as_ptr(), 1, 2)
        };
        assert_eq!(v.as_ref(), &[2, 3]);
        assert!(matches!(v.destructor, U8VecDestructor::DefaultRust));
    }
    #[test]
    fn u8vec_copy_from_bytes_accepts_all_byte_values() {
        // Arbitrary (non-UTF-8) bytes must round-trip unchanged — U8Vec has no
        // encoding invariant, unlike AzString.
        let buf: Vec<u8> = (0u8..=255).collect();
        let v = U8Vec::copy_from_bytes(buf.as_ptr(), 0, buf.len());
        assert_eq!(v.as_ref(), buf.as_slice());
    }
    // ==================================================================
    // AzString::from_c_str
    // ==================================================================
    #[test]
    fn azstring_from_c_str_null_is_empty() {
        let s = unsafe { AzString::from_c_str(core::ptr::null()) };
        assert!(s.is_empty());
        assert_eq!(s.as_str(), "");
    }
    #[test]
    fn azstring_from_c_str_reads_up_to_the_terminator() {
        let c = b"hello\0trailing garbage\0";
        let s = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
        assert_eq!(s.as_str(), "hello");
        assert_eq!(s.len(), 5, "the NUL terminator is not part of the string");
    }
    #[test]
    fn azstring_from_c_str_empty_c_string_is_empty() {
        let c = b"\0";
        let s = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
        assert!(s.is_empty());
    }
    #[test]
    fn azstring_from_c_str_replaces_non_utf8_bytes() {
        // A latin-1 "café" is not valid UTF-8; it must come back lossily
        // rather than violating the as_str() invariant.
        let c = b"caf\xE9\0";
        let s = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
        assert_eq!(s.as_str(), "caf\u{FFFD}");
        assert!(core::str::from_utf8(s.as_bytes()).is_ok());
    }
    #[test]
    fn azstring_from_c_str_handles_a_long_c_string() {
        let mut c = "z".repeat(100_000).into_bytes();
        c.push(0);
        let s = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
        assert_eq!(s.len(), 100_000);
    }
    // ==================================================================
    // AzString::to_c_str  (+ round trip through from_c_str)
    // ==================================================================
    #[test]
    fn azstring_to_c_str_appends_exactly_one_nul() {
        let s = AzString::from_const_str("abc");
        let c = s.to_c_str();
        assert_eq!(c.as_ref(), b"abc\0");
        assert_eq!(c.len(), s.len() + 1);
    }
    #[test]
    fn azstring_to_c_str_of_empty_is_just_the_terminator() {
        let c = AzString::default().to_c_str();
        assert_eq!(c.as_ref(), b"\0");
        assert_eq!(c.len(), 1);
    }
    #[test]
    fn azstring_c_str_round_trip() {
        for original in ["", "abc", "héllo \u{1F600}", "  spaced  "] {
            let s = AzString::from_const_str(original);
            let c = s.to_c_str();
            let back = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
            assert_eq!(back.as_str(), original, "C round-trip must be lossless");
            assert_eq!(back, s);
        }
    }
    #[test]
    fn azstring_c_str_round_trip_truncates_at_an_interior_nul() {
        // Documented C-string reality: a string containing a NUL cannot survive
        // a *const char* round-trip. Assert the truncation is deterministic
        // rather than pretending it round-trips.
        let s = AzString::from_string(String::from("a\0b"));
        let c = s.to_c_str();
        assert_eq!(c.as_ref(), b"a\0b\0", "to_c_str keeps the interior NUL");
        let back = unsafe { AzString::from_c_str(c.as_ptr().cast::<i8>()) };
        assert_eq!(back.as_str(), "a", "from_c_str stops at the first NUL");
    }
    #[test]
    fn azstring_to_c_str_is_an_independent_allocation() {
        let s = AzString::from_const_str("shared?");
        let c = s.to_c_str();
        assert!(matches!(c.destructor, U8VecDestructor::DefaultRust));
        assert_ne!(
            c.as_ptr(),
            s.as_bytes().as_ptr(),
            "to_c_str must copy, not alias the source"
        );
        assert_eq!(s.as_str(), "shared?", "source must be untouched");
    }
    // ==================================================================
    // AzString::from_utf8 / from_utf8_lossy
    // ==================================================================
    #[test]
    fn azstring_from_utf8_null_or_zero_len_is_empty() {
        let buf = b"abc";
        assert!(unsafe { AzString::from_utf8(core::ptr::null(), 3) }.is_empty());
        assert!(unsafe { AzString::from_utf8(buf.as_ptr(), 0) }.is_empty());
        assert!(unsafe { AzString::from_utf8_lossy(core::ptr::null(), 3) }.is_empty());
        assert!(unsafe { AzString::from_utf8_lossy(buf.as_ptr(), 0) }.is_empty());
    }
    #[test]
    fn azstring_from_utf8_accepts_valid_multibyte() {
        let buf = "héllo \u{1F600}".as_bytes();
        let s = unsafe { AzString::from_utf8(buf.as_ptr(), buf.len()) };
        assert_eq!(s.as_str(), "héllo \u{1F600}");
        assert_eq!(s.len(), buf.len());
    }
    #[test]
    fn azstring_from_utf8_rejects_invalid_but_lossy_replaces_it() {
        // A truncated 2-byte sequence: strict → empty, lossy → U+FFFD.
        let buf = b"caf\xC3";
        let strict = unsafe { AzString::from_utf8(buf.as_ptr(), buf.len()) };
        assert!(
            strict.is_empty(),
            "from_utf8 must return an EMPTY string for invalid UTF-8, got {:?}",
            strict.as_str()
        );
        let lossy = unsafe { AzString::from_utf8_lossy(buf.as_ptr(), buf.len()) };
        assert_eq!(lossy.as_str(), "caf\u{FFFD}");
    }
    #[test]
    fn azstring_from_utf8_rejects_overlong_and_stray_continuations() {
        for bad in [
            &b"\xC0\xAF"[..],         // overlong encoding of '/'
            &b"\xED\xA0\x80"[..],     // UTF-16 surrogate half, illegal in UTF-8
            &b"\xF8\x88\x80\x80"[..], // 5-byte sequence, illegal since RFC 3629
            &b"\x80"[..],             // stray continuation byte
            &b"\xFF\xFE"[..],         // never-valid bytes
        ] {
            let strict = unsafe { AzString::from_utf8(bad.as_ptr(), bad.len()) };
            assert!(strict.is_empty(), "from_utf8 must reject {bad:?}");
            let lossy = unsafe { AzString::from_utf8_lossy(bad.as_ptr(), bad.len()) };
            assert!(
                lossy.as_str().contains('\u{FFFD}'),
                "from_utf8_lossy must substitute U+FFFD for {bad:?}"
            );
            // Both paths must uphold the UTF-8 invariant that as_str() assumes.
            assert!(core::str::from_utf8(lossy.as_bytes()).is_ok());
        }
    }
    #[test]
    fn azstring_from_utf8_keeps_interior_nul() {
        let buf = b"a\0b";
        let s = unsafe { AzString::from_utf8(buf.as_ptr(), buf.len()) };
        assert_eq!(s.len(), 3);
        assert_eq!(s.as_bytes(), b"a\0b");
    }
    #[test]
    fn azstring_from_utf8_handles_a_megabyte() {
        let buf = "y".repeat(1_000_000);
        let s = unsafe { AzString::from_utf8(buf.as_bytes().as_ptr(), buf.len()) };
        assert_eq!(s.len(), 1_000_000);
    }
    // ==================================================================
    // AzString::from_utf16_le / from_utf16_be / from_utf16_with_byte_order
    // ==================================================================
    #[test]
    fn azstring_from_utf16_le_decodes_bmp_and_surrogate_pairs() {
        let text = "héllo \u{1F600}"; // the emoji needs a surrogate pair
        let bytes = utf16_bytes(text, true);
        let s = unsafe { AzString::from_utf16_le(bytes.as_ptr(), bytes.len()) };
        assert_eq!(s.as_str(), text);
    }
    #[test]
    fn azstring_from_utf16_be_decodes_bmp_and_surrogate_pairs() {
        let text = "héllo \u{1F600}";
        let bytes = utf16_bytes(text, false);
        let s = unsafe { AzString::from_utf16_be(bytes.as_ptr(), bytes.len()) };
        assert_eq!(s.as_str(), text);
    }
    #[test]
    fn azstring_from_utf16_byte_order_actually_matters() {
        // Decoding LE bytes as BE must NOT silently yield the same text.
        let le = utf16_bytes("AB", true);
        assert_eq!(le.as_slice(), &[0x41, 0x00, 0x42, 0x00]);
        let as_be = unsafe { AzString::from_utf16_be(le.as_ptr(), le.len()) };
        assert_eq!(
            as_be.as_str(),
            "\u{4100}\u{4200}",
            "BE decode of LE bytes must byte-swap, not guess"
        );
        assert_ne!(as_be.as_str(), "AB");
    }
    #[test]
    fn azstring_from_utf16_odd_length_is_empty() {
        let bytes = utf16_bytes("hello", true);
        let odd = bytes.len() - 1;
        assert_eq!(odd % 2, 1);
        // Still inside the buffer, so this is a safe call — it must be rejected
        // on the length check, not read a half code unit.
        assert!(unsafe { AzString::from_utf16_le(bytes.as_ptr(), odd) }.is_empty());
        assert!(unsafe { AzString::from_utf16_be(bytes.as_ptr(), odd) }.is_empty());
        // The smallest odd length of all:
        assert!(unsafe { AzString::from_utf16_le(bytes.as_ptr(), 1) }.is_empty());
    }
    #[test]
    fn azstring_from_utf16_null_or_zero_len_is_empty() {
        let bytes = utf16_bytes("hi", true);
        assert!(unsafe { AzString::from_utf16_le(core::ptr::null(), 4) }.is_empty());
        assert!(unsafe { AzString::from_utf16_be(core::ptr::null(), 4) }.is_empty());
        assert!(unsafe { AzString::from_utf16_le(bytes.as_ptr(), 0) }.is_empty());
        assert!(unsafe { AzString::from_utf16_be(bytes.as_ptr(), 0) }.is_empty());
    }
    #[test]
    fn azstring_from_utf16_unpaired_surrogate_is_empty() {
        // A lone high surrogate is not valid UTF-16 → documented empty result.
        let lone_high: [u8; 2] = 0xD83C_u16.to_le_bytes();
        assert!(unsafe { AzString::from_utf16_le(lone_high.as_ptr(), 2) }.is_empty());
        // A lone LOW surrogate, and a reversed (low-then-high) pair.
        let lone_low: [u8; 2] = 0xDF89_u16.to_le_bytes();
        assert!(unsafe { AzString::from_utf16_le(lone_low.as_ptr(), 2) }.is_empty());
        let reversed: Vec<u8> = [0xDF89_u16, 0xD83C_u16]
            .iter()
            .flat_map(|u| u.to_le_bytes())
            .collect();
        assert!(unsafe { AzString::from_utf16_le(reversed.as_ptr(), reversed.len()) }.is_empty());
    }
    #[test]
    fn azstring_from_utf16_decodes_noncharacters_and_nul() {
        // U+FFFE / U+0000 are valid code points (not surrogates) — they must
        // decode rather than being treated as an error or a terminator.
        let units: Vec<u8> = [0x0041_u16, 0x0000, 0xFFFE]
            .iter()
            .flat_map(|u| u.to_le_bytes())
            .collect();
        let s = unsafe { AzString::from_utf16_le(units.as_ptr(), units.len()) };
        assert_eq!(s.as_str(), "A\u{0}\u{FFFE}");
        assert_eq!(s.len(), 1 + 1 + 3);
    }
    #[test]
    fn azstring_from_utf16_handles_100k_code_units() {
        let text = "ab".repeat(50_000);
        let bytes = utf16_bytes(&text, true);
        assert_eq!(bytes.len(), 200_000);
        let s = unsafe { AzString::from_utf16_le(bytes.as_ptr(), bytes.len()) };
        assert_eq!(s.len(), 100_000);
    }
    #[test]
    fn azstring_from_utf16_with_byte_order_honours_the_supplied_fn() {
        // The private shared impl must use the caller's byte-order fn verbatim.
        fn swap_halves(b: [u8; 2]) -> u16 {
            u16::from_be_bytes(b)
        }
        let le = utf16_bytes("Az", true);
        let via_shared = unsafe {
            AzString::from_utf16_with_byte_order(le.as_ptr(), le.len(), u16::from_le_bytes)
        };
        assert_eq!(via_shared.as_str(), "Az");
        let swapped =
            unsafe { AzString::from_utf16_with_byte_order(le.as_ptr(), le.len(), swap_halves) };
        assert_eq!(swapped.as_str(), "\u{4100}\u{7A00}");
        // The odd-length / null guards live in the shared impl, so check them here too.
        assert!(unsafe {
            AzString::from_utf16_with_byte_order(le.as_ptr(), 3, u16::from_le_bytes)
        }
        .is_empty());
        assert!(unsafe {
            AzString::from_utf16_with_byte_order(core::ptr::null(), 2, u16::from_le_bytes)
        }
        .is_empty());
    }
    // ==================================================================
    // AzString — getters / predicates / conversions
    // ==================================================================
    #[test]
    fn azstring_as_str_and_as_bytes_agree_for_every_constructor() {
        let buf = "mixed \u{1F600}".as_bytes();
        let mut arena = StringArena::new();
        let strings = [
            AzString::default(),
            AzString::from_const_str("mixed \u{1F600}"),
            AzString::from_string(String::from("mixed \u{1F600}")),
            AzString::from("mixed \u{1F600}"),
            AzString::copy_from_bytes(buf.as_ptr(), 0, buf.len()),
            unsafe { AzString::from_utf8(buf.as_ptr(), buf.len()) },
            arena.intern("mixed \u{1F600}"),
        ];
        for s in &strings {
            assert_eq!(
                s.as_bytes(),
                s.as_str().as_bytes(),
                "as_bytes() and as_str() must view the same memory"
            );
            assert_eq!(s.len(), s.as_bytes().len());
            assert_eq!(s.is_empty(), s.len() == 0);
            let via_as_ref: &str = s.as_ref();
            assert_eq!(via_as_ref, s.as_str(), "AsRef must match as_str");
            assert_eq!(&**s, s.as_str(), "Deref must match as_str");
        }
    }
    #[test]
    fn azstring_is_empty_only_for_zero_bytes() {
        assert!(AzString::default().is_empty());
        assert!(AzString::from_const_str("").is_empty());
        assert!(AzString::from_string(String::new()).is_empty());
        // Whitespace and a NUL byte are content, not emptiness.
        assert!(!AzString::from_const_str(" ").is_empty());
        assert!(!AzString::from_const_str("\t\n").is_empty());
        assert!(!AzString::from_string(String::from("\0")).is_empty());
        assert_eq!(AzString::from_string(String::from("\0")).len(), 1);
    }
    #[test]
    fn azstring_len_counts_bytes_not_chars() {
        assert_eq!(AzString::from_const_str("é").len(), 2);
        assert_eq!(AzString::from_const_str("\u{1F600}").len(), 4);
        assert_eq!(AzString::from_const_str("e\u{0301}").len(), 3); // combining accent
        assert_eq!(
            AzString::from_const_str("\u{1F600}")
                .as_str()
                .chars()
                .count(),
            1
        );
    }
    #[test]
    fn azstring_into_bytes_moves_without_copying_or_double_freeing() {
        let s = AzString::from_string(String::from("payload"));
        let ptr = s.as_bytes().as_ptr();
        let (len, cap) = (s.vec.len, s.vec.cap);
        let v = s.into_bytes();
        assert_eq!(v.as_ref(), b"payload");
        assert_eq!(v.as_ptr(), ptr, "into_bytes must move, not copy");
        assert_eq!(v.len(), len);
        assert_eq!(v.capacity(), cap);
        assert!(matches!(v.destructor, U8VecDestructor::DefaultRust));
        // Dropping `v` here frees the buffer exactly once (the source was
        // ManuallyDrop'd) — a double free would abort the test process.
    }
    #[test]
    fn azstring_into_bytes_preserves_a_non_owning_destructor() {
        let v = AzString::from_const_str("static").into_bytes();
        assert_eq!(v.as_ref(), b"static");
        assert!(
            matches!(v.destructor, U8VecDestructor::NoDestructor),
            "a &'static-backed AzString must not gain a freeing destructor"
        );
    }
    #[test]
    fn azstring_into_bytes_of_empty_is_empty() {
        let v = AzString::default().into_bytes();
        assert!(v.is_empty());
        assert_eq!(v.as_ref(), b"");
    }
    #[test]
    fn azstring_into_library_owned_string_works_for_all_destructors() {
        // DefaultRust: moves the allocation out.
        assert_eq!(
            AzString::from_string(String::from("owned \u{1F600}")).into_library_owned_string(),
            "owned \u{1F600}"
        );
        // NoDestructor: must COPY the static, never take ownership of it.
        assert_eq!(
            AzString::from_const_str("static").into_library_owned_string(),
            "static"
        );
        // External (arena-backed): must copy out of the arena.
        let owned = {
            let mut arena = StringArena::new();
            let s = arena.intern("interned");
            s.into_library_owned_string()
        };
        assert_eq!(
            owned, "interned",
            "must outlive the arena it was copied from"
        );
        // Empty / default.
        assert_eq!(AzString::default().into_library_owned_string(), "");
    }
    #[test]
    fn azstring_into_library_owned_string_copies_static_memory() {
        let mut owned = AzString::from_const_str("static").into_library_owned_string();
        // If this had aliased the &'static str, mutating it would be UB /
        // a segfault writing to rodata.
        owned.push_str(" + mutable");
        assert_eq!(owned, "static + mutable");
    }
    // ==================================================================
    // AzString::clone_self
    // ==================================================================
    #[test]
    fn azstring_clone_self_deep_copies_library_owned_memory() {
        let s = AzString::from_string(String::from("deep"));
        let c = s.clone_self();
        assert_eq!(c, s);
        assert_ne!(
            c.as_bytes().as_ptr(),
            s.as_bytes().as_ptr(),
            "a DefaultRust clone must own a fresh allocation"
        );
        assert!(matches!(c.vec.destructor, U8VecDestructor::DefaultRust));
    }
    #[test]
    fn azstring_clone_self_shares_static_memory() {
        let s = AzString::from_const_str("static");
        let c = s.clone_self();
        assert_eq!(c, s);
        assert_eq!(
            c.as_bytes().as_ptr(),
            s.as_bytes().as_ptr(),
            "cloning a &'static-backed string should alias, not allocate"
        );
        assert!(matches!(c.vec.destructor, U8VecDestructor::NoDestructor));
    }
    #[test]
    fn azstring_clone_self_of_empty_and_unicode() {
        for s in [
            AzString::default(),
            AzString::from_const_str(""),
            AzString::from_string(String::from("\u{1F600}\u{0}\u{0301}")),
        ] {
            let c = s.clone_self();
            assert_eq!(c.as_str(), s.as_str());
            assert_eq!(c.len(), s.len());
        }
    }
    #[test]
    fn azstring_clone_trait_matches_clone_self() {
        let s = AzString::from_string(String::from("via trait"));
        assert_eq!(s.clone(), s.clone_self());
    }
    // ==================================================================
    // AzString — Debug / Display round trips (fmt)
    // ==================================================================
    #[test]
    fn azstring_display_round_trips_through_from() {
        for original in [
            "",
            " ",
            "plain",
            "héllo \u{1F600}",
            "with \"quotes\" and \\ backslash",
            "line\nbreak\ttab",
            "e\u{0301} combining",
        ] {
            let s = AzString::from(original);
            let rendered = format!("{s}");
            assert_eq!(rendered, original, "Display must emit the string verbatim");
            let reparsed = AzString::from(rendered.as_str());
            assert_eq!(reparsed, s, "parse(serialize(x)) == x");
            // serialize(parse(serialize(x))) == serialize(x)
            assert_eq!(format!("{reparsed}"), rendered);
        }
    }
    #[test]
    fn azstring_debug_matches_str_debug_and_escapes() {
        let s = AzString::from("a\"b\\c\nd");
        let expected = format!("{:?}", "a\"b\\c\nd");
        assert_eq!(
            format!("{s:?}"),
            expected,
            "Debug must delegate to str::fmt"
        );
        assert!(
            format!("{s:?}").starts_with('"'),
            "Debug output must be quoted"
        );
        assert!(
            !format!("{s:?}").contains('\n'),
            "Debug must escape newlines"
        );
    }
    #[test]
    fn azstring_debug_and_display_of_empty_do_not_panic() {
        assert_eq!(format!("{:?}", AzString::default()), "\"\"");
        assert_eq!(format!("{}", AzString::default()), "");
        assert_eq!(format!("{:?}", AzString::from_const_str("")), "\"\"");
    }
    #[test]
    fn azstring_display_of_a_megabyte_is_lossless() {
        let huge = "q".repeat(1_000_000);
        let s = AzString::from_string(huge.clone());
        assert_eq!(format!("{s}").len(), huge.len());
    }
    #[test]
    fn azstring_debug_is_stable_across_constructors() {
        // Same text, different memory ownership → identical rendering.
        let buf = "same".as_bytes();
        let a = AzString::from_const_str("same");
        let b = AzString::from_string(String::from("same"));
        let c = AzString::copy_from_bytes(buf.as_ptr(), 0, buf.len());
        assert_eq!(format!("{a:?}"), format!("{b:?}"));
        assert_eq!(format!("{b:?}"), format!("{c:?}"));
        assert_eq!(format!("{a}"), format!("{c}"));
    }
    // ==================================================================
    // AzString — Eq / Ord / Hash invariants
    // ==================================================================
    #[test]
    fn azstring_eq_and_hash_ignore_memory_ownership() {
        let buf = "key".as_bytes();
        let mut arena = StringArena::new();
        let variants = [
            AzString::from_const_str("key"),
            AzString::from_string(String::from("key")),
            AzString::copy_from_bytes(buf.as_ptr(), 0, buf.len()),
            arena.intern("key"),
        ];
        for v in &variants {
            assert_eq!(
                *v, variants[0],
                "equality must compare CONTENT, not pointers"
            );
            assert_eq!(
                hash_of(v),
                hash_of(&variants[0]),
                "Hash must agree with Eq across destructor kinds"
            );
            assert_eq!(
                hash_of(v),
                hash_of(&"key"),
                "AzString must hash like the &str it wraps"
            );
        }
    }
    #[test]
    fn azstring_ord_matches_str_ord() {
        let mut v = [
            AzString::from("b"),
            AzString::from(""),
            AzString::from("\u{1F600}"),
            AzString::from("a"),
            AzString::from("ab"),
        ];
        v.sort();
        let sorted: Vec<&str> = v.iter().map(AzString::as_str).collect();
        assert_eq!(sorted, ["", "a", "ab", "b", "\u{1F600}"]);
        assert_eq!(
            AzString::from("a").partial_cmp(&AzString::from("b")),
            Some(core::cmp::Ordering::Less)
        );
        assert_eq!(
            AzString::from("x").cmp(&AzString::from("x")),
            core::cmp::Ordering::Equal
        );
    }
    // ==================================================================
    // StringArena
    // ==================================================================
    #[test]
    fn arena_new_starts_empty() {
        let arena = StringArena::new();
        assert_eq!(arena.metrics(), (0, 0), "a fresh arena allocates nothing");
        assert_eq!(StringArena::default().metrics(), (0, 0));
    }
    #[test]
    fn arena_metrics_track_chunks_and_bytes() {
        let mut arena = StringArena::new();
        let _a = arena.intern("abc");
        let (chunks, bytes) = arena.metrics();
        assert_eq!(chunks, 1);
        assert_eq!(bytes, 3);
        let _b = arena.intern("de");
        let (chunks, bytes) = arena.metrics();
        assert_eq!(chunks, 1, "a second small string reuses the open chunk");
        assert_eq!(bytes, 5);
    }
    #[test]
    fn arena_empty_string_allocates_nothing_and_is_readable() {
        let mut arena = StringArena::new();
        let e = arena.intern("");
        assert!(e.is_empty());
        assert_eq!(e.as_str(), "");
        assert_eq!(arena.metrics(), (0, 0), "empty strings need no storage");
        assert!(
            !e.vec.ptr.is_null(),
            "the dangling ptr must still be non-null"
        );
    }
    #[test]
    fn arena_string_is_external_and_stashes_an_arc_in_cap() {
        let mut arena = StringArena::new();
        let s = arena.intern("hi");
        assert!(matches!(s.vec.destructor, U8VecDestructor::External(_)));
        assert_ne!(s.vec.cap, 0, "cap holds the Arc pointer, not a capacity");
        assert_eq!(s.as_str(), "hi");
    }
    #[test]
    fn arena_intern_refcounts_each_string() {
        let mut arena = StringArena::new();
        assert_eq!(Arc::strong_count(&arena.inner), 1);
        let a = arena.intern("one");
        let b = arena.intern("two");
        assert_eq!(
            Arc::strong_count(&arena.inner),
            3,
            "each interned string must hold its own Arc reference"
        );
        drop(a);
        assert_eq!(Arc::strong_count(&arena.inner), 2);
        drop(b);
        assert_eq!(Arc::strong_count(&arena.inner), 1);
    }
    #[test]
    fn arena_clone_deep_copies_and_does_not_bump_the_refcount() {
        let mut arena = StringArena::new();
        let s = arena.intern("interned");
        let c = s.clone_self();
        assert_eq!(
            Arc::strong_count(&arena.inner),
            2,
            "cloning an External string deep-copies; it must NOT retain the arena"
        );
        assert!(matches!(c.vec.destructor, U8VecDestructor::DefaultRust));
        assert_eq!(c.as_str(), "interned");
        assert_ne!(c.vec.ptr, s.vec.ptr);
    }
    #[test]
    fn arena_clone_outlives_the_arena_and_the_original() {
        let clone = {
            let mut arena = StringArena::new();
            let s = arena.intern("deep-copied out of the arena");
            let c = s.clone_self();
            drop(s);
            drop(arena);
            c
        };
        assert_eq!(clone.as_str(), "deep-copied out of the arena");
    }
    #[test]
    fn arena_exact_half_chunk_boundary_fills_one_chunk_exactly() {
        // len == CHUNK_SIZE / 2 is NOT "oversized" (the check is `>`), so two of
        // them must fit in a single chunk with zero reallocation, and the third
        // must open a new one.
        let mut arena = StringArena::new();
        let half = "h".repeat(StringArena::CHUNK_SIZE / 2);
        let a = arena.intern(&half);
        let b = arena.intern(&half);
        assert_eq!(arena.metrics().0, 1, "two half-chunks must share one chunk");
        let c = arena.intern(&half);
        assert_eq!(arena.metrics().0, 2, "the third must open a new chunk");
        // If the exact-fit append had reallocated, `a`/`b` would now dangle.
        assert_eq!(a.as_str(), half);
        assert_eq!(b.as_str(), half);
        assert_eq!(c.as_str(), half);
    }
    #[test]
    fn arena_oversized_string_is_readable_and_gets_its_own_chunk() {
        let mut arena = StringArena::new();
        let big = "b".repeat(StringArena::CHUNK_SIZE + 1);
        let s = arena.intern(&big);
        assert_eq!(s.len(), big.len());
        assert_eq!(s.as_str(), big.as_str());
        assert_eq!(arena.metrics(), (1, big.len()));
    }
    #[test]
    fn arena_many_interleaved_sizes_all_read_back_correctly() {
        let mut arena = StringArena::new();
        let mut kept = Vec::new();
        for i in 0..200 {
            let s = format!("s{i}-{}", "p".repeat(i % 17));
            kept.push((arena.intern(&s), s));
        }
        for (interned, expected) in &kept {
            assert_eq!(interned.as_str(), expected.as_str());
        }
    }
    #[test]
    fn arena_interns_unicode_and_nul_bytes_verbatim() {
        let mut arena = StringArena::new();
        let weird = "héllo \u{1F600}\u{0}\u{0301}";
        let s = arena.intern(weird);
        assert_eq!(s.as_str(), weird);
        assert_eq!(s.len(), weird.len());
    }
    #[test]
    fn arena_strings_outlive_the_handle_even_when_interleaved() {
        let (a, b) = {
            let mut arena = StringArena::new();
            let a = arena.intern("first");
            let big = "z".repeat(StringArena::CHUNK_SIZE * 2);
            let _dropped = arena.intern(&big);
            let b = arena.intern("second");
            (a, b)
        };
        assert_eq!(a.as_str(), "first");
        assert_eq!(b.as_str(), "second");
    }
    /// RED — genuine bug in `StringArena::intern` (use-after-free).
    ///
    /// The oversized branch pushes a *dedicated, completely full* chunk
    /// (`len == cap`) but never touches `current_remaining`. If a small string
    /// was interned first, `remaining` is still > 0, so the next small intern
    /// skips the "push a fresh chunk" branch and appends into
    /// `chunks.last_mut()` — which is now that full dedicated chunk. The
    /// `extend_from_slice` therefore grows a `len == cap` Vec, reallocating it
    /// and leaving the `AzString` handed out for the oversized string pointing
    /// at freed memory.
    ///
    /// This test only inspects chunk *lengths* — it never dereferences the
    /// dangling pointer, so the test itself stays UB-free.
    #[test]
    fn arena_small_after_oversized_must_not_grow_the_full_dedicated_chunk() {
        let mut arena = StringArena::new();
        // 1. open a shared chunk, leaving current_remaining > 0
        let _small = arena.intern("a");
        // 2. oversized → dedicated chunk with len == cap == big_len
        let big = "x".repeat(StringArena::CHUNK_SIZE);
        let big_len = big.len();
        let interned_big = arena.intern(&big);
        assert_eq!(
            interned_big.as_str(),
            big.as_str(),
            "valid before the next intern"
        );
        // 3. another small string: must NOT be appended into the full chunk
        let _small2 = arena.intern("y");
        // Safety: read-only look at the chunk lengths; no chunk data is read
        // and the (possibly dangling) `interned_big.vec.ptr` is never deref'd.
        let grew = unsafe {
            let chunks = &*arena.inner.chunks.get();
            chunks.iter().any(|c| c.len() > big_len)
        };
        assert!(
            !grew,
            "intern() appended a small string into the FULL dedicated chunk of an oversized \
             string (len == cap), which reallocates that Vec and leaves every AzString pointing \
             into it dangling — a use-after-free. Root cause: the oversized branch pushes a chunk \
             without resetting `current_remaining`, so the next small string takes the \
             `chunks.last_mut()` fast path onto the wrong chunk."
        );
    }
    // ==================================================================
    // arena_string_destructor
    // ==================================================================
    #[test]
    fn arena_destructor_drops_one_arc_ref_and_is_idempotent() {
        let inner = Arc::new(StringArenaInner {
            chunks: UnsafeCell::new(Vec::new()),
            current_remaining: UnsafeCell::new(0),
        });
        let raw = Arc::into_raw(Arc::clone(&inner));
        assert_eq!(Arc::strong_count(&inner), 2);
        let mut v = U8Vec {
            ptr: core::ptr::NonNull::<u8>::dangling().as_ptr().cast_const(),
            len: 0,
            cap: raw as usize,
            destructor: U8VecDestructor::External(arena_string_destructor),
        };
        arena_string_destructor(&mut v);
        assert_eq!(
            Arc::strong_count(&inner),
            1,
            "the destructor must release exactly one Arc reference"
        );
        assert_eq!(
            v.cap, 0,
            "cap must be zeroed to guard against a double drop"
        );
        // A second call must be a no-op rather than a double free.
        arena_string_destructor(&mut v);
        assert_eq!(Arc::strong_count(&inner), 1);
        assert_eq!(v.cap, 0);
        // `v` still carries the External destructor; dropping it runs the
        // destructor a third time — also a no-op, since cap == 0.
        drop(v);
        assert_eq!(Arc::strong_count(&inner), 1);
    }
    #[test]
    fn arena_destructor_tolerates_a_null_arc_pointer() {
        // cap == 0 (e.g. a zeroed FFI husk) must not be turned into Arc::from_raw(null).
        let mut v = U8Vec {
            ptr: core::ptr::null(),
            len: 0,
            cap: 0,
            destructor: U8VecDestructor::NoDestructor,
        };
        arena_string_destructor(&mut v);
        assert_eq!(v.cap, 0);
    }
    #[test]
    fn arena_last_reference_frees_the_chunks() {
        // The arena's bytes must survive until the LAST AzString goes away,
        // and dropping in either order must not double-free.
        let inner_ptr;
        let s = {
            let mut arena = StringArena::new();
            let s = arena.intern("outlives the handle");
            inner_ptr = Arc::as_ptr(&arena.inner);
            assert_eq!(Arc::strong_count(&arena.inner), 2);
            s
        };
        // The arena handle is gone but the string still owns a reference.
        assert_eq!(s.as_str(), "outlives the handle");
        assert_eq!(s.vec.cap as *const StringArenaInner, inner_ptr);
        drop(s); // final reference → chunks freed here, exactly once
    }
}