azul-css 0.0.8

Common datatypes used for styling applications using the Azul desktop GUI framework
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
//! Core FFI-safe types used across crate boundaries.
//!
//! This module defines the fundamental types for FFI interop: [`AzString`] (an FFI-safe
//! string backed by [`U8Vec`] with destructor-based memory management), [`EmptyStruct`] (a
//! non-zero-size unit type), and various `Vec`/`Option` wrappers generated by the
//! `impl_vec!` and `impl_option!` macros.

use alloc::{
    string::{String, ToString},
    vec::Vec,
};

use crate::props::basic::ColorU;

// ============================================================================
// EmptyStruct type - FFI-safe replacement for ()
// ============================================================================

/// FFI-safe void type to replace `()` in Result types.
/// 
/// Since `()` (unit type) has zero size, it's not FFI-safe.
/// This type provides a minimal 1-byte representation that can be
/// safely passed across the C ABI boundary.
/// 
/// # Usage
/// Instead of `Result<(), Error>`, use `Result<EmptyStruct, Error>`.
/// 
/// # Example
/// ```ignore
/// fn do_something() -> Result<EmptyStruct, MyError> {
///     // ... do work ...
///     Ok(EmptyStruct::default())
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
#[derive(Default)]
pub struct EmptyStruct {
    /// Reserved byte to ensure the struct has non-zero size.
    /// Always initialized to 0.
    pub _reserved: u8,
}


impl EmptyStruct {
    /// Create a new EmptyStruct value (equivalent to `()`)
    #[must_use]
    pub const fn new() -> Self {
        Self { _reserved: 0 }
    }
}

impl From<()> for EmptyStruct {
    fn from(_: ()) -> Self {
        Self::default()
    }
}

impl From<EmptyStruct> for () {
    fn from(_: EmptyStruct) -> Self {
        
    }
}

// ============================================================================
// Debug message types
// ============================================================================

/// Debug message severity or category for layout diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
#[derive(Default)]
pub enum LayoutDebugMessageType {
    #[default]
    Info,
    Warning,
    Error,
    // Layout-specific categories for filtering
    BoxProps,
    CssGetter,
    /// Block Formatting Context layout
    BfcLayout,
    /// Inline Formatting Context layout
    IfcLayout,
    TableLayout,
    DisplayType,
    PositionCalculation,
}


/// A debug message emitted during layout, with severity, text, and source location.
#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
#[repr(C)]
pub struct LayoutDebugMessage {
    pub message_type: LayoutDebugMessageType,
    pub message: AzString,
    pub location: AzString,
}

impl LayoutDebugMessage {
    /// Create a new debug message with automatic caller location tracking
    #[track_caller]
    pub fn new(message_type: LayoutDebugMessageType, message: impl Into<String>) -> Self {
        let location = core::panic::Location::caller();
        Self {
            message_type,
            message: AzString::from_string(message.into()),
            location: AzString::from_string(format!(
                "{}:{}:{}",
                location.file(),
                location.line(),
                location.column()
            )),
        }
    }

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

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

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

    /// Helper for BoxProps debug messages
    #[track_caller]
    pub fn box_props(message: impl Into<String>) -> Self {
        Self::new(LayoutDebugMessageType::BoxProps, message)
    }

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

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

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

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

    /// Helper for Display Type debug messages
    #[track_caller]
    pub fn display_type(message: impl Into<String>) -> Self {
        Self::new(LayoutDebugMessageType::DisplayType, message)
    }
}

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

impl_option!(
    AzString,
    OptionString,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

static DEFAULT_STR: &str = "";

impl Default for AzString {
    fn default() -> Self {
        DEFAULT_STR.into()
    }
}

impl<'a> From<&'a str> for AzString {
    fn from(s: &'a str) -> Self {
        s.to_string().into()
    }
}

impl AsRef<str> for AzString {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl core::fmt::Debug for AzString {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.as_str().fmt(f)
    }
}

impl core::fmt::Display for AzString {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        self.as_str().fmt(f)
    }
}

