cheers 0.1.0-alpha.1

Fullstack hypermedia framework for Rust.
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
use core::{
    fmt::{self, Debug, Formatter, Write},
    marker::PhantomData,
    ptr,
};
use std::{borrow::Cow, rc::Rc, sync::Arc};

use crate::context::{AttributeValue, Context, DatastarSource, Element, ScriptSource};

/// Raw pre-escaped output for a specific rendering context.
///
/// `Raw<T, Element>` is for already-sanitized HTML nodes. [`RawAttribute<T>`]
/// is the same idea in attribute context. `Raw<T, DatastarSource>` is for already-sanitized
/// JavaScript source intended for Datastar HTML attributes, and `Raw<T, ScriptSource>`
/// is for already-sanitized JavaScript source intended for `<script>` bodies.
///
/// Most code should prefer [`html!`](crate::prelude::html) and normal [`Render`] implementations.
/// Reach for `Raw` only when you already have trusted, pre-escaped markup and need to insert it
/// without further escaping.
///
/// # Safety
///
/// `Raw` disables Cheers' normal escaping. Passing unsanitized user input here can create XSS
/// vulnerabilities.
///
/// # Example
///
/// ```
/// use cheers::{Raw, prelude::*};
///
/// // XSS SAFETY: this HTML is trusted and already sanitized.
/// let trusted = Raw::dangerously_create("<strong>trusted</strong>");
///
/// assert_eq!(
///     html! { div { (trusted) } }.render().into_inner(),
///     "<div><strong>trusted</strong></div>",
/// );
/// ```
#[derive(Clone, Copy, Default, Eq, Hash)]
pub struct Raw<T: AsRef<str>, C: Context = Element> {
    inner: T,
    context: PhantomData<C>,
}

impl<T: AsRef<str>, C: Context> Raw<T, C> {
    /// Creates a new [`Raw`] from the given string.
    ///
    /// It is recommended to add a `// XSS SAFETY` comment above the usage of
    /// this function to indicate why it is safe to directly use the contained
    /// raw output for the chosen rendering context.
    #[inline]
    pub const fn dangerously_create(value: T) -> Self {
        Self {
            inner: value,
            context: PhantomData,
        }
    }

    /// Extracts the inner value.
    #[inline]
    pub const fn into_inner(self) -> T {
        // SAFETY: `Raw<T, C>` has exactly one non-zero-sized field, which is `inner`.
        unsafe { const_precise_live_drops_hack!(self.inner) }
    }

    /// Gets a reference to the inner value.
    #[inline]
    pub const fn as_inner(&self) -> &T {
        &self.inner
    }

    /// Gets a reference to the inner value as an [`&str`][str].
    #[inline]
    pub fn as_str(&self) -> &str {
        self.inner.as_ref()
    }
}

impl<T: AsRef<str>> Raw<T> {
    /// Converts the [`Raw<T>`] into a [`Rendered<T>`].
    #[inline]
    #[must_use]
    pub const fn rendered(self) -> Rendered<T> {
        // SAFETY: `Raw<T>` has exactly one non-zero-sized field, which is `inner`.
        let value = unsafe { const_precise_live_drops_hack!(self.inner) };
        Rendered(value)
    }
}

impl<T: AsRef<str> + PartialEq<U>, C: Context, U: AsRef<str>> PartialEq<Raw<U, C>> for Raw<T, C> {
    #[inline]
    fn eq(&self, other: &Raw<U, C>) -> bool {
        self.inner == other.inner
    }
}

impl<T: AsRef<str>, C: Context> Debug for Raw<T, C> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("Raw").field(&self.inner.as_ref()).finish()
    }
}

/// A raw pre-escaped attribute value.
///
/// This is a type alias for [`Raw<T, Attribute>`].
pub type RawAttribute<T> = Raw<T, AttributeValue>;

/// Raw pre-escaped JavaScript source.
///
/// This is a type alias for [`Raw<T, DatastarSource>`].
pub type RawDatastarSource<T> = Raw<T, DatastarSource>;

/// Raw pre-escaped JavaScript source for a `<script>` body.
///
/// This is a type alias for [`Raw<T, ScriptSource>`].
pub type RawScript<T> = Raw<T, ScriptSource>;

