safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
//! Heap-allocated safe-type wrappers ([`SafeHtml`], [`SafeUrl`], [`SafeScript`],
//! [`TrustedResourceUrl`], [`SafeStyle`], [`SafeStyleSheet`]) and their proto
//! replicas. Requires the `alloc` feature.

use super::*;
use alloc::borrow::Cow;
use alloc::string::String;
use core::borrow::Borrow;

/// `Cow::to_mut` with a capacity plan: promoting a borrowed constant
/// allocates room for the constant *and* the `additional` bytes about to be
/// appended in one go, instead of `to_mut()`'s exact-size clone followed by
/// an immediate regrowth on the first `push_str`.
#[inline]
fn cow_to_mut_reserve<'a>(cow: &'a mut Cow<'static, str>, additional: usize) -> &'a mut String {
    match cow {
        Cow::Borrowed(s) => {
            let mut owned = String::with_capacity(s.len().saturating_add(additional));
            owned.push_str(s);
            *cow = Cow::Owned(owned);
        }
        Cow::Owned(s) => s.reserve(additional),
    }
    // Now always owned, so this is a plain borrow.
    cow.to_mut()
}

/// A string that is safe to use in HTML contexts (such as template
/// interpolation or DOM properties).
///
/// The safety contract of `SafeHtml` is that its value as a string will not
/// cause untrusted script execution (XSS) when evaluated as HTML in a
/// browser.
///
/// Construct instances using safe validators like [`SafeHtml::escape`] or
/// [`SafeHtml::comment`].
///
/// # Security
///
/// With the `serde` feature, `Deserialize` trusts the input string (the
/// contract cannot be re-verified). Only deserialize from trusted storage
/// or internal services, never from user-controlled request bodies.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeHtml {
    html: Cow<'static, str>,
}

impl SafeHtml {
    /// Creates a `SafeHtml` instance containing an empty string.
    pub const fn empty() -> Self {
        SafeHtml {
            html: Cow::Borrowed(""),
        }
    }

    /// Creates a `SafeHtml` from a compile-time constant or heavily vetted
    /// static string.
    ///
    /// # Security
    ///
    /// The `&'static str` bound is intended for string literals reviewed
    /// alongside the code. Do not pass leaked runtime strings.
    pub const fn from_constant(val: &'static str) -> Self {
        SafeHtml {
            html: Cow::Borrowed(val),
        }
    }

    /// Creates a `SafeHtml` instance representing a non-breaking space
    /// (`&nbsp;`).
    pub const fn nbsp() -> Self {
        SafeHtml {
            html: Cow::Borrowed("&nbsp;"),
        }
    }

    /// Creates a `SafeHtml` instance representing the HTML5 doctype
    /// declaration.
    pub const fn html5_doctype_declaration() -> Self {
        SafeHtml {
            html: Cow::Borrowed("<!DOCTYPE html>"),
        }
    }

    /// Creates a `SafeHtml` instance by escaping HTML markup in `text`.
    pub fn escape(text: &str) -> Self {
        let mut html = String::with_capacity(text.len());
        let _ = escape_html_and_coerce_to(text, &mut html);
        SafeHtml {
            html: Cow::Owned(html),
        }
    }

    /// A version of `SafeHtml::escape` that preserves valid HTML character
    /// references.
    pub fn escape_allow_character_references(text: &str) -> Self {
        let mut html = String::with_capacity(text.len());
        let _ = escape_allow_character_references_to(text, &mut html);
        SafeHtml {
            html: Cow::Owned(html),
        }
    }

    /// Creates a `SafeHtml` instance by escaping HTML markup in `text` and
    /// embedding it between HTML comment markers.
    pub fn comment(text: &str) -> Self {
        let mut html = String::with_capacity(text.len() + 7);
        html.push_str("<!--");
        let _ = escape_html_and_coerce_to(text, &mut html);
        html.push_str("-->");
        SafeHtml {
            html: Cow::Owned(html),
        }
    }

    /// Create a `SafeHtml` from a raw string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the string satisfies the safe HTML
    /// contract (it cannot trigger XSS).
    pub unsafe fn from_string_unchecked(html: String) -> Self {
        SafeHtml {
            html: Cow::Owned(html),
        }
    }