impl AzString {
    #[inline]
    pub const fn from_const_str(s: &'static str) -> Self {
        Self {
            vec: U8Vec::from_const_slice(s.as_bytes()),
        }
    }

    /// Creates a new AzString from a null-terminated C string (const char*).
    /// This copies the string data into a new allocation.
    ///
    /// # Safety
    /// - `ptr` must be a valid pointer to a null-terminated UTF-8 string
    /// - The string must remain valid for the duration of this call
    ///
    /// Note: `ptr` is `*const i8` rather than `*const core::ffi::c_char`
    /// so the auto-generated FFI signature in `dll_api_internal.rs`
    /// (which uses a literal `i8`) matches on every target —
    /// `c_char` is `i8` on x86/ARM Apple/Windows/Linux but `u8` on
    /// Android, which would otherwise produce a `*const u8 vs *const i8`
    /// mismatch at codegen-call sites. We cast internally before
    /// handing the pointer to `CStr::from_ptr`.
    #[inline]
    pub unsafe fn from_c_str(ptr: *const i8) -> Self {
        if ptr.is_null() {
            return Self::default();
        }
        let c_str = core::ffi::CStr::from_ptr(ptr as *const core::ffi::c_char);
        let bytes = c_str.to_bytes();
        Self::copy_from_bytes(bytes.as_ptr(), 0, bytes.len())
    }

    /// Copies bytes from a pointer into a new AzString.
    /// This is useful for C FFI where you have a char* buffer.
    ///
    /// Invalid UTF-8 sequences are replaced with U+FFFD to maintain
    /// the UTF-8 invariant required by [`as_str()`](Self::as_str).
    #[inline]
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
        let raw = U8Vec::copy_from_bytes(ptr, start, len);
        let s = String::from_utf8_lossy(raw.as_ref()).into_owned();
        Self::from_string(s)
    }

    #[inline]
    pub fn from_string(s: String) -> Self {
        Self {
            vec: U8Vec::from_vec(s.into_bytes()),
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        unsafe { core::str::from_utf8_unchecked(self.vec.as_ref()) }
    }

    /// NOTE: CLONES the memory if the memory is external or &'static
    /// Moves the memory out if the memory is library-allocated
    #[inline]
    pub fn clone_self(&self) -> Self {
        Self {
            vec: self.vec.clone_self(),
        }
    }

    #[inline]
    pub fn into_library_owned_string(self) -> String {
        match self.vec.destructor {
            U8VecDestructor::NoDestructor | U8VecDestructor::External(_) | U8VecDestructor::AlreadyDestroyed => {
                self.as_str().to_string()
            }
            U8VecDestructor::DefaultRust => {
                let m = core::mem::ManuallyDrop::new(self);
                unsafe { String::from_raw_parts(m.vec.ptr as *mut u8, m.vec.len, m.vec.cap) }
            }
        }
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.vec.as_ref()
    }

    #[inline]
    pub fn into_bytes(self) -> U8Vec {
        let m = core::mem::ManuallyDrop::new(self);
        U8Vec {
            ptr: m.vec.ptr,
            len: m.vec.len,
            cap: m.vec.cap,
            destructor: m.vec.destructor,
        }
    }

    /// Returns the length of the string in bytes (not including null terminator)
    #[inline]
    pub fn len(&self) -> usize {
        self.vec.len
    }

    /// Returns true if the string is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.vec.len == 0
    }

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

    /// Shared implementation for UTF-16 decoding with a caller-supplied byte-order function.
    ///
    /// # Safety
    /// - `ptr` must be valid for reading `len` bytes
    /// - `len` must be even (UTF-16 uses 2 bytes per code unit)
    unsafe fn from_utf16_with_byte_order(
        ptr: *const u8,
        len: usize,
        from_bytes: fn([u8; 2]) -> u16,
    ) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::default();
        }

        // UTF-16 requires pairs of bytes
        if !len.is_multiple_of(2) {
            return Self::default();
        }

        let byte_slice = core::slice::from_raw_parts(ptr, len);
        let code_units: Vec<u16> = byte_slice
            .chunks_exact(2)
            .map(|chunk| from_bytes([chunk[0], chunk[1]]))
            .collect();

        match String::from_utf16(&code_units) {
            Ok(s) => Self::from_string(s),
            Err(_) => Self::default(),
        }
    }

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

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

    /// Creates a new AzString from UTF-8 bytes with lossy conversion.
    /// Invalid UTF-8 sequences are replaced with the Unicode replacement character (U+FFFD).
    ///
    /// # Safety
    /// - `ptr` must be valid for reading `len` bytes
    #[inline]
    pub unsafe fn from_utf8_lossy(ptr: *const u8, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::default();
        }
        
        let byte_slice = core::slice::from_raw_parts(ptr, len);
        let s = String::from_utf8_lossy(byte_slice).into_owned();
        Self::from_string(s)
    }

    /// Creates a new AzString from UTF-8 bytes.
    /// Returns an empty string if the input is not valid UTF-8.
    ///
    /// # Safety
    /// - `ptr` must be valid for reading `len` bytes
    #[inline]
    pub unsafe fn from_utf8(ptr: *const u8, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::default();
        }
        
        let byte_slice = core::slice::from_raw_parts(ptr, len);
        match core::str::from_utf8(byte_slice) {
            Ok(s) => Self::from_string(s.to_string()),
            Err(_) => Self::default(),
        }
    }
}

