azul-css 0.0.7

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
use alloc::{
    string::{String, ToString},
    vec::Vec,
};

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

// ============================================================================
// Void 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<Void, Error>`.
/// 
/// # Example
/// ```ignore
/// fn do_something() -> Result<Void, MyError> {
///     // ... do work ...
///     Ok(Void::default())
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct Void {
    /// Reserved byte to ensure the struct has non-zero size.
    /// Always initialized to 0.
    pub _reserved: u8,
}

impl Default for Void {
    fn default() -> Self {
        Self { _reserved: 0 }
    }
}

impl Void {
    /// Create a new Void value (equivalent to `()`)
    pub const fn new() -> Self {
        Self { _reserved: 0 }
    }
}

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

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

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

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

impl Default for LayoutDebugMessageType {
    fn default() -> Self {
        Self::Info
    }
}

// Define a struct for debug messages
#[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)
    }
}

#[repr(C)]
pub struct AzString {
    pub vec: U8Vec,
}

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

/// Type alias for compatibility - OptionAzString is the same as OptionString
pub type OptionAzString = OptionString;

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<'a>(&'a self) -> &'a 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
    #[inline]
    pub unsafe fn from_c_str(ptr: *const core::ffi::c_char) -> Self {
        if ptr.is_null() {
            return Self::default();
        }
        let c_str = core::ffi::CStr::from_ptr(ptr);
        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.
    #[inline]
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
        Self {
            vec: U8Vec::copy_from_bytes(ptr, start, len),
        }
    }

    #[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(_) => {
                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,
            run_destructor: m.vec.run_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)
    }

    /// 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 {
        if ptr.is_null() || len == 0 {
            return Self::default();
        }
        
        // UTF-16 requires pairs of bytes
        if len % 2 != 0 {
            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| u16::from_le_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 (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 {
        if ptr.is_null() || len == 0 {
            return Self::default();
        }
        
        // UTF-16 requires pairs of bytes
        if len % 2 != 0 {
            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| u16::from_be_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-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.
    #[inline]
    pub fn copy_from_bytes(ptr: *const u8, start: usize, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::new();
        }
        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)
            }
        }
    }
}