    /// Appends another `SafeHtml` to this one.
    pub fn append(&mut self, other: &SafeHtml) -> &mut Self {
        cow_to_mut_reserve(&mut self.html, other.html.len()).push_str(&other.html);
        self
    }

    /// Appends `text` to this `SafeHtml` after escaping.
    pub fn escape_and_append(&mut self, text: &str) -> &mut Self {
        let buf = cow_to_mut_reserve(&mut self.html, text.len());
        let _ = escape_html_and_coerce_to(text, buf);
        self
    }

    /// Returns the string representation of the `SafeHtml` value.
    pub fn as_str(&self) -> &str {
        &self.html
    }

    /// Consumes the `SafeHtml` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.html.into_owned()
    }

    /// Serializes this `SafeHtml` into a replica of `SafeHtmlProto` for
    /// serialization compatibility.
    pub fn to_proto(&self) -> SafeHtmlProto {
        SafeHtmlProto {
            private_do_not_access_or_else_safe_html_wrapped_value: alloc::string::String::from(
                self.as_str(),
            ),
        }
    }

    /// Deserializes a replica of `SafeHtmlProto` into a `SafeHtml`
    /// instance.
    pub fn from_proto(proto: Option<&SafeHtmlProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                SafeHtml::from_string_unchecked(
                    p.private_do_not_access_or_else_safe_html_wrapped_value
                        .clone(),
                )
            },
            None => SafeHtml::empty(),
        }
    }

    /// Concatenates multiple `SafeHtml` values. Accepts both owned values
    /// and references.
    pub fn concat<I>(iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: core::borrow::Borrow<SafeHtml>,
    {
        let mut html = String::new();
        for item in iter {
            html.push_str(item.borrow().as_str());
        }
        SafeHtml {
            html: Cow::Owned(html),
        }
    }

    /// Joins multiple `SafeHtml` values with a delimiter. Accepts both
    /// owned values and references.
    pub fn join<I>(iter: I, separator: &SafeHtml) -> Self
    where
        I: IntoIterator,
        I::Item: core::borrow::Borrow<SafeHtml>,
    {
        let mut html = String::new();
        let mut first = true;
        for item in iter {
            if !first {
                html.push_str(separator.as_str());
            }
            first = false;
            html.push_str(item.borrow().as_str());
        }
        SafeHtml {
            html: Cow::Owned(html),
        }
    }
}

impl core::fmt::Display for SafeHtml {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.html)
    }
}

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

impl core::ops::Deref for SafeHtml {
    type Target = crate::SafeHtmlStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `SafeHtml` contract.
        unsafe { crate::SafeHtmlStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<SafeHtml> for String {
    fn from(value: SafeHtml) -> Self {
        value.html.into_owned()
    }
}

impl<T: core::borrow::Borrow<SafeHtml>> FromIterator<T> for SafeHtml {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        SafeHtml::concat(iter)
    }
}

// Add Assign operations for ergonomic SafeHtml concatenation
impl core::ops::AddAssign<&SafeHtml> for SafeHtml {
    fn add_assign(&mut self, rhs: &SafeHtml) {
        self.append(rhs);
    }
}

impl core::ops::AddAssign<SafeHtml> for SafeHtml {
    fn add_assign(&mut self, rhs: SafeHtml) {
        self.append(&rhs);
    }
}

impl core::ops::Add<&SafeHtml> for SafeHtml {
    type Output = SafeHtml;
    fn add(mut self, rhs: &SafeHtml) -> Self::Output {
        self += rhs;
        self
    }
}

impl core::ops::Add<SafeHtml> for SafeHtml {
    type Output = SafeHtml;
    fn add(mut self, rhs: SafeHtml) -> Self::Output {
        self += &rhs;
        self
    }
}

// --- SafeUrl ---

/// A string that is safe to use where URLs are expected in DOM APIs and
/// HTML documents.
///
/// The safety contract of `SafeUrl` is that its value as a string will not
/// cause untrusted script execution when evaluated as a hyperlink URL
/// (such as in `href`).
///
/// # Security
///
/// With the `serde` feature, `Deserialize` re-validates the URL and fails
/// deserialization on unsafe input.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeUrl {
    url: Cow<'static, str>,
}

impl SafeUrl {
    /// Creates an empty `SafeUrl`.
    pub const fn empty() -> Self {
        SafeUrl {
            url: Cow::Borrowed(""),
        }
    }

