vy_core/
helpers.rs

1use crate::{buffer::Buffer, IntoHtml};
2
3macro_rules! impl_tuple {
4	( ( $($i:ident,)+ ) ) => {
5		impl<$($i,)+> IntoHtml for ($($i,)+)
6		where
7			$($i: IntoHtml,)+
8		{
9            #[inline]
10            fn into_html(self) -> impl IntoHtml {
11				#[allow(non_snake_case)]
12				let ($($i,)+) = self;
13				($(
14					$i.into_html()
15				),+)
16            }
17
18            #[inline]
19			fn escape_and_write(self, buf: &mut Buffer) {
20				#[allow(non_snake_case)]
21				let ($($i,)+) = self;
22				$(
23					$i.escape_and_write(buf);
24				)+
25			}
26
27            #[inline]
28            fn size_hint(&self) -> usize {
29				#[allow(non_snake_case)]
30				let ($($i,)+) = self;
31                let mut n = 0;
32				$(
33					n += $i.size_hint();
34				)+
35                n
36            }
37		}
38	};
39	($f:ident) => {
40		impl_tuple!(($f,));
41	};
42	($f:ident $($i:ident)+) => {
43		impl_tuple!(($f, $($i,)+));
44		impl_tuple!($($i)+);
45	};
46}
47
48impl_tuple!(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
49
50macro_rules! via_itoa {
51    ($($ty:ty)*) => {
52        $(
53            impl $crate::IntoHtml for $ty {
54                #[inline]
55                fn into_html(self) -> impl IntoHtml {
56                    self
57                }
58
59                #[inline]
60                fn escape_and_write(self, buf: &mut Buffer) {
61                    // Implementation from: https://raw.githubusercontent.com/rust-sailfish/sailfish/47e281cd1c5d8c3299955f360595e4c37d1d111c/sailfish/src/runtime/render.rs
62
63                    use itoap::Integer;
64
65                    // SAFETY: `MAX_LEN < 40` and then does not overflows `isize::MAX`.
66                    // Also `b.len()` should be always less than or equal to `isize::MAX`.
67                    unsafe {
68                        buf.reserve_small(Self::MAX_LEN);
69                        let ptr = buf.as_mut_ptr().add(buf.len());
70
71                        // SAFETY: `MAX_LEN` is always greater than zero, so
72                        // `b.as_mut_ptr()` always point to valid block of memory
73                        let l = itoap::write_to_ptr(ptr, self);
74                        buf.advance(l);
75                    }
76                    debug_assert!(buf.len() <= buf.capacity());
77                }
78            }
79        )*
80    };
81}
82
83macro_rules! via_ryu {
84    ($($ty:ty)*) => {
85        $(
86            impl $crate::IntoHtml for $ty {
87                #[inline]
88                fn into_html(self) -> impl IntoHtml {
89                    self
90                }
91
92                #[inline]
93                fn escape_and_write(self, buf: &mut Buffer) {
94                    buf.push_str(ryu::Buffer::new().format(self));
95                }
96            }
97        )*
98    };
99}
100
101via_itoa! {
102    isize i8 i16 i32 i64 i128
103    usize u8 u16 u32 u64 u128
104}
105
106via_ryu! { f32 f64 }