impl From<String> for AzString {
    fn from(input: String) -> AzString {
        AzString::from_string(input)
    }
}

impl PartialOrd for AzString {
    fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
        self.as_str().partial_cmp(rhs.as_str())
    }
}

impl Ord for AzString {
    fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
        self.as_str().cmp(rhs.as_str())
    }
}

impl Clone for AzString {
    fn clone(&self) -> Self {
        self.clone_self()
    }
}

impl PartialEq for AzString {
    fn eq(&self, rhs: &Self) -> bool {
        self.as_str().eq(rhs.as_str())
    }
}

impl Eq for AzString {}

impl core::hash::Hash for AzString {
    fn hash<H>(&self, state: &mut H)
    where
        H: core::hash::Hasher,
    {
        self.as_str().hash(state)
    }
}

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

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl_option!(
    u8,
    OptionU8,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

impl_vec!(u8, U8Vec, U8VecDestructor, U8VecDestructorType, U8VecSlice, OptionU8);
impl_vec_mut!(u8, U8Vec);
impl_vec_debug!(u8, U8Vec);
impl_vec_partialord!(u8, U8Vec);
impl_vec_ord!(u8, U8Vec);
impl_vec_clone!(u8, U8Vec, U8VecDestructor);
impl_vec_partialeq!(u8, U8Vec);
impl_vec_eq!(u8, U8Vec);
impl_vec_hash!(u8, U8Vec);

impl U8Vec {
    /// Copies bytes from a pointer into a new Vec.
    /// This is useful for C FFI where you have a uint8_t* buffer.
    ///
    /// # Safety contract (caller must ensure)
    /// - `ptr` must be valid for reading `start + len` bytes
    /// - `start + len` must not overflow
    #[inline]
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::new();
        }
        debug_assert!(
            start.checked_add(len).is_some(),
            "U8Vec::copy_from_bytes: start + len overflows"
        );
        let slice = unsafe { core::slice::from_raw_parts(ptr.add(start), len) };
        Self::from_vec(slice.to_vec())
    }
}

impl_option!(
    U8Vec,
    OptionU8Vec,
    copy = false,
    [Debug, Clone, PartialEq, Ord, PartialOrd, Eq, Hash]
);

impl_vec!(u16, U16Vec, U16VecDestructor, U16VecDestructorType, U16VecSlice, OptionU16);
impl_vec_debug!(u16, U16Vec);
impl_vec_partialord!(u16, U16Vec);
impl_vec_ord!(u16, U16Vec);
impl_vec_clone!(u16, U16Vec, U16VecDestructor);
impl_vec_partialeq!(u16, U16Vec);
impl_vec_eq!(u16, U16Vec);
impl_vec_hash!(u16, U16Vec);