    /// Creates a `SafeUrl` from a compile-time constant or heavily vetted
    /// static URL.
    ///
    /// # Security
    ///
    /// The `&'static str` bound is intended for string literals reviewed
    /// alongside the code. Do not pass leaked runtime strings.
    pub const fn from_constant(val: &'static str) -> Self {
        SafeUrl {
            url: Cow::Borrowed(val),
        }
    }

    /// Creates a `SafeUrl` from the given URL, validating that the scheme
    /// is not `javascript:`.
    ///
    /// Falls back to `INNOCUOUS_URL` if validation fails.
    pub fn sanitize_block_only_javascript(url: &str) -> Self {
        if is_safe_url_block_javascript(url) {
            SafeUrl {
                url: Cow::Owned(String::from(url)),
            }
        } else {
            SafeUrl {
                url: Cow::Borrowed(INNOCUOUS_URL),
            }
        }
    }

    /// Creates a `SafeUrl` from the given URL, validating it against
    /// default safe schemes.
    ///
    /// Falls back to `INNOCUOUS_URL` if validation fails.
    pub fn sanitize(url: &str) -> Self {
        if is_safe_url_restrictive(url) {
            SafeUrl {
                url: Cow::Owned(String::from(url)),
            }
        } else {
            SafeUrl {
                url: Cow::Borrowed(INNOCUOUS_URL),
            }
        }
    }

    /// Creates a `SafeUrl` from the given URL, validating it against
    /// default and custom schemes.
    ///
    /// Falls back to `INNOCUOUS_URL` if validation fails.
    pub fn sanitize_with_schemes<S: AsRef<str>>(url: &str, extra_schemes: &[S]) -> Self {
        if is_safe_url_restrictive_with_schemes(url, extra_schemes) {
            SafeUrl {
                url: Cow::Owned(String::from(url)),
            }
        } else {
            SafeUrl {
                url: Cow::Borrowed(INNOCUOUS_URL),
            }
        }
    }

    /// Validates and sanitizes a URL for use in CSS context (such as style
    /// attributes or stylesheets).
    ///
    /// If validation fails, returns `INNOCUOUS_URL`. If it passes,
    /// percent-escapes CSS-sensitive characters.
    pub fn sanitize_for_css(url: &str) -> Self {
        if !is_safe_url_restrictive(url) {
            return SafeUrl {
                url: Cow::Borrowed(INNOCUOUS_URL),
            };
        }
        let mut escaped = String::with_capacity(url.len());
        let _ = percent_escape_css_url_to(url, &mut escaped);
        SafeUrl {
            url: Cow::Owned(escaped),
        }
    }

    /// Create a `SafeUrl` from a string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the string satisfies the safe URL
    /// contract.
    pub unsafe fn from_string_unchecked(url: String) -> Self {
        SafeUrl {
            url: Cow::Owned(url),
        }
    }

    /// Appends a query parameter with a percent-encoded name and value.
    ///
    /// The pair is inserted before any `#fragment`, using `?` or `&` as
    /// appropriate. Because both name and value are strictly
    /// percent-encoded, untrusted input cannot inject additional
    /// parameters or alter the URL structure.
    pub fn push_query_param(&mut self, name: &str, value: &str) -> &mut Self {
        push_query_param_impl(&mut self.url, name, value);
        self
    }

    /// Returns the string representation of the `SafeUrl` value.
    pub fn as_str(&self) -> &str {
        &self.url
    }

    /// Consumes the `SafeUrl` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.url.into_owned()
    }

    /// Serializes this `SafeUrl` into a replica of `SafeUrlProto` for
    /// serialization compatibility.
    pub fn to_proto(&self) -> SafeUrlProto {
        SafeUrlProto {
            private_do_not_access_or_else_safe_url_wrapped_value: alloc::string::String::from(
                self.as_str(),
            ),
        }
    }

    /// Deserializes a replica of `SafeUrlProto` into a `SafeUrl` instance.
    pub fn from_proto(proto: Option<&SafeUrlProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                SafeUrl::from_string_unchecked(
                    p.private_do_not_access_or_else_safe_url_wrapped_value
                        .clone(),
                )
            },
            None => SafeUrl::empty(),
        }
    }
}