/// A rendered HTML string.
///
/// This type is returned by [`Render::render`] ([`Rendered<String>`]), as
/// well as [`Raw<T>::rendered`] ([`Rendered<T>`]).
///
/// This type intentionally does **not** implement [`Render`] to discourage
/// anti-patterns such as rendering to a string then embedding that HTML string
/// into another page. To do this, you should use [`RenderExt::memoize`], or
/// use [`Raw`] directly.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// let rendered = html! { p { "Hello" } }.render();
///
/// assert_eq!(rendered.as_inner(), "<p>Hello</p>");
/// ```
#[derive(Debug, Clone, Copy, Default, Eq, Hash)]
pub struct Rendered<T>(T);

impl<T> Rendered<T> {
    /// Extracts the inner value.
    #[inline]
    pub const fn into_inner(self) -> T {
        // SAFETY: `Rendered<T>` has only one field, which is `0`.
        unsafe { const_precise_live_drops_hack!(self.0) }
    }

    /// Gets a reference to the inner value.
    #[inline]
    pub const fn as_inner(&self) -> &T {
        &self.0
    }
}

impl<T: PartialEq<U>, U> PartialEq<Rendered<U>> for Rendered<T> {
    #[inline]
    fn eq(&self, other: &Rendered<U>) -> bool {
        self.0 == other.0
    }
}

/// Workaround for [`const_precise_live_drops`](https://github.com/rust-lang/rust/issues/73255) being unstable.
///
/// # Safety
///
/// - `$self` must be a struct with exactly 1 non-zero-sized field
/// - `$field` must be the name/index of that field
macro_rules! const_precise_live_drops_hack {
    ($self:ident. $field:tt) => {{
        let this = core::mem::ManuallyDrop::new($self);
        (&raw const (*(&raw const this).cast::<Self>()).$field).read()
    }};
}
pub(crate) use const_precise_live_drops_hack;

/// The buffer used for rendering output in a specific [`Context`].
///
/// This is a wrapper around [`String`] that prevents accidental XSS
/// vulnerabilities by disallowing direct rendering of raw output into the
/// buffer without clearly indicating the risk of doing so.
#[derive(Clone, Default, PartialEq, Eq)]
#[repr(transparent)]
pub struct Buffer<C: Context = Element> {
    inner: String,
    context: PhantomData<C>,
}

/// A buffer used for rendering attribute values.
///
/// This is a type alias for [`Buffer<AttributeValue>`].
pub type AttributeBuffer = Buffer<AttributeValue>;

#[expect(
    clippy::missing_const_for_fn,
    reason = "`Buffer` does not make sense in `const` contexts"
)]
impl<C: Context> Buffer<C> {
    #[inline]
    fn cast_context<T: Context>(&mut self) -> &mut Buffer<T> {
        // SAFETY:
        // - Both `Buffer<C>` and `Buffer<T>` are `#[repr(transparent)]` wrappers
        //   around `String`, differing only in the zero-sized `PhantomData`
        //   marker type.
        // - `PhantomData` does not affect memory layout, so the layout of
        //   `Buffer<C>` and `Buffer<T>` is guaranteed to be identical by Rust's
        //   type system.
        // - This cast only changes the marker type and does not affect the
        //   actual data or its validity.
        // - The lifetime of the reference is preserved, and there are no
        //   aliasing or validity issues, as both types are functionally
        //   identical at runtime.
        unsafe { &mut *ptr::from_mut(self).cast::<Buffer<T>>() }
    }