impl_vec!(f32, F32Vec, F32VecDestructor, F32VecDestructorType, F32VecSlice, OptionF32);
impl_vec_debug!(f32, F32Vec);
impl_vec_partialord!(f32, F32Vec);
impl_vec_clone!(f32, F32Vec, F32VecDestructor);
impl_vec_partialeq!(f32, F32Vec);

// Vec<char>
impl_vec!(u32, U32Vec, U32VecDestructor, U32VecDestructorType, U32VecSlice, OptionU32);
impl_vec_mut!(u32, U32Vec);
impl_vec_debug!(u32, U32Vec);
impl_vec_partialord!(u32, U32Vec);
impl_vec_ord!(u32, U32Vec);
impl_vec_clone!(u32, U32Vec, U32VecDestructor);
impl_vec_partialeq!(u32, U32Vec);
impl_vec_eq!(u32, U32Vec);
impl_vec_hash!(u32, U32Vec);

impl_vec!(AzString, StringVec, StringVecDestructor, StringVecDestructorType, StringVecSlice, OptionString);
impl_vec_debug!(AzString, StringVec);
impl_vec_partialord!(AzString, StringVec);
impl_vec_ord!(AzString, StringVec);
impl_vec_clone!(AzString, StringVec, StringVecDestructor);
impl_vec_partialeq!(AzString, StringVec);
impl_vec_eq!(AzString, StringVec);
impl_vec_hash!(AzString, StringVec);

impl From<Vec<String>> for StringVec {
    fn from(v: Vec<String>) -> StringVec {
        let new_v: Vec<AzString> = v.into_iter().map(|s| s.into()).collect();
        new_v.into()
    }
}

impl_option!(
    StringVec,
    OptionStringVec,
    copy = false,
    [Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash]
);

impl_option!(
    u16,
    OptionU16,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    u32,
    OptionU32,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    u64,
    OptionU64,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    usize,
    OptionUsize,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    i16,
    OptionI16,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    i32,
    OptionI32,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(bool, OptionBool, [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]);
impl_option!(f32, OptionF32, [Debug, Copy, Clone, PartialEq, PartialOrd]);
impl_option!(f64, OptionF64, [Debug, Copy, Clone, PartialEq, PartialOrd]);

// Manual implementations for Hash and Ord on OptionF32 (since f32 doesn't implement these traits)
impl core::hash::Hash for OptionF32 {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        match self {
            OptionF32::None => 0u8.hash(state),
            OptionF32::Some(v) => {
                1u8.hash(state);
                v.to_bits().hash(state);
            }
        }
    }
}

impl Eq for OptionF32 {}

impl Ord for OptionF32 {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        match (self, other) {
            (OptionF32::None, OptionF32::None) => core::cmp::Ordering::Equal,
            (OptionF32::None, OptionF32::Some(_)) => core::cmp::Ordering::Less,
            (OptionF32::Some(_), OptionF32::None) => core::cmp::Ordering::Greater,
            (OptionF32::Some(a), OptionF32::Some(b)) => {
                a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal)
            }
        }
    }
}

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