/// Shared implementation of safe query-parameter appending: inserts
/// `?name=value` / `&name=value` (both parts percent-encoded) before any
/// `#fragment`. The common fragment-free case appends in place with no
/// temporary allocation.
fn push_query_param_impl(url: &mut Cow<'static, str>, name: &str, value: &str) {
    let extra = name.len().saturating_add(value.len()).saturating_add(2);
    // One capacity-aware Cow promotion up front; everything below operates
    // on a plain String (repeated Cow derefs cost measurable nanoseconds
    // on this hot path).
    let url = cow_to_mut_reserve(url, extra);
    match url.find('#') {
        None => {
            let has_query = url.contains('?');
            url.push(if has_query { '&' } else { '?' });
            let _ = url_encode_component_to(name, &mut *url);
            url.push('=');
            let _ = url_encode_component_to(value, &mut *url);
        }
        Some(insert_at) => {
            let has_query = url.get(..insert_at).unwrap_or("").contains('?');
            let mut param = String::with_capacity(extra);
            param.push(if has_query { '&' } else { '?' });
            let _ = url_encode_component_to(name, &mut param);
            param.push('=');
            let _ = url_encode_component_to(value, &mut param);
            url.insert_str(insert_at, &param);
        }
    }
}

impl core::fmt::Display for SafeUrl {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.url)
    }
}

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

impl core::ops::Deref for SafeUrl {
    type Target = crate::SafeUrlStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `SafeUrl` contract.
        unsafe { crate::SafeUrlStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<SafeUrl> for String {
    fn from(value: SafeUrl) -> Self {
        value.url.into_owned()
    }
}

// --- SafeScript ---

/// A string that is safe to use in JavaScript execution contexts (like
/// inline `<script>` tags).
///
/// The security contract is that this value represents vetted JavaScript
/// code and does not contain untrusted input.
///
/// # Security
///
/// With the `serde` feature, `Deserialize` trusts the input string. Only
/// deserialize from trusted storage or internal services.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeScript {
    script: Cow<'static, str>,
}

impl SafeScript {
    /// Creates an empty `SafeScript`.
    pub const fn empty() -> Self {
        SafeScript {
            script: Cow::Borrowed(""),
        }
    }

    /// Creates a `SafeScript` from a compile-time constant or heavily
    /// vetted static string.
    pub const fn from_constant(val: &'static str) -> Self {
        SafeScript {
            script: Cow::Borrowed(val),
        }
    }

    /// Creates a `SafeScript` by taking an existing JSON string and
    /// escaping HTML-sensitive characters.
    ///
    /// Replaces `<`, `>`, and `&` with their Unicode escape sequences
    /// (`<`, etc.) so that the JSON can be safely embedded in
    /// an HTML `<script>` block.
    ///
    /// # Safety note
    /// The input must be a syntactically valid JSON string. This function
    /// only performs HTML escaping, it does not validate JSON
    /// correctness.
    pub fn from_escaped_json(json: &str) -> Self {
        let mut script = String::with_capacity(json.len());
        let _ = escape_json_for_script_to(json, &mut script);
        SafeScript {
            script: Cow::Owned(script),
        }
    }

    /// Create a `SafeScript` from a string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the string satisfies the safe script
    /// contract (no untrusted code execution).
    pub unsafe fn from_string_unchecked(script: String) -> Self {
        SafeScript {
            script: Cow::Owned(script),
        }
    }

    /// Returns the string representation of the `SafeScript` value.
    pub fn as_str(&self) -> &str {
        &self.script
    }

    /// Consumes the `SafeScript` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.script.into_owned()
    }

    /// Serializes this `SafeScript` into a replica of `SafeScriptProto`
    /// for serialization compatibility.
    pub fn to_proto(&self) -> SafeScriptProto {
        SafeScriptProto {
            private_do_not_access_or_else_safe_script_wrapped_value: alloc::string::String::from(
                self.as_str(),
            ),
        }
    }

    /// Deserializes a replica of `SafeScriptProto` into a `SafeScript`
    /// instance.
    pub fn from_proto(proto: Option<&SafeScriptProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                SafeScript::from_string_unchecked(
                    p.private_do_not_access_or_else_safe_script_wrapped_value
                        .clone(),
                )
            },
            None => SafeScript::empty(),
        }
    }
}