    /// Creates a new, empty [`Buffer`].
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        // XSS SAFETY: The buffer is empty and does not contain any output.
        Self::dangerously_from_string(String::new())
    }

    /// Creates a new [`Buffer`] from the given [`String`].
    ///
    /// It is recommended to add a `// XSS SAFETY` comment above the usage of
    /// this function to indicate why the original string is safe to be used as
    /// raw output for the chosen rendering context.
    #[inline]
    #[must_use]
    pub fn dangerously_from_string(string: String) -> Self {
        Self {
            inner: string,
            context: PhantomData,
        }
    }

    /// Creates a new [`&mut Buffer`](Buffer) from the given [`&mut
    /// String`](String).
    ///
    /// It is recommended to add a `// XSS SAFETY` comment above the usage of
    /// this function to indicate why the original string is safe to be used as
    /// raw output for the chosen rendering context.
    #[inline]
    #[must_use]
    pub fn dangerously_from_string_mut(string: &mut String) -> &mut Self {
        // SAFETY:
        // - `Buffer<C>` is a `#[repr(transparent)]` wrapper around `String`, differing
        //   only in the zero-sized `PhantomData` marker type.
        // - `PhantomData` does not affect memory layout, so the layout of `Buffer<C>`
        //   and `String` is guaranteed to be identical by Rust's type system.
        // - The lifetime of the reference is preserved, and there are no aliasing or
        //   validity issues, as both types are functionally identical at runtime.
        unsafe { &mut *ptr::from_mut(string).cast::<Self>() }
    }

    /// Converts this into a `&mut Buffer<AttributeValue>`.
    #[inline]
    pub fn as_attribute_buffer(&mut self) -> &mut AttributeBuffer {
        self.cast_context()
    }

    /// Converts this into a `&mut Buffer<DatastarSource>`.
    #[inline]
    pub fn as_datastar_buffer(&mut self) -> &mut Buffer<DatastarSource> {
        self.cast_context()
    }

    /// Converts this into a `&mut Buffer<ScriptSource>`.
    #[inline]
    pub fn as_script_buffer(&mut self) -> &mut Buffer<ScriptSource> {
        self.cast_context()
    }

    /// Renders the buffer to a [`Rendered<String>`].
    #[inline]
    #[must_use]
    pub fn rendered(self) -> Rendered<String> {
        Rendered(self.inner)
    }
}

#[expect(
    clippy::missing_const_for_fn,
    reason = "`Buffer` does not make sense in `const` contexts"
)]
impl<C: Context> Buffer<C> {
    /// Gets a mutable reference to the inner [`String`].
    ///
    /// For [`Buffer<Element>`] (a.k.a. [`Buffer`]) writes, the caller must push
    /// complete HTML nodes. If rendering string-like types, the pushed contents
    /// must escape `&` to `&amp;`, `<` to `&lt;`, and `>` to `&gt;`.
    ///
    /// For `Buffer<AttributeValue>` writes, the caller must push attribute
    /// values which will eventually be surrounded by double quotes. The pushed
    /// contents must escape `&` to `&amp;`, `<` to `&lt;`, `>` to `&gt;`, and
    /// `"` to `&quot;`.
    ///
    /// For `Buffer<DatastarSource>` writes, the caller must push JavaScript source intended
    /// for a Datastar attribute value which will eventually be surrounded by
    /// double quotes. The pushed contents must therefore remain valid
    /// JavaScript *and* escape any characters that would otherwise break HTML
    /// attribute parsing, such as `&`, `<`, `>`, and `"`.
    ///
    /// For `Buffer<ScriptSource>` writes, the caller must push JavaScript source intended
    /// for a `<script>` body. The pushed contents must therefore remain valid
    /// JavaScript and avoid raw `</script` sequences that would terminate the
    /// surrounding script element.
    ///
    /// It is recommended to add a `// XSS SAFETY` comment above the usage of
    /// this method to indicate why it is safe to directly write to the
    /// underlying buffer.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cheers::prelude::*;
    ///
    /// fn get_some_html() -> String {
    ///     // get html from some source, such as a CMS
    ///     "<h2>Some HTML from the CMS</h2>".into()
    /// }
    ///
    /// let mut buffer = Buffer::new();
    ///
    /// html! {
    ///     h1 { "My Document!" }
    /// }
    /// .render_to(&mut buffer);
    ///
    /// // XSS SAFETY: The CMS sanitizes the HTML before returning it.
    /// buffer.dangerously_get_string().push_str(&get_some_html());
    ///
    /// assert_eq!(
    ///     buffer.rendered().as_inner(),
    ///     "<h1>My Document!</h1><h2>Some HTML from the CMS</h2>"
    /// )
    /// ```
    #[inline]
    pub fn dangerously_get_string(&mut self) -> &mut String {
        &mut self.inner
    }
}

impl Debug for Buffer {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Buffer").field(&self.inner).finish()
    }
}