use alloc::sync::Arc;
use core::cell::UnsafeCell;

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

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

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

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

    pub fn new() -> Self {
        Self {
            inner: Arc::new(StringArenaInner {
                chunks: UnsafeCell::new(Vec::new()),
                current_remaining: UnsafeCell::new(0),
            }),
        }
    }

    /// Returns `(chunk_count, total_bytes_used)` for metrics.
    pub fn metrics(&self) -> (usize, usize) {
        // Safety: metrics is read-only; the caller holds &self so no
        // concurrent mutation via &mut self is possible.
        unsafe {
            let chunks = &*self.inner.chunks.get();
            let total: usize = chunks.iter().map(|c| c.len()).sum();
            (chunks.len(), total)
        }
    }

    /// Intern `s` into the arena and return an AzString whose backing
    /// bytes live inside the arena. The returned AzString owns a cloned
    /// `Arc` reference; dropping it decrements the refcount, and the
    /// arena frees its chunks when the final reference is released.
    pub fn intern(&mut self, s: &str) -> AzString {
        let bytes = s.as_bytes();
        let len = bytes.len();

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

                // Oversized strings get their own dedicated chunk so we
                // don't waste the tail of the current chunk.
                if len > Self::CHUNK_SIZE / 2 {
                    let mut v = Vec::with_capacity(len);
                    v.extend_from_slice(bytes);
                    let p = v.as_ptr();
                    chunks.push(v);
                    p
                } else {
                    if *remaining < len {
                        chunks.push(Vec::with_capacity(Self::CHUNK_SIZE));
                        *remaining = Self::CHUNK_SIZE;
                    }
                    // Safety: chunk was allocated with capacity ≥ len and
                    // `remaining` tracks unused capacity — no realloc.
                    let chunk = chunks.last_mut().unwrap();
                    let offset = chunk.len();
                    chunk.extend_from_slice(bytes);
                    *remaining -= len;
                    chunk.as_ptr().add(offset)
                }
            }
        };

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

        AzString {
            vec: U8Vec {
                ptr,
                len,
                // NOTE: `cap` stores an Arc pointer, not a capacity. This
                // works because the `External` destructor path never calls
                // `Vec::from_raw_parts(ptr, len, cap)` — only `DefaultRust`
                // does that.
                cap: arc_raw as usize,
                destructor: U8VecDestructor::External(arena_string_destructor),
            },
        }
    }
}

impl Default for StringArena {
    fn default() -> Self {
        Self::new()
    }
}

/// Destructor installed on every arena-backed AzString. Reads the Arc
/// pointer out of `cap` and drops one Arc reference; when the count
/// reaches zero the `StringArenaInner` is freed.
extern "C" fn arena_string_destructor(vec: *mut U8Vec) {
    // Safety: called at most once per AzString drop. `cap` was set by
    // `StringArena::intern` to `Arc::into_raw(Arc<StringArenaInner>)`.
    unsafe {
        let v = &mut *vec;
        let arc_raw = v.cap as *const StringArenaInner;
        if !arc_raw.is_null() {
            let _ = Arc::from_raw(arc_raw);
            // Prevent a hypothetical double-drop from dereferencing
            // freed memory.
            v.cap = 0;
        }
    }
}

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

    #[test]
    fn intern_round_trip() {
        let mut arena = StringArena::new();
        let a = arena.intern("hello");
        let b = arena.intern("world");
        let c = arena.intern("");
        assert_eq!(a.as_str(), "hello");
        assert_eq!(b.as_str(), "world");
        assert_eq!(c.as_str(), "");
    }

    #[test]
    fn strings_outlive_arena_handle() {
        let a = {
            let mut arena = StringArena::new();
            arena.intern("survives drop of arena handle")
        };
        assert_eq!(a.as_str(), "survives drop of arena handle");
    }

    #[test]
    fn oversized_string_gets_dedicated_chunk() {
        let mut arena = StringArena::new();
        let big = "x".repeat(StringArena::CHUNK_SIZE);
        let s = arena.intern(&big);
        assert_eq!(s.len(), big.len());
        assert_eq!(s.as_str(), big.as_str());
    }

    #[test]
    fn many_small_strings_share_chunk() {
        let mut arena = StringArena::new();
        let mut strings = Vec::new();
        for i in 0..100 {
            strings.push(arena.intern(&format!("s{i}")));
        }
        let (chunks, _bytes) = arena.metrics();
        assert!(chunks <= 2, "expected ≤2 chunks for 100 small strings, got {chunks}");
        for (i, s) in strings.iter().enumerate() {
            assert_eq!(s.as_str(), format!("s{i}"));
        }
    }

    #[test]
    fn clone_deep_copies_and_is_independent() {
        // Cloning an External AzString deep-copies into DefaultRust, so
        // the clone doesn't depend on the arena at all.
        let clone = {
            let mut arena = StringArena::new();
            let a = arena.intern("deep-copy test");
            a.clone()
        };
        assert_eq!(clone.as_str(), "deep-copy test");
    }
}