impl core::fmt::Display for SafeScript {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.script)
    }
}

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

impl core::ops::Deref for SafeScript {
    type Target = crate::SafeScriptStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `SafeScript` contract.
        unsafe { crate::SafeScriptStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<SafeScript> for String {
    fn from(value: SafeScript) -> Self {
        value.script.into_owned()
    }
}

// --- TrustedResourceUrl ---

/// A URL representing a trusted resource that is safe to load as executable
/// code or styling (like `<script src="...">`).
///
/// Unlike `SafeUrl`, this represents a resource under direct developer
/// control (e.g. same-origin scripts).
///
/// # Security
///
/// With the `serde` feature, `Deserialize` trusts the input string. Only
/// deserialize from trusted storage or internal services.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TrustedResourceUrl {
    url: Cow<'static, str>,
}

impl TrustedResourceUrl {
    /// Creates an empty `TrustedResourceUrl`.
    pub const fn empty() -> Self {
        TrustedResourceUrl {
            url: Cow::Borrowed(""),
        }
    }

    /// Creates a `TrustedResourceUrl` from a compile-time constant or
    /// heavily vetted static URL.
    pub const fn from_constant(val: &'static str) -> Self {
        TrustedResourceUrl {
            url: Cow::Borrowed(val),
        }
    }

    /// Create a `TrustedResourceUrl` from a string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the string represents a resource under
    /// complete application control.
    pub unsafe fn from_string_unchecked(url: String) -> Self {
        TrustedResourceUrl {
            url: Cow::Owned(url),
        }
    }

    /// Appends a query parameter with a percent-encoded name and value.
    ///
    /// The pair is inserted before any `#fragment`, using `?` or `&` as
    /// appropriate. Because both name and value are strictly
    /// percent-encoded, untrusted input cannot inject additional
    /// parameters or alter the URL structure, so this operation preserves
    /// the trusted-resource contract.
    pub fn push_query_param(&mut self, name: &str, value: &str) -> &mut Self {
        push_query_param_impl(&mut self.url, name, value);
        self
    }

    /// Returns the string representation of the `TrustedResourceUrl` value.
    pub fn as_str(&self) -> &str {
        &self.url
    }

    /// Consumes the `TrustedResourceUrl` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.url.into_owned()
    }

    /// Serializes this `TrustedResourceUrl` into a replica of
    /// `TrustedResourceUrlProto` for serialization compatibility.
    pub fn to_proto(&self) -> TrustedResourceUrlProto {
        TrustedResourceUrlProto {
            private_do_not_access_or_else_trusted_resource_url_wrapped_value:
                alloc::string::String::from(self.as_str()),
        }
    }

    /// Deserializes a replica of `TrustedResourceUrlProto` into a
    /// `TrustedResourceUrl` instance.
    pub fn from_proto(proto: Option<&TrustedResourceUrlProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                TrustedResourceUrl::from_string_unchecked(
                    p.private_do_not_access_or_else_trusted_resource_url_wrapped_value
                        .clone(),
                )
            },
            None => TrustedResourceUrl::empty(),
        }
    }
}

impl core::fmt::Display for TrustedResourceUrl {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.url)
    }
}

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

impl core::ops::Deref for TrustedResourceUrl {
    type Target = crate::TrustedResourceUrlStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `TrustedResourceUrl` contract.
        unsafe { crate::TrustedResourceUrlStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<TrustedResourceUrl> for String {
    fn from(value: TrustedResourceUrl) -> Self {
        value.url.into_owned()
    }
}

// --- SafeStyle ---

/// A sequence of CSS declarations (`name1:value1;name2:value2;`) that is
/// safe to use in CSS contexts such as `style` attributes.
///
/// The safety contract (per Google's safe-html-types) is that the value
/// will not cause untrusted script execution when evaluated as CSS: it
/// never contains literal angle brackets, and it never ends inside a
/// property name or value, so `SafeStyle` values compose safely by
/// concatenation.
///
/// Build instances with [`SafeStyle::from_properties`] /
/// [`SafeStyle::push_property`], which validate names and sanitize values
/// (invalid values are replaced with [`INNOCUOUS_PROPERTY_VALUE`]).
///
/// # Security
///
/// With the `serde` feature, `Deserialize` trusts the input string. Only
/// deserialize from trusted storage or internal services.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeStyle {
    style: Cow<'static, str>,
}

impl SafeStyle {
    /// Creates an empty `SafeStyle`.
    pub const fn empty() -> Self {
        SafeStyle {
            style: Cow::Borrowed(""),
        }
    }