/// A type that can be rendered by Cheers.
///
/// This is the core trait behind components. A type becomes usable as a component in `html!` by
/// implementing `Render`. `#[derive(Cheers)]` does not implement this trait; it only generates
/// helper APIs such as ids, signals, and form names.
///
/// For [`Render<Element>`] (a.k.a. [`Render`]) implementations, this
/// must render complete HTML nodes. If rendering string-like types, the
/// implementation must escape `&` to `&amp;`, `<` to `&lt;`, and `>` to `&gt;`.
///
/// For [`Render<AttributeValue>`] implementations, this must render an
/// attribute value which will eventually be surrounded by double quotes. The
/// implementation must escape `&` to `&amp;`, `<` to `&lt;`, `>` to `&gt;`, and
/// `"` to `&quot;`.
///
/// For [`Render<DatastarSource>`] implementations, this must render JavaScript source for
/// a Datastar attribute value. The implementation must ensure the result is
/// valid JavaScript and is also safe to embed in a double-quoted HTML
/// attribute value.
///
/// For [`Render<ScriptSource>`] implementations, this must render JavaScript source for
/// a `<script>` body. The implementation must ensure the result is valid JavaScript
/// and cannot terminate the surrounding script element.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// pub struct Person {
///     name: String,
///     age: u8,
/// }
///
/// impl Render for Person {
///     fn render_to(&self, buffer: &mut Buffer) {
///         html! {
///             div {
///                 h1 { (self.name) }
///                 p { "Age: " (self.age) }
///             }
///         }
///         .render_to(buffer);
///     }
/// }
///
/// let person = Person {
///     name: "Alice".into(),
///     age: 20,
/// };
///
/// assert_eq!(
///     html! { main { (person) } }.render().as_inner(),
///     r#"<main><div><h1>Alice</h1><p>Age: 20</p></div></main>"#,
/// );
/// ```
pub trait Render<C: Context = Element> {
    /// Renders this value to the buffer.
    fn render_to(&self, buffer: &mut Buffer<C>);

    /// Renders this value to a string. This is a convenience method that
    /// calls [`render_to`] into a new [`Buffer`] and returns the result.
    ///
    /// This is useful for tests, debugging, and one-off rendering. For composition inside other
    /// markup, prefer rendering the value directly rather than round-tripping through a string.
    ///
    /// If overridden for performance reasons, this must match the
    /// implementation of [`render_to`].
    ///
    /// [`render_to`]: Render::render_to
    #[inline]
    fn render(&self) -> Rendered<String>
    where
        Self: Render<C>,
    {
        let mut buffer = Buffer::<C>::new();
        self.render_to(&mut buffer);
        buffer.rendered()
    }
}

/// Convenience methods for [`Render`] types.
///
/// This trait currently provides [`memoize`](RenderExt::memoize), which pre-renders a value into
/// reusable [`Raw`] HTML.
///
/// # Example
///
/// ```
/// use cheers::prelude::*;
///
/// let cached = html! { span { "cached" } }.memoize();
/// let rendered = html! { div { (&cached) (&cached) } }.render().into_inner();
///
/// assert_eq!(
///     rendered,
///     "<div><span>cached</span><span>cached</span></div>"
/// );
/// ```
pub trait RenderExt: Render {
    /// Pre-renders the value and stores it in a [`Raw`] so that it can be
    /// re-used among multiple renderings without re-computing the value.
    ///
    /// This should generally be avoided to avoid unnecessary allocations, but
    /// may be useful if it is more expensive to compute and render the value.
    #[inline]
    fn memoize(&self) -> Raw<String> {
        // XSS SAFETY: The value has already been rendered and is assumed as safe.
        Raw::dangerously_create(self.render().into_inner())
    }
}

impl<T: Render> RenderExt for T {}

/// A value lazily rendered via a closure.
///
/// For [`Lazy<F, Element>`] (a.k.a. [`Lazy<F>`]), this must render complete
/// HTML nodes. If rendering string-like types, the closure must escape `&` to
/// `&amp;`, `<` to `&lt;`, and `>` to `&gt;`.
///
/// For [`Lazy<F, AttributeValue>`] (a.k.a. [`LazyAttribute<F>`]), this must
/// render an attribute value which will eventually be surrounded by double
/// quotes. The closure must escape `&` to `&amp;`, `<` to `&lt;`, `>` to
/// `&gt;`, and `"` to `&quot;`.
///
/// For [`Lazy<F, DatastarSource>`], this must render JavaScript source intended for a
/// double-quoted Datastar HTML attribute value.
///
/// For [`Lazy<F, ScriptSource>`], this must render JavaScript source intended for a
/// `<script>` body.
#[derive(Clone, Copy)]
#[must_use = "`Lazy` does nothing unless `.render()` or `.render_to()` is called"]
pub struct Lazy<F: Fn(&mut Buffer<C>), C: Context = Element> {
    f: F,
    context: PhantomData<C>,
}

