azul_css/
lib.rs

1//! Provides datatypes used to describe an application's style using the Azul GUI framework.
2#![allow(warnings)]
3
4// #![no_std]
5
6#[macro_use]
7extern crate alloc;
8extern crate core;
9
10#[cfg(feature = "parser")]
11pub mod parser;
12
13use alloc::{
14    string::{String, ToString},
15    vec::Vec,
16};
17
18#[macro_export]
19macro_rules! impl_vec {
20    ($struct_type:ident, $struct_name:ident, $destructor_name:ident) => {
21        #[repr(C)]
22        pub struct $struct_name {
23            ptr: *const $struct_type,
24            len: usize,
25            cap: usize,
26            destructor: $destructor_name,
27        }
28
29        #[derive(Debug, Copy, Clone)]
30        #[repr(C, u8)]
31        pub enum $destructor_name {
32            DefaultRust,
33            NoDestructor,
34            External(extern "C" fn(*mut $struct_name)),
35        }
36
37        unsafe impl Send for $struct_name {}
38        unsafe impl Sync for $struct_name {}
39
40        impl $struct_name {
41            #[inline(always)]
42            pub fn new() -> $struct_name {
43                // lets hope the optimizer catches this
44                Self::from_vec(alloc::vec::Vec::new())
45            }
46
47            #[inline]
48            pub fn with_capacity(cap: usize) -> Self {
49                Self::from_vec(alloc::vec::Vec::<$struct_type>::with_capacity(cap))
50            }
51
52            #[inline(always)]
53            pub const fn from_const_slice(input: &'static [$struct_type]) -> Self {
54                Self {
55                    ptr: input.as_ptr(),
56                    len: input.len(),
57                    cap: input.len(),
58                    destructor: $destructor_name::NoDestructor, // because of &'static
59                }
60            }
61
62            #[inline(always)]
63            pub fn from_vec(input: alloc::vec::Vec<$struct_type>) -> Self {
64                let ptr = input.as_ptr();
65                let len = input.len();
66                let cap = input.capacity();
67
68                let _ = ::core::mem::ManuallyDrop::new(input);
69
70                Self {
71                    ptr,
72                    len,
73                    cap,
74                    destructor: $destructor_name::DefaultRust,
75                }
76            }
77
78            #[inline]
79            pub fn iter(&self) -> core::slice::Iter<$struct_type> {
80                self.as_ref().iter()
81            }
82
83            #[inline(always)]
84            pub fn ptr_as_usize(&self) -> usize {
85                self.ptr as usize
86            }
87
88            #[inline(always)]
89            pub const fn len(&self) -> usize {
90                self.len
91            }
92
93            #[inline(always)]
94            pub const fn capacity(&self) -> usize {
95                self.cap
96            }
97
98            #[inline(always)]
99            pub const fn is_empty(&self) -> bool {
100                self.len == 0
101            }
102
103            #[inline(always)]
104            pub fn get(&self, index: usize) -> Option<&$struct_type> {
105                let v1: &[$struct_type] = self.as_ref();
106                let res = v1.get(index);
107                res
108            }
109
110            #[allow(dead_code)]
111            #[inline(always)]
112            unsafe fn get_unchecked(&self, index: usize) -> &$struct_type {
113                let v1: &[$struct_type] = self.as_ref();
114                let res = v1.get_unchecked(index);
115                res
116            }
117
118            #[inline(always)]
119            pub fn as_slice(&self) -> &[$struct_type] {
120                self.as_ref()
121            }
122        }
123
124        impl AsRef<[$struct_type]> for $struct_name {
125            fn as_ref(&self) -> &[$struct_type] {
126                unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
127            }
128        }
129
130        impl Default for $struct_name {
131            fn default() -> Self {
132                Self::from_vec(alloc::vec::Vec::new())
133            }
134        }
135
136        impl core::iter::FromIterator<$struct_type> for $struct_name {
137            fn from_iter<T>(iter: T) -> Self
138            where
139                T: IntoIterator<Item = $struct_type>,
140            {
141                Self::from_vec(alloc::vec::Vec::from_iter(iter))
142            }
143        }
144
145        impl From<alloc::vec::Vec<$struct_type>> for $struct_name {
146            fn from(input: alloc::vec::Vec<$struct_type>) -> $struct_name {
147                $struct_name::from_vec(input)
148            }
149        }
150
151        impl From<&'static [$struct_type]> for $struct_name {
152            fn from(input: &'static [$struct_type]) -> $struct_name {
153                Self::from_const_slice(input)
154            }
155        }
156
157        impl Drop for $struct_name {
158            fn drop(&mut self) {
159                match self.destructor {
160                    $destructor_name::DefaultRust => {
161                        let _ = unsafe {
162                            alloc::vec::Vec::from_raw_parts(
163                                self.ptr as *mut $struct_type,
164                                self.len,
165                                self.cap,
166                            )
167                        };
168                    }
169                    $destructor_name::NoDestructor => {}
170                    $destructor_name::External(f) => {
171                        f(self);
172                    }
173                }
174                // necessary so that double-frees are avoided
175                self.destructor = $destructor_name::NoDestructor;
176            }
177        }
178    };
179}
180
181#[macro_export]
182macro_rules! impl_vec_as_hashmap {
183    ($struct_type:ident, $struct_name:ident) => {
184        impl $struct_name {
185            pub fn insert_hm_item(&mut self, item: $struct_type) {
186                if !self.contains_hm_item(&item) {
187                    let mut vec = self.clone().into_library_owned_vec();
188                    vec.push(item);
189                    *self = Self::from_vec(vec);
190                }
191            }
192
193            pub fn remove_hm_item(&mut self, remove_key: &$struct_type) {
194                *self = Self::from_vec(
195                    self.as_ref()
196                        .iter()
197                        .filter_map(|r| if *r == *remove_key { None } else { Some(*r) })
198                        .collect::<Vec<_>>(),
199                );
200            }
201
202            pub fn contains_hm_item(&self, searched: &$struct_type) -> bool {
203                self.as_ref().iter().any(|i| i == searched)
204            }
205        }
206    };
207}
208
209/// NOTE: impl_vec_mut can only exist for vectors that are known to be library-allocated!
210#[macro_export]
211macro_rules! impl_vec_mut {
212    ($struct_type:ident, $struct_name:ident) => {
213        impl AsMut<[$struct_type]> for $struct_name {
214            fn as_mut(&mut self) -> &mut [$struct_type] {
215                unsafe { core::slice::from_raw_parts_mut(self.ptr as *mut $struct_type, self.len) }
216            }
217        }
218
219        impl From<$struct_name> for alloc::vec::Vec<$struct_type> {
220            #[allow(unused_mut)]
221            fn from(mut input: $struct_name) -> alloc::vec::Vec<$struct_type> {
222                input.into_library_owned_vec()
223            }
224        }
225
226        impl core::iter::Extend<$struct_type> for $struct_name {
227            fn extend<T: core::iter::IntoIterator<Item = $struct_type>>(&mut self, iter: T) {
228                for elem in iter {
229                    self.push(elem);
230                }
231            }
232        }
233
234        impl $struct_name {
235            // <'a> has to live longer thant &'self
236            pub fn as_mut_slice_extended<'a>(&mut self) -> &'a mut [$struct_type] {
237                unsafe { core::slice::from_raw_parts_mut(self.ptr as *mut $struct_type, self.len) }
238            }
239
240            #[inline]
241            pub fn as_mut_ptr(&mut self) -> *mut $struct_type {
242                self.ptr as *mut $struct_type
243            }
244
245            #[inline]
246            pub fn sort_by<F: FnMut(&$struct_type, &$struct_type) -> core::cmp::Ordering>(
247                &mut self,
248                compare: F,
249            ) {
250                self.as_mut().sort_by(compare);
251            }
252
253            #[inline]
254            pub fn push(&mut self, value: $struct_type) {
255                // code is copied from the rust stdlib, since it's not possible to
256                // create a temporary Vec here. Doing that would create two
257                if self.len == self.capacity() {
258                    self.buf_reserve(self.len, 1);
259                }
260                unsafe {
261                    let end = self.as_mut_ptr().add(self.len);
262                    core::ptr::write(end, value);
263                    self.len += 1;
264                }
265            }
266
267            pub fn insert(&mut self, index: usize, element: $struct_type) {
268                let len = self.len();
269                if index > len {
270                    return;
271                }
272
273                // space for the new element
274                if len == self.capacity() {
275                    self.reserve(1);
276                }
277
278                unsafe {
279                    // infallible
280                    // The spot to put the new value
281                    {
282                        let p = self.as_mut_ptr().add(index);
283                        // Shift everything over to make space. (Duplicating the
284                        // `index`th element into two consecutive places.)
285                        core::ptr::copy(p, p.offset(1), len - index);
286                        // Write it in, overwriting the first copy of the `index`th
287                        // element.
288                        core::ptr::write(p, element);
289                    }
290                    self.set_len(len + 1);
291                }
292            }
293
294            pub fn remove(&mut self, index: usize) {
295                let len = self.len();
296                if index >= len {
297                    return;
298                }
299
300                unsafe {
301                    // infallible
302                    let ret;
303                    {
304                        // the place we are taking from.
305                        let ptr = self.as_mut_ptr().add(index);
306                        // copy it out, unsafely having a copy of the value on
307                        // the stack and in the vector at the same time.
308                        ret = core::ptr::read(ptr);
309
310                        // Shift everything down to fill in that spot.
311                        core::ptr::copy(ptr.offset(1), ptr, len - index - 1);
312                    }
313                    self.set_len(len - 1);
314                    let _ = ret;
315                }
316            }
317
318            #[inline]
319            pub fn pop(&mut self) -> Option<$struct_type> {
320                if self.len == 0 {
321                    None
322                } else {
323                    unsafe {
324                        self.len -= 1;
325                        Some(core::ptr::read(self.ptr.add(self.len())))
326                    }
327                }
328            }
329
330            #[inline]
331            pub fn iter_mut(&mut self) -> core::slice::IterMut<$struct_type> {
332                self.as_mut().iter_mut()
333            }
334
335            #[inline]
336            pub fn into_iter(self) -> alloc::vec::IntoIter<$struct_type> {
337                let v1: alloc::vec::Vec<$struct_type> = self.into();
338                v1.into_iter()
339            }
340
341            #[inline]
342            fn amortized_new_size(
343                &self,
344                used_cap: usize,
345                needed_extra_cap: usize,
346            ) -> Result<usize, bool> {
347                // Nothing we can really do about these checks :(
348                let required_cap = used_cap.checked_add(needed_extra_cap).ok_or(true)?;
349                // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
350                let double_cap = self.cap * 2;
351                // `double_cap` guarantees exponential growth.
352                Ok(core::cmp::max(double_cap, required_cap))
353            }
354
355            #[inline]
356            fn current_layout(&self) -> Option<core::alloc::Layout> {
357                if self.cap == 0 {
358                    None
359                } else {
360                    // We have an allocated chunk of memory, so we can bypass runtime
361                    // checks to get our current layout.
362                    unsafe {
363                        let align = core::mem::align_of::<$struct_type>();
364                        let size = core::mem::size_of::<$struct_type>() * self.cap;
365                        Some(core::alloc::Layout::from_size_align_unchecked(size, align))
366                    }
367                }
368            }
369
370            #[inline]
371            fn alloc_guard(alloc_size: usize) -> Result<(), bool> {
372                if core::mem::size_of::<usize>() < 8 && alloc_size > ::core::isize::MAX as usize {
373                    Err(true)
374                } else {
375                    Ok(())
376                }
377            }
378
379            #[inline]
380            fn try_reserve(
381                &mut self,
382                used_cap: usize,
383                needed_extra_cap: usize,
384            ) -> Result<(), bool> {
385                // NOTE: we don't early branch on ZSTs here because we want this
386                // to actually catch "asking for more than usize::MAX" in that case.
387                // If we make it past the first branch then we are guaranteed to
388                // panic.
389
390                // Don't actually need any more capacity.
391                // Wrapping in case they give a bad `used_cap`
392                if self.capacity().wrapping_sub(used_cap) >= needed_extra_cap {
393                    return Ok(());
394                }
395
396                let new_cap = self.amortized_new_size(used_cap, needed_extra_cap)?;
397                let new_layout =
398                    alloc::alloc::Layout::array::<$struct_type>(new_cap).map_err(|_| true)?;
399
400                // FIXME: may crash and burn on over-reserve
401                $struct_name::alloc_guard(new_layout.size())?;
402
403                let res = unsafe {
404                    match self.current_layout() {
405                        Some(layout) => {
406                            alloc::alloc::realloc(self.ptr as *mut u8, layout, new_layout.size())
407                        }
408                        None => alloc::alloc::alloc(new_layout),
409                    }
410                };
411
412                if res == core::ptr::null_mut() {
413                    return Err(false);
414                }
415
416                self.ptr = res as *mut $struct_type;
417                self.cap = new_cap;
418
419                Ok(())
420            }
421
422            fn buf_reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
423                match self.try_reserve(used_cap, needed_extra_cap) {
424                    Err(true /* Overflow */) => {
425                        panic!("memory allocation failed: overflow");
426                    }
427                    Err(false /* AllocError(_) */) => {
428                        panic!("memory allocation failed: error allocating new memory");
429                    }
430                    Ok(()) => { /* yay */ }
431                }
432            }
433
434            pub fn append(&mut self, other: &mut Self) {
435                unsafe {
436                    self.append_elements(other.as_slice() as _);
437                    other.set_len(0);
438                }
439            }
440
441            unsafe fn set_len(&mut self, new_len: usize) {
442                debug_assert!(new_len <= self.capacity());
443                self.len = new_len;
444            }
445
446            pub fn reserve(&mut self, additional: usize) {
447                self.buf_reserve(self.len, additional);
448            }
449
450            /// Appends elements to `Self` from other buffer.
451            #[inline]
452            unsafe fn append_elements(&mut self, other: *const [$struct_type]) {
453                let count = (*other).len();
454                self.reserve(count);
455                let len = self.len();
456                core::ptr::copy_nonoverlapping(
457                    other as *const $struct_type,
458                    self.as_mut_ptr().add(len),
459                    count,
460                );
461                self.len += count;
462            }
463
464            pub fn truncate(&mut self, len: usize) {
465                // This is safe because:
466                //
467                // * the slice passed to `drop_in_place` is valid; the `len > self.len` case avoids
468                //   creating an invalid slice, and
469                // * the `len` of the vector is shrunk before calling `drop_in_place`, such that no
470                //   value will be dropped twice in case `drop_in_place` were to panic once (if it
471                //   panics twice, the program aborts).
472                unsafe {
473                    if len > self.len {
474                        return;
475                    }
476                    let remaining_len = self.len - len;
477                    let s = core::ptr::slice_from_raw_parts_mut(
478                        self.as_mut_ptr().add(len),
479                        remaining_len,
480                    );
481                    self.len = len;
482                    core::ptr::drop_in_place(s);
483                }
484            }
485
486            pub fn retain<F>(&mut self, mut f: F)
487            where
488                F: FnMut(&$struct_type) -> bool,
489            {
490                let len = self.len();
491                let mut del = 0;
492
493                {
494                    for i in 0..len {
495                        if unsafe { !f(self.get_unchecked(i)) } {
496                            del += 1;
497                        } else if del > 0 {
498                            self.as_mut().swap(i - del, i);
499                        }
500                    }
501                }
502
503                if del > 0 {
504                    self.truncate(len - del);
505                }
506            }
507        }
508    };
509}
510
511#[macro_export]
512macro_rules! impl_vec_debug {
513    ($struct_type:ident, $struct_name:ident) => {
514        impl core::fmt::Debug for $struct_name {
515            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
516                self.as_ref().fmt(f)
517            }
518        }
519    };
520}
521
522#[macro_export]
523macro_rules! impl_vec_partialord {
524    ($struct_type:ident, $struct_name:ident) => {
525        impl PartialOrd for $struct_name {
526            fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
527                self.as_ref().partial_cmp(rhs.as_ref())
528            }
529        }
530    };
531}
532
533#[macro_export]
534macro_rules! impl_vec_ord {
535    ($struct_type:ident, $struct_name:ident) => {
536        impl Ord for $struct_name {
537            fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
538                self.as_ref().cmp(rhs.as_ref())
539            }
540        }
541    };
542}
543
544#[macro_export]
545macro_rules! impl_vec_clone {
546    ($struct_type:ident, $struct_name:ident, $destructor_name:ident) => {
547        impl $struct_name {
548            // Creates a `Vec` from a `Cow<'static, [T]>` - useful to avoid allocating in the case
549            // of &'static memory
550            #[inline(always)]
551            pub fn from_copy_on_write(
552                input: alloc::borrow::Cow<'static, [$struct_type]>,
553            ) -> $struct_name {
554                match input {
555                    alloc::borrow::Cow::Borrowed(static_array) => {
556                        Self::from_const_slice(static_array)
557                    }
558                    alloc::borrow::Cow::Owned(owned_vec) => Self::from_vec(owned_vec),
559                }
560            }
561
562            /// NOTE: CLONES the memory if the memory is external or &'static
563            /// Moves the memory out if the memory is library-allocated
564            #[inline(always)]
565            pub fn clone_self(&self) -> Self {
566                match self.destructor {
567                    $destructor_name::NoDestructor => Self {
568                        ptr: self.ptr,
569                        len: self.len,
570                        cap: self.cap,
571                        destructor: $destructor_name::NoDestructor,
572                    },
573                    $destructor_name::External(_) | $destructor_name::DefaultRust => {
574                        Self::from_vec(self.as_ref().to_vec())
575                    }
576                }
577            }
578
579            /// NOTE: CLONES the memory if the memory is external or &'static
580            /// Moves the memory out if the memory is library-allocated
581            #[inline(always)]
582            pub fn into_library_owned_vec(self) -> alloc::vec::Vec<$struct_type> {
583                match self.destructor {
584                    $destructor_name::NoDestructor | $destructor_name::External(_) => {
585                        self.as_ref().to_vec()
586                    }
587                    $destructor_name::DefaultRust => {
588                        let v = unsafe {
589                            alloc::vec::Vec::from_raw_parts(
590                                self.ptr as *mut $struct_type,
591                                self.len,
592                                self.cap,
593                            )
594                        };
595                        core::mem::forget(self);
596                        v
597                    }
598                }
599            }
600        }
601        impl Clone for $struct_name {
602            fn clone(&self) -> Self {
603                self.clone_self()
604            }
605        }
606    };
607}
608
609#[macro_export]
610macro_rules! impl_vec_partialeq {
611    ($struct_type:ident, $struct_name:ident) => {
612        impl PartialEq for $struct_name {
613            fn eq(&self, rhs: &Self) -> bool {
614                self.as_ref().eq(rhs.as_ref())
615            }
616        }
617    };
618}
619
620#[macro_export]
621macro_rules! impl_vec_eq {
622    ($struct_type:ident, $struct_name:ident) => {
623        impl Eq for $struct_name {}
624    };
625}
626
627#[macro_export]
628macro_rules! impl_vec_hash {
629    ($struct_type:ident, $struct_name:ident) => {
630        impl core::hash::Hash for $struct_name {
631            fn hash<H>(&self, state: &mut H)
632            where
633                H: core::hash::Hasher,
634            {
635                self.as_ref().hash(state);
636            }
637        }
638    };
639}
640
641#[macro_export]
642macro_rules! impl_option_inner {
643    ($struct_type:ident, $struct_name:ident) => {
644        impl From<$struct_name> for Option<$struct_type> {
645            fn from(o: $struct_name) -> Option<$struct_type> {
646                match o {
647                    $struct_name::None => None,
648                    $struct_name::Some(t) => Some(t),
649                }
650            }
651        }
652
653        impl From<Option<$struct_type>> for $struct_name {
654            fn from(o: Option<$struct_type>) -> $struct_name {
655                match o {
656                    None => $struct_name::None,
657                    Some(t) => $struct_name::Some(t),
658                }
659            }
660        }
661
662        impl Default for $struct_name {
663            fn default() -> $struct_name {
664                $struct_name::None
665            }
666        }
667
668        impl $struct_name {
669            pub fn as_option(&self) -> Option<&$struct_type> {
670                match self {
671                    $struct_name::None => None,
672                    $struct_name::Some(t) => Some(t),
673                }
674            }
675            pub fn replace(&mut self, value: $struct_type) -> $struct_name {
676                ::core::mem::replace(self, $struct_name::Some(value))
677            }
678            pub fn is_some(&self) -> bool {
679                match self {
680                    $struct_name::None => false,
681                    $struct_name::Some(_) => true,
682                }
683            }
684            pub fn is_none(&self) -> bool {
685                !self.is_some()
686            }
687            pub const fn as_ref(&self) -> Option<&$struct_type> {
688                match *self {
689                    $struct_name::Some(ref x) => Some(x),
690                    $struct_name::None => None,
691                }
692            }
693            pub fn as_mut(&mut self) -> Option<&mut $struct_type> {
694                match self {
695                    $struct_name::Some(x) => Some(x),
696                    $struct_name::None => None,
697                }
698            }
699            pub fn map<U, F: FnOnce($struct_type) -> U>(self, f: F) -> Option<U> {
700                match self {
701                    $struct_name::Some(x) => Some(f(x)),
702                    $struct_name::None => None,
703                }
704            }
705            pub fn and_then<U, F>(self, f: F) -> Option<U>
706            where
707                F: FnOnce($struct_type) -> Option<U>,
708            {
709                match self {
710                    $struct_name::None => None,
711                    $struct_name::Some(x) => f(x),
712                }
713            }
714        }
715    };
716}
717
718#[macro_export]
719macro_rules! impl_option {
720    ($struct_type:ident, $struct_name:ident, copy = false, clone = false, [$($derive:meta),* ]) => (
721        $(#[derive($derive)])*
722        #[repr(C, u8)]
723        pub enum $struct_name {
724            None,
725            Some($struct_type)
726        }
727
728        impl $struct_name {
729            pub fn into_option(self) -> Option<$struct_type> {
730                match self {
731                    $struct_name::None => None,
732                    $struct_name::Some(t) => Some(t),
733                }
734            }
735        }
736
737        impl_option_inner!($struct_type, $struct_name);
738    );
739    ($struct_type:ident, $struct_name:ident, copy = false, [$($derive:meta),* ]) => (
740        $(#[derive($derive)])*
741        #[repr(C, u8)]
742        pub enum $struct_name {
743            None,
744            Some($struct_type)
745        }
746
747        impl $struct_name {
748            pub fn into_option(&self) -> Option<$struct_type> {
749                match self {
750                    $struct_name::None => None,
751                    $struct_name::Some(t) => Some(t.clone()),
752                }
753            }
754        }
755
756        impl_option_inner!($struct_type, $struct_name);
757    );
758    ($struct_type:ident, $struct_name:ident, [$($derive:meta),* ]) => (
759        $(#[derive($derive)])*
760        #[repr(C, u8)]
761        pub enum $struct_name {
762            None,
763            Some($struct_type)
764        }
765
766        impl $struct_name {
767            pub fn into_option(&self) -> Option<$struct_type> {
768                match self {
769                    $struct_name::None => None,
770                    $struct_name::Some(t) => Some(*t),
771                }
772            }
773        }
774
775        impl_option_inner!($struct_type, $struct_name);
776    );
777}
778
779#[macro_export]
780macro_rules! impl_result_inner {
781    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident) => {
782        impl From<$struct_name> for Result<$ok_struct_type, $err_struct_type> {
783            fn from(o: $struct_name) -> Result<$ok_struct_type, $err_struct_type> {
784                match o {
785                    $struct_name::Ok(o) => Ok(o),
786                    $struct_name::Err(e) => Err(e),
787                }
788            }
789        }
790
791        impl From<Result<$ok_struct_type, $err_struct_type>> for $struct_name {
792            fn from(o: Result<$ok_struct_type, $err_struct_type>) -> $struct_name {
793                match o {
794                    Ok(o) => $struct_name::Ok(o),
795                    Err(e) => $struct_name::Err(e),
796                }
797            }
798        }
799
800        impl $struct_name {
801            pub fn as_result(&self) -> Result<&$ok_struct_type, &$err_struct_type> {
802                match self {
803                    $struct_name::Ok(o) => Ok(o),
804                    $struct_name::Err(e) => Err(e),
805                }
806            }
807            pub fn is_ok(&self) -> bool {
808                match self {
809                    $struct_name::Ok(_) => true,
810                    $struct_name::Err(_) => false,
811                }
812            }
813            pub fn is_err(&self) -> bool {
814                !self.is_ok()
815            }
816        }
817    };
818}
819
820#[macro_export]
821macro_rules! impl_result {
822    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident, copy = false, clone = false, [$($derive:meta),* ]) => (
823        $(#[derive($derive)])*
824        #[repr(C, u8)]
825        pub enum $struct_name {
826            Ok($ok_struct_type),
827            Err($err_struct_type)
828        }
829
830        impl $struct_name {
831            pub fn into_result(self) -> Result<$ok_struct_type, $err_struct_type> {
832                match self {
833                    $struct_name::Ok(o) => Ok(o),
834                    $struct_name::Err(e) => Err(e),
835                }
836            }
837        }
838
839        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
840    );
841    ($ok_struct_type:ident, $err_struct_type:ident, $struct_name:ident, copy = false, [$($derive:meta),* ]) => (
842        $(#[derive($derive)])*
843        #[repr(C, u8)]
844        pub enum $struct_name {
845            Ok($ok_struct_type),
846            Err($err_struct_type)
847        }
848        impl $struct_name {
849            pub fn into_result(&self) -> Result<$ok_struct_type, $err_struct_type> {
850                match self {
851                    $struct_name::Ok(o) => Ok(o.clone()),
852                    $struct_name::Err(e) => Err(e.clone()),
853                }
854            }
855        }
856
857        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
858    );
859    ($ok_struct_type:ident, $err_struct_type:ident,  $struct_name:ident, [$($derive:meta),* ]) => (
860        $(#[derive($derive)])*
861        #[repr(C, u8)]
862        pub enum $struct_name {
863            Ok($ok_struct_type),
864            Err($err_struct_type)
865        }
866
867        impl $struct_name {
868            pub fn into_result(&self) -> Result<$ok_struct_type, $err_struct_type> {
869                match self {
870                    $struct_name::Ok(o) => Ok(*o),
871                    $struct_name::Err(e) => Err(*e),
872                }
873            }
874        }
875
876        impl_result_inner!($ok_struct_type, $err_struct_type, $struct_name);
877    );
878}
879
880#[repr(C)]
881pub struct AzString {
882    pub vec: U8Vec,
883}
884
885impl_option!(
886    AzString,
887    OptionAzString,
888    copy = false,
889    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
890);
891
892static DEFAULT_STR: &str = "";
893
894impl Default for AzString {
895    fn default() -> Self {
896        DEFAULT_STR.into()
897    }
898}
899
900impl<'a> From<&'a str> for AzString {
901    fn from(s: &'a str) -> Self {
902        s.to_string().into()
903    }
904}
905
906impl AsRef<str> for AzString {
907    fn as_ref<'a>(&'a self) -> &'a str {
908        self.as_str()
909    }
910}
911
912impl core::fmt::Debug for AzString {
913    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
914        self.as_str().fmt(f)
915    }
916}
917
918impl core::fmt::Display for AzString {
919    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
920        self.as_str().fmt(f)
921    }
922}
923
924impl AzString {
925    #[inline]
926    pub const fn from_const_str(s: &'static str) -> Self {
927        Self {
928            vec: U8Vec::from_const_slice(s.as_bytes()),
929        }
930    }
931
932    #[inline]
933    pub fn from_string(s: String) -> Self {
934        Self {
935            vec: U8Vec::from_vec(s.into_bytes()),
936        }
937    }
938
939    #[inline]
940    pub fn as_str(&self) -> &str {
941        unsafe { core::str::from_utf8_unchecked(self.vec.as_ref()) }
942    }
943
944    /// NOTE: CLONES the memory if the memory is external or &'static
945    /// Moves the memory out if the memory is library-allocated
946    #[inline]
947    pub fn clone_self(&self) -> Self {
948        Self {
949            vec: self.vec.clone_self(),
950        }
951    }
952
953    #[inline]
954    pub fn into_library_owned_string(self) -> String {
955        match self.vec.destructor {
956            U8VecDestructor::NoDestructor | U8VecDestructor::External(_) => {
957                self.as_str().to_string()
958            }
959            U8VecDestructor::DefaultRust => {
960                let m = core::mem::ManuallyDrop::new(self);
961                unsafe { String::from_raw_parts(m.vec.ptr as *mut u8, m.vec.len, m.vec.cap) }
962            }
963        }
964    }
965
966    #[inline]
967    pub fn as_bytes(&self) -> &[u8] {
968        self.vec.as_ref()
969    }
970
971    #[inline]
972    pub fn into_bytes(self) -> U8Vec {
973        let m = core::mem::ManuallyDrop::new(self);
974        U8Vec {
975            ptr: m.vec.ptr,
976            len: m.vec.len,
977            cap: m.vec.cap,
978            destructor: m.vec.destructor,
979        }
980    }
981}
982
983impl From<String> for AzString {
984    fn from(input: String) -> AzString {
985        AzString::from_string(input)
986    }
987}
988
989impl PartialOrd for AzString {
990    fn partial_cmp(&self, rhs: &Self) -> Option<core::cmp::Ordering> {
991        self.as_str().partial_cmp(rhs.as_str())
992    }
993}
994
995impl Ord for AzString {
996    fn cmp(&self, rhs: &Self) -> core::cmp::Ordering {
997        self.as_str().cmp(rhs.as_str())
998    }
999}
1000
1001impl Clone for AzString {
1002    fn clone(&self) -> Self {
1003        self.clone_self()
1004    }
1005}
1006
1007impl PartialEq for AzString {
1008    fn eq(&self, rhs: &Self) -> bool {
1009        self.as_str().eq(rhs.as_str())
1010    }
1011}
1012
1013impl Eq for AzString {}
1014
1015impl core::hash::Hash for AzString {
1016    fn hash<H>(&self, state: &mut H)
1017    where
1018        H: core::hash::Hasher,
1019    {
1020        self.as_str().hash(state)
1021    }
1022}
1023
1024impl core::ops::Deref for AzString {
1025    type Target = str;
1026
1027    fn deref(&self) -> &str {
1028        self.as_str()
1029    }
1030}
1031
1032impl_option!(
1033    ColorU,
1034    OptionColorU,
1035    [Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash]
1036);
1037
1038impl_vec!(u8, U8Vec, U8VecDestructor);
1039impl_vec_debug!(u8, U8Vec);
1040impl_vec_partialord!(u8, U8Vec);
1041impl_vec_ord!(u8, U8Vec);
1042impl_vec_clone!(u8, U8Vec, U8VecDestructor);
1043impl_vec_partialeq!(u8, U8Vec);
1044impl_vec_eq!(u8, U8Vec);
1045impl_vec_hash!(u8, U8Vec);
1046
1047impl_option!(
1048    U8Vec,
1049    OptionU8Vec,
1050    copy = false,
1051    [Debug, Clone, PartialEq, Ord, PartialOrd, Eq, Hash]
1052);
1053
1054impl_vec!(u16, U16Vec, U16VecDestructor);
1055impl_vec_debug!(u16, U16Vec);
1056impl_vec_partialord!(u16, U16Vec);
1057impl_vec_ord!(u16, U16Vec);
1058impl_vec_clone!(u16, U16Vec, U16VecDestructor);
1059impl_vec_partialeq!(u16, U16Vec);
1060impl_vec_eq!(u16, U16Vec);
1061impl_vec_hash!(u16, U16Vec);
1062
1063impl_vec!(f32, F32Vec, F32VecDestructor);
1064impl_vec_debug!(f32, F32Vec);
1065impl_vec_partialord!(f32, F32Vec);
1066impl_vec_clone!(f32, F32Vec, F32VecDestructor);
1067impl_vec_partialeq!(f32, F32Vec);
1068
1069// Vec<char>
1070impl_vec!(u32, U32Vec, U32VecDestructor);
1071impl_vec_mut!(u32, U32Vec);
1072impl_vec_debug!(u32, U32Vec);
1073impl_vec_partialord!(u32, U32Vec);
1074impl_vec_ord!(u32, U32Vec);
1075impl_vec_clone!(u32, U32Vec, U32VecDestructor);
1076impl_vec_partialeq!(u32, U32Vec);
1077impl_vec_eq!(u32, U32Vec);
1078impl_vec_hash!(u32, U32Vec);
1079
1080impl_vec!(AzString, StringVec, StringVecDestructor);
1081impl_vec_debug!(AzString, StringVec);
1082impl_vec_partialord!(AzString, StringVec);
1083impl_vec_ord!(AzString, StringVec);
1084impl_vec_clone!(AzString, StringVec, StringVecDestructor);
1085impl_vec_partialeq!(AzString, StringVec);
1086impl_vec_eq!(AzString, StringVec);
1087impl_vec_hash!(AzString, StringVec);
1088
1089impl From<Vec<String>> for StringVec {
1090    fn from(v: Vec<String>) -> StringVec {
1091        let new_v: Vec<AzString> = v.into_iter().map(|s| s.into()).collect();
1092        new_v.into()
1093    }
1094}
1095
1096impl_option!(
1097    StringVec,
1098    OptionStringVec,
1099    copy = false,
1100    [Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash]
1101);
1102
1103impl_option!(
1104    u16,
1105    OptionU16,
1106    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
1107);
1108impl_option!(
1109    u32,
1110    OptionU32,
1111    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
1112);
1113impl_option!(
1114    i16,
1115    OptionI16,
1116    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
1117);
1118impl_option!(
1119    i32,
1120    OptionI32,
1121    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
1122);
1123impl_option!(f32, OptionF32, [Debug, Copy, Clone, PartialEq, PartialOrd]);
1124impl_option!(f64, OptionF64, [Debug, Copy, Clone, PartialEq, PartialOrd]);
1125
1126mod css;
1127mod css_properties;
1128mod print_css;
1129
1130pub use crate::{css::*, css_properties::*, print_css::*};