    /// Creates a `SafeStyle` from a compile-time constant or heavily
    /// vetted static string.
    ///
    /// # Security
    ///
    /// The constant must satisfy the `SafeStyle` contract: complete
    /// `name:value;` declarations with no literal angle brackets.
    pub const fn from_constant(val: &'static str) -> Self {
        SafeStyle {
            style: Cow::Borrowed(val),
        }
    }

    /// Builds a `SafeStyle` from `(property_name, property_value)` pairs.
    ///
    /// Names failing [`is_safe_style_property_name`] are skipped; values
    /// failing [`is_safe_style_property_value`] are replaced with
    /// [`INNOCUOUS_PROPERTY_VALUE`].
    pub fn from_properties(properties: &[(&str, &str)]) -> Self {
        let mut style = SafeStyle::empty();
        for (name, value) in properties {
            style.push_property(name, value);
        }
        style
    }

    /// Appends one `name:value;` declaration.
    ///
    /// The name must match [`is_safe_style_property_name`] (otherwise the
    /// declaration is skipped entirely). The value is trimmed and
    /// validated with [`is_safe_style_property_value`]; on failure it is
    /// replaced with [`INNOCUOUS_PROPERTY_VALUE`] so the output remains
    /// structurally well-formed.
    pub fn push_property(&mut self, name: &str, value: &str) -> &mut Self {
        if !is_safe_style_property_name(name) {
            return self;
        }
        let value = value.trim();
        let value = if is_safe_style_property_value(value) {
            value
        } else {
            INNOCUOUS_PROPERTY_VALUE
        };
        let buf = cow_to_mut_reserve(&mut self.style, name.len() + value.len() + 2);
        buf.push_str(name);
        buf.push(':');
        buf.push_str(value);
        buf.push(';');
        self
    }

    /// Appends a `background-image:url("...");` declaration.
    ///
    /// The URL is first sanitized like [`SafeUrl::sanitize`] (unsafe URLs
    /// become [`INNOCUOUS_URL`]) and then CSS-percent-escaped, so quotes
    /// and parentheses cannot break out of the `url("...")` token.
    pub fn push_background_image_url(&mut self, url: &str) -> &mut Self {
        let checked = if is_safe_url_restrictive(url) {
            url
        } else {
            INNOCUOUS_URL
        };
        // `background-image:url("` + url + `");`
        let buf = cow_to_mut_reserve(&mut self.style, checked.len() + 25);
        buf.push_str("background-image:url(\"");
        let _ = percent_escape_css_url_to(checked, &mut *buf);
        buf.push_str("\");");
        self
    }

    /// Appends another `SafeStyle`. Safe because complete declaration
    /// sequences compose by concatenation.
    pub fn append(&mut self, other: &SafeStyle) -> &mut Self {
        cow_to_mut_reserve(&mut self.style, other.style.len()).push_str(&other.style);
        self
    }

    /// Create a `SafeStyle` from a string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure the string satisfies the `SafeStyle`
    /// contract.
    pub unsafe fn from_string_unchecked(style: String) -> Self {
        SafeStyle {
            style: Cow::Owned(style),
        }
    }

    /// Returns the string representation of the `SafeStyle` value.
    pub fn as_str(&self) -> &str {
        &self.style
    }

    /// Consumes the `SafeStyle` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.style.into_owned()
    }

    /// Serializes this `SafeStyle` into a replica of `SafeStyleProto` for
    /// serialization compatibility.
    pub fn to_proto(&self) -> SafeStyleProto {
        SafeStyleProto {
            private_do_not_access_or_else_safe_style_wrapped_value: alloc::string::String::from(
                self.as_str(),
            ),
        }
    }

    /// Deserializes a replica of `SafeStyleProto` into a `SafeStyle`
    /// instance.
    pub fn from_proto(proto: Option<&SafeStyleProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                SafeStyle::from_string_unchecked(
                    p.private_do_not_access_or_else_safe_style_wrapped_value
                        .clone(),
                )
            },
            None => SafeStyle::empty(),
        }
    }
}