/// An attribute value lazily rendered via a closure.
///
/// This is a type alias for [`Lazy<F, AttributeValue>`].
pub type LazyAttribute<F> = Lazy<F, AttributeValue>;

/// JavaScript source for a `<script>` body lazily rendered via a closure.
///
/// This is a type alias for [`Lazy<F, ScriptSource>`].
pub type LazyScript<F> = Lazy<F, ScriptSource>;

impl<F: Fn(&mut Buffer<C>), C: Context> Lazy<F, C> {
    /// Creates a new [`Lazy`] from the given closure.
    ///
    /// It is recommended to add a `// XSS SAFETY` comment above the usage of
    /// this function to indicate why it is safe to assume that the closure will
    /// not write possibly unsafe output to the buffer for the chosen rendering
    /// context.
    #[inline]
    pub const fn dangerously_create(f: F) -> Self {
        Self {
            f,
            context: PhantomData,
        }
    }

    /// Extracts the inner closure.
    #[inline]
    pub const fn into_inner(self) -> F {
        // SAFETY: `Lazy<F, C>` has exactly one non-zero-sized field, which is `f`.
        unsafe { const_precise_live_drops_hack!(self.f) }
    }

    /// Gets a reference to the inner closure.
    #[inline]
    pub const fn as_inner(&self) -> &F {
        &self.f
    }
}

impl<F: Fn(&mut Buffer<C>), C: Context> Render<C> for Lazy<F, C> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<C>) {
        (self.f)(buffer);
    }
}

impl<F: Fn(&mut Buffer<C>), C: Context> Debug for Lazy<F, C> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Lazy").finish_non_exhaustive()
    }
}

impl<T: AsRef<str>, C: Context> Render<C> for Raw<T, C> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<C>) {
        // XSS SAFETY: `Raw` values are expected to be pre-escaped for
        // their respective rendering context.
        buffer.dangerously_get_string().push_str(self.as_str());
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Rendered(self.as_str().into())
    }
}

#[inline]
fn push_html_double_quoted_attribute_char(dst: &mut String, ch: char) {
    match ch {
        '&' => dst.push_str("&amp;"),
        '<' => dst.push_str("&lt;"),
        '>' => dst.push_str("&gt;"),
        '"' => dst.push_str("&quot;"),
        ch => dst.push(ch),
    }
}

#[inline]
pub(crate) fn push_datastar_source_to_html_attribute(dst: &mut String, source: &str) {
    for ch in source.chars() {
        push_html_double_quoted_attribute_char(dst, ch);
    }
}

#[inline]
pub(crate) fn push_json_source_to_html_attribute(dst: &mut String, source: &str) {
    for ch in source.chars() {
        match ch {
            '\u{2028}' => dst.push_str("\\u2028"),
            '\u{2029}' => dst.push_str("\\u2029"),
            ch => push_html_double_quoted_attribute_char(dst, ch),
        }
    }
}

#[inline]
pub(crate) fn push_js_single_quoted_string_to_html_attribute(dst: &mut String, value: &str) {
    dst.push('\'');

    for ch in value.chars() {
        match ch {
            '\\' => dst.push_str("\\\\"),
            '\'' => dst.push_str("\\'"),
            '\n' => dst.push_str("\\n"),
            '\r' => dst.push_str("\\r"),
            '\t' => dst.push_str("\\t"),
            '\u{2028}' => dst.push_str("\\u2028"),
            '\u{2029}' => dst.push_str("\\u2029"),
            ch if ch.is_control() => {
                // XSS SAFETY: control characters are emitted as JS `\uXXXX`
                // escape sequences, which are valid JavaScript source and do
                // not introduce raw HTML-special characters.
                _ = write!(dst, "\\u{:04x}", ch as u32);
            }
            ch => push_html_double_quoted_attribute_char(dst, ch),
        }
    }

    dst.push('\'');
}