impl core::fmt::Display for SafeStyle {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.style)
    }
}

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

impl core::ops::Deref for SafeStyle {
    type Target = crate::SafeStyleStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `SafeStyle` contract.
        unsafe { crate::SafeStyleStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<SafeStyle> for String {
    fn from(value: SafeStyle) -> Self {
        value.style.into_owned()
    }
}

// --- SafeStyleSheet ---

/// A complete CSS style sheet that is safe to embed in a `<style>`
/// element.
///
/// The safety contract (per Google's safe-html-types) is that the value
/// will not cause untrusted script execution when evaluated as CSS, and
/// in particular contains no unescaped `<` characters.
///
/// # Security
///
/// With the `serde` feature, `Deserialize` trusts the input string. Only
/// deserialize from trusted storage or internal services.
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeStyleSheet {
    sheet: Cow<'static, str>,
}

impl SafeStyleSheet {
    /// Creates an empty `SafeStyleSheet`.
    pub const fn empty() -> Self {
        SafeStyleSheet {
            sheet: Cow::Borrowed(""),
        }
    }

    /// Creates a `SafeStyleSheet` from a compile-time constant or heavily
    /// vetted static string.
    pub const fn from_constant(val: &'static str) -> Self {
        SafeStyleSheet {
            sheet: Cow::Borrowed(val),
        }
    }

    /// Builds a `selector{declarations}` style rule from a validated
    /// selector and a [`SafeStyle`].
    ///
    /// Returns `None` if the selector fails [`is_safe_css_selector`].
    pub fn from_style_rule(selector: &str, style: &SafeStyle) -> Option<Self> {
        if !is_safe_css_selector(selector) {
            return None;
        }
        let mut sheet = String::with_capacity(selector.len() + style.as_str().len() + 2);
        sheet.push_str(selector);
        sheet.push('{');
        sheet.push_str(style.as_str());
        sheet.push('}');
        Some(SafeStyleSheet {
            sheet: Cow::Owned(sheet),
        })
    }

    /// Appends another `SafeStyleSheet`. Safe because complete style
    /// sheets compose by concatenation.
    pub fn append(&mut self, other: &SafeStyleSheet) -> &mut Self {
        cow_to_mut_reserve(&mut self.sheet, other.sheet.len()).push_str(&other.sheet);
        self
    }

    /// Create a `SafeStyleSheet` from a string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure the string satisfies the `SafeStyleSheet`
    /// contract (no unescaped `<`, no untrusted script execution).
    pub unsafe fn from_string_unchecked(sheet: String) -> Self {
        SafeStyleSheet {
            sheet: Cow::Owned(sheet),
        }
    }

    /// Returns the string representation of the `SafeStyleSheet` value.
    pub fn as_str(&self) -> &str {
        &self.sheet
    }

    /// Consumes the `SafeStyleSheet` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.sheet.into_owned()
    }

    /// Serializes this `SafeStyleSheet` into a replica of
    /// `SafeStyleSheetProto` for serialization compatibility.
    pub fn to_proto(&self) -> SafeStyleSheetProto {
        SafeStyleSheetProto {
            private_do_not_access_or_else_safe_style_sheet_wrapped_value:
                alloc::string::String::from(self.as_str()),
        }
    }

    /// Deserializes a replica of `SafeStyleSheetProto` into a
    /// `SafeStyleSheet` instance.
    pub fn from_proto(proto: Option<&SafeStyleSheetProto>) -> Self {
        match proto {
            Some(p) => unsafe {
                SafeStyleSheet::from_string_unchecked(
                    p.private_do_not_access_or_else_safe_style_sheet_wrapped_value
                        .clone(),
                )
            },
            None => SafeStyleSheet::empty(),
        }
    }
}

impl core::fmt::Display for SafeStyleSheet {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.sheet)
    }
}

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

impl core::ops::Deref for SafeStyleSheet {
    type Target = crate::SafeStyleSheetStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the `SafeStyleSheet` contract.
        unsafe { crate::SafeStyleSheetStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<SafeStyleSheet> for String {
    fn from(value: SafeStyleSheet) -> Self {
        value.sheet.into_owned()
    }
}

// --- Identifier ---

/// An owned, validated HTML identifier (`[A-Za-z][A-Za-z0-9_-]*`), safe to
/// use in `id`/`name`/`class` attributes and CSS selectors without escaping.
/// Mirrors Go safehtml's `Identifier`.
///
/// Construct with the compile-time-validated [`Identifier::from_constant`],
/// the runtime-validated [`Identifier::try_from_value`], or
/// [`Identifier::try_with_constant_prefix`] for namespacing runtime values
/// under a vetted prefix.
///
/// # Security
///
/// With the `serde` feature, `Deserialize` re-validates the identifier and
/// fails deserialization on invalid input.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Identifier {
    id: Cow<'static, str>,
}

impl Identifier {
    /// Creates an `Identifier` from a compile-time constant, validating it
    /// in `const` context. Allocation-free.
    ///
    /// # Panics
    ///
    /// Panics at compile time (in `const` context) if `val` is not a valid
    /// identifier.
    pub const fn from_constant(val: &'static str) -> Self {
        assert!(
            is_safe_identifier(val),
            "Identifier::from_constant requires [A-Za-z][A-Za-z0-9_-]*"
        );
        Identifier {
            id: Cow::Borrowed(val),
        }
    }

    /// Validates `value` at runtime, returning `None` if it is not a valid
    /// identifier.
    pub fn try_from_value(value: &str) -> Option<Identifier> {
        if is_safe_identifier(value) {
            Some(Identifier {
                id: Cow::Owned(String::from(value)),
            })
        } else {
            None
        }
    }

    /// Builds `prefix-value` from a vetted constant prefix and a runtime
    /// value, for namespacing user-derived names (e.g. `row-{key}`).
    ///
    /// The prefix must itself be a valid identifier; the value may
    /// additionally start with a digit (the prefix supplies the leading
    /// letter). Returns `None` if either part is invalid.
    pub fn try_with_constant_prefix(prefix: &'static str, value: &str) -> Option<Identifier> {
        if !is_safe_identifier(prefix)
            || value.is_empty()
            || !value
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        {
            return None;
        }
        let mut id = String::with_capacity(prefix.len() + 1 + value.len());
        id.push_str(prefix);
        id.push('-');
        id.push_str(value);
        Some(Identifier { id: Cow::Owned(id) })
    }

    /// Create an `Identifier` from a raw string without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure the string matches `[A-Za-z][A-Za-z0-9_-]*`.
    pub unsafe fn from_string_unchecked(id: String) -> Self {
        Identifier { id: Cow::Owned(id) }
    }

    /// Returns the string representation of the `Identifier`.
    pub fn as_str(&self) -> &str {
        &self.id
    }

    /// Consumes the `Identifier` and returns its inner `String`.
    pub fn into_string(self) -> String {
        self.id.into_owned()
    }
}

impl core::fmt::Display for Identifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.id)
    }
}

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

impl core::ops::Deref for Identifier {
    type Target = crate::IdentifierStr;
    fn deref(&self) -> &Self::Target {
        // SAFETY: this value already satisfies the identifier contract.
        unsafe { crate::IdentifierStr::from_str_unchecked(self.as_str()) }
    }
}

impl From<Identifier> for String {
    fn from(value: Identifier) -> Self {
        value.id.into_owned()
    }
}

/// A replica of the protobuf message `SafeHtmlProto` for compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeHtmlProto {
    pub private_do_not_access_or_else_safe_html_wrapped_value: String,
}

/// A replica of the protobuf message `SafeUrlProto` for compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeUrlProto {
    pub private_do_not_access_or_else_safe_url_wrapped_value: String,
}

/// A replica of the protobuf message `SafeScriptProto` for compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeScriptProto {
    pub private_do_not_access_or_else_safe_script_wrapped_value: String,
}

/// A replica of the protobuf message `TrustedResourceUrlProto` for
/// compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedResourceUrlProto {
    pub private_do_not_access_or_else_trusted_resource_url_wrapped_value: String,
}

/// A replica of the protobuf message `SafeStyleProto` for compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeStyleProto {
    pub private_do_not_access_or_else_safe_style_wrapped_value: String,
}

/// A replica of the protobuf message `SafeStyleSheetProto` for
/// compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SafeStyleSheetProto {
    pub private_do_not_access_or_else_safe_style_sheet_wrapped_value: String,
}