#[inline]
pub(crate) fn push_js_single_quoted_string_to_script(dst: &mut String, value: &str) {
    dst.push('\'');

    for ch in value.chars() {
        match ch {
            '\\' => dst.push_str("\\\\"),
            '\'' => dst.push_str("\\'"),
            '\n' => dst.push_str("\\n"),
            '\r' => dst.push_str("\\r"),
            '\t' => dst.push_str("\\t"),
            '<' => dst.push_str("\\x3C"),
            '\u{2028}' => dst.push_str("\\u2028"),
            '\u{2029}' => dst.push_str("\\u2029"),
            ch if ch.is_control() => {
                // XSS SAFETY: control characters are emitted as JS `\uXXXX`
                // escape sequences, which are valid JavaScript source and do
                // not introduce a raw script terminator.
                _ = write!(dst, "\\u{:04x}", ch as u32);
            }
            ch => dst.push(ch),
        }
    }

    dst.push('\'');
}

impl Render for fmt::Arguments<'_> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        struct ElementEscaper<'a>(&'a mut String);

        impl Write for ElementEscaper<'_> {
            #[inline]
            fn write_str(&mut self, s: &str) -> fmt::Result {
                html_escape::encode_text_to_string(s, self.0);
                Ok(())
            }
        }

        // XSS SAFETY: `ElementEscaper` will escape special characters.
        _ = ElementEscaper(buffer.dangerously_get_string()).write_fmt(*self);
    }
}

impl Render<AttributeValue> for fmt::Arguments<'_> {
    #[inline]
    fn render_to(&self, buffer: &mut AttributeBuffer) {
        struct AttributeEscaper<'a>(&'a mut String);

        impl Write for AttributeEscaper<'_> {
            #[inline]
            fn write_str(&mut self, s: &str) -> fmt::Result {
                html_escape::encode_double_quoted_attribute_to_string(s, self.0);
                Ok(())
            }
        }

        // XSS SAFETY: `AttributeEscaper` will escape special characters.
        _ = AttributeEscaper(buffer.dangerously_get_string()).write_fmt(*self);
    }
}

impl Render for char {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        // XSS SAFETY: manual escaping
        let s = buffer.dangerously_get_string();
        match *self {
            '&' => s.push_str("&amp;"),
            '<' => s.push_str("&lt;"),
            '>' => s.push_str("&gt;"),
            c => s.push(c),
        }
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Rendered(match *self {
            '&' => "&amp;".into(),
            '<' => "&lt;".into(),
            '>' => "&gt;".into(),
            c => c.into(),
        })
    }
}

impl Render<AttributeValue> for char {
    #[inline]
    fn render_to(&self, buffer: &mut AttributeBuffer) {
        // XSS SAFETY: we are manually performing escaping here
        let s = buffer.dangerously_get_string();

        match *self {
            '&' => s.push_str("&amp;"),
            '<' => s.push_str("&lt;"),
            '>' => s.push_str("&gt;"),
            '"' => s.push_str("&quot;"),
            c => s.push(c),
        }
    }
}

impl Render<DatastarSource> for char {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        let mut encoded = [0; 4];
        // XSS SAFETY: the helper emits a JS string literal while also escaping
        // HTML attribute delimiters.
        push_js_single_quoted_string_to_html_attribute(
            buffer.dangerously_get_string(),
            self.encode_utf8(&mut encoded),
        );
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        let mut s = String::with_capacity(8);
        let mut encoded = [0; 4];
        push_js_single_quoted_string_to_html_attribute(&mut s, self.encode_utf8(&mut encoded));
        Rendered(s)
    }
}

impl Render<ScriptSource> for char {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        let mut encoded = [0; 4];
        // XSS SAFETY: the helper emits a JS string literal while also preventing
        // raw script terminators.
        push_js_single_quoted_string_to_script(
            buffer.dangerously_get_string(),
            self.encode_utf8(&mut encoded),
        );
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        let mut s = String::with_capacity(8);
        let mut encoded = [0; 4];
        push_js_single_quoted_string_to_script(&mut s, self.encode_utf8(&mut encoded));
        Rendered(s)
    }
}

impl Render for str {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        // XSS SAFETY: we use `html_escape` to ensure the text is properly escaped
        html_escape::encode_text_to_string(self, buffer.dangerously_get_string());
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Rendered(html_escape::encode_text(self).into_owned())
    }
}

impl Render<AttributeValue> for str {
    #[inline]
    fn render_to(&self, buffer: &mut AttributeBuffer) {
        // XSS SAFETY: we use `html_escape` to ensure the text is properly escaped
        html_escape::encode_double_quoted_attribute_to_string(
            self,
            buffer.dangerously_get_string(),
        );
    }
}

impl Render<DatastarSource> for str {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        // XSS SAFETY: the helper emits a JS string literal while also escaping
        // HTML attribute delimiters.
        push_js_single_quoted_string_to_html_attribute(buffer.dangerously_get_string(), self);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        let mut s = String::with_capacity(self.len() + 2);
        push_js_single_quoted_string_to_html_attribute(&mut s, self);
        Rendered(s)
    }
}

impl Render<ScriptSource> for str {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        // XSS SAFETY: the helper emits a JS string literal while also preventing
        // raw script terminators.
        push_js_single_quoted_string_to_script(buffer.dangerously_get_string(), self);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        let mut s = String::with_capacity(self.len() + 2);
        push_js_single_quoted_string_to_script(&mut s, self);
        Rendered(s)
    }
}

impl Render for String {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        self.as_str().render_to(buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Render::<Element>::render(self.as_str())
    }
}

impl Render<AttributeValue> for String {
    #[inline]
    fn render_to(&self, buffer: &mut AttributeBuffer) {
        self.as_str().render_to(buffer);
    }
}

impl Render<DatastarSource> for String {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        self.as_str().render_to(buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Render::<DatastarSource>::render(self.as_str())
    }
}

impl Render<ScriptSource> for String {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        self.as_str().render_to(buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Render::<ScriptSource>::render(self.as_str())
    }
}

impl<C: Context> Render<C> for bool {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<C>) {
        // XSS SAFETY: "true" and "false" are safe strings
        buffer
            .dangerously_get_string()
            .push_str(if *self { "true" } else { "false" });
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        Rendered(if *self { "true" } else { "false" }.into())
    }
}

macro_rules! render_via_itoa {
    ($($Ty:ty)*) => {
        $(
            impl<C: Context> Render<C> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<C>) {
                    // XSS SAFETY: integers are safe
                    buffer.dangerously_get_string().push_str(itoa::Buffer::new().format(*self));
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    Rendered(itoa::Buffer::new().format(*self).into())
                }
            }
        )*
    };
}

render_via_itoa! {
    i8 i16 i32
    u8 u16 u32
}

macro_rules! render_big_int_via_itoa {
    ($($Ty:ty)*) => {
        $(
            impl Render<Element> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<Element>) {
                    buffer.dangerously_get_string().push_str(itoa::Buffer::new().format(*self));
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    Rendered(itoa::Buffer::new().format(*self).into())
                }
            }

            impl Render<AttributeValue> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<AttributeValue>) {
                    buffer.dangerously_get_string().push_str(itoa::Buffer::new().format(*self));
                }
            }
        )*
    };
}

render_big_int_via_itoa! {
    i64 i128 isize
    u64 u128 usize
}

macro_rules! render_via_zmij {
    ($($Ty:ty)*) => {
        $(
            impl<C: Context> Render<C> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<C>) {
                    // XSS SAFETY: floats are safe
                    buffer.dangerously_get_string().push_str(zmij::Buffer::new().format(*self));
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    Rendered(zmij::Buffer::new().format(*self).into())
                }
            }
        )*
    };
}

render_via_zmij! {
    f32 f64
}

macro_rules! render_via_deref {
    ($($Ty:ty)*) => {
        $(
            impl<T: Render + ?Sized> Render for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer) {
                    T::render_to(&**self, buffer);
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    T::render(&**self)
                }
            }

            impl<T: Render<AttributeValue> + ?Sized> Render<AttributeValue> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut AttributeBuffer) {
                    T::render_to(&**self, buffer);
                }
            }

            impl<T: Render<DatastarSource> + ?Sized> Render<DatastarSource> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
                    T::render_to(&**self, buffer);
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    T::render(&**self)
                }
            }

            impl<T: Render<ScriptSource> + ?Sized> Render<ScriptSource> for $Ty {
                #[inline]
                fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
                    T::render_to(&**self, buffer);
                }

                #[inline]
                fn render(&self) -> Rendered<String> {
                    T::render(&**self)
                }
            }
        )*
    };
}

render_via_deref! {
    &T
    &mut T
    Box<T>
    Rc<T>
    Arc<T>
}

impl<'a, B: 'a + Render + ToOwned + ?Sized> Render for Cow<'a, B> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        B::render_to(&**self, buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        B::render(&**self)
    }
}

impl<'a, B: 'a + Render<AttributeValue> + ToOwned + ?Sized> Render<AttributeValue> for Cow<'a, B> {
    #[inline]
    fn render_to(&self, buffer: &mut AttributeBuffer) {
        B::render_to(&**self, buffer);
    }
}

impl<'a, B: 'a + Render<DatastarSource> + ToOwned + ?Sized> Render<DatastarSource> for Cow<'a, B> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        B::render_to(&**self, buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        B::render(&**self)
    }
}

impl<'a, B: 'a + Render<ScriptSource> + ToOwned + ?Sized> Render<ScriptSource> for Cow<'a, B> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        B::render_to(&**self, buffer);
    }

    #[inline]
    fn render(&self) -> Rendered<String> {
        B::render(&**self)
    }
}

impl<T: Render> Render for [T] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        for item in self {
            item.render_to(buffer);
        }
    }
}

impl<T: Render<DatastarSource>> Render<DatastarSource> for [T] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        buffer.dangerously_get_string().push('[');

        for (index, item) in self.iter().enumerate() {
            if index != 0 {
                buffer.dangerously_get_string().push(',');
            }
            item.render_to(buffer);
        }

        buffer.dangerously_get_string().push(']');
    }
}

impl<T: Render<ScriptSource>> Render<ScriptSource> for [T] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        buffer.dangerously_get_string().push('[');

        for (index, item) in self.iter().enumerate() {
            if index != 0 {
                buffer.dangerously_get_string().push(',');
            }
            item.render_to(buffer);
        }

        buffer.dangerously_get_string().push(']');
    }
}

impl<T: Render, const N: usize> Render for [T; N] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render<DatastarSource>, const N: usize> Render<DatastarSource> for [T; N] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render<ScriptSource>, const N: usize> Render<ScriptSource> for [T; N] {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render> Render for Vec<T> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render<DatastarSource>> Render<DatastarSource> for Vec<T> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<DatastarSource>) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render<ScriptSource>> Render<ScriptSource> for Vec<T> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<ScriptSource>) {
        self.as_slice().render_to(buffer);
    }
}

impl<T: Render<C>, C: Context> Render<C> for Option<T> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<C>) {
        if let Some(value) = self {
            value.render_to(buffer);
        }
    }
}

impl<T: Render<C>, E: Render<C>, C: Context> Render<C> for Result<T, E> {
    #[inline]
    fn render_to(&self, buffer: &mut Buffer<C>) {
        match self {
            Ok(value) => value.render_to(buffer),
            Err(err) => err.render_to(buffer),
        }
    }
}

macro_rules! impl_tuple {
    () => {
        impl<C: Context> Render<C> for () {
            #[inline]
            fn render_to(&self, _: &mut Buffer<C>) {}
        }
    };
    (($i:tt $T:ident)) => {
        #[cfg_attr(docsrs, doc(fake_variadic))]
        #[cfg_attr(docsrs, doc = "This trait is implemented for tuples up to twelve items long.")]
        impl<$T: Render<C>, C: Context> Render<C> for ($T,) {
            #[inline]
            fn render_to(&self, buffer: &mut Buffer<C>) {
                self.$i.render_to(buffer);
            }
        }
    };
    (($i0:tt $T0:ident) $(($i:tt $T:ident))+) => {
        #[cfg_attr(docsrs, doc(hidden))]
        impl<$T0: Render<C>, $($T: Render<C>),*, C: Context> Render<C> for ($T0, $($T,)*) {
            #[inline]
            fn render_to(&self, buffer: &mut Buffer<C>) {
                self.$i0.render_to(buffer);
                $(self.$i.render_to(buffer);)*
            }
        }
    }
}

impl_tuple!();
impl_tuple!((0 T));
impl_tuple!((0 T0) (1 T1));
impl_tuple!((0 T0) (1 T1) (2 T2));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6) (7 T7));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6) (7 T7) (8 T8));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6) (7 T7) (8 T8) (9 T9));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6) (7 T7) (8 T8) (9 T9) (10 T10));
impl_tuple!((0 T0) (1 T1) (2 T2) (3 T3) (4 T4) (5 T5) (6 T6) (7 T7) (8 T8) (9 T9) (10 T10) (11 T11));