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
//! # Safehtml
//!
//! A pure Rust, 2024 edition, `no_std`-compatible library that implements
//! safety contracts and validation for strings used in security-sensitive web
//! contexts (HTML, CSS, JavaScript, and URLs).
//!
//! The design is a Rust implementation of Google's
//! [safe-html-types](https://github.com/google/safe-html-types) contracts (as
//! seen in the C++ and Go `safehtml` libraries), covering all six contract
//! types: [`SafeHtml`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
//! [`SafeUrl`], and [`TrustedResourceUrl`]. It is engineered specifically to
//! prevent Cross-Site Scripting (XSS) and code-injection vulnerabilities by
//! construction.
//!
//! ## Embedded & `no_std` Suitability
//!
//! This crate is highly optimized for embedded and resource-constrained
//! environments:
//! 1. **Zero-Allocation Core**: All validation and escaping logic operates
//! directly on `&str` and writes to implementations of [`core::fmt::Write`].
//! This allows formatting directly into stack-allocated buffers (e.g.,
//! `heapless::String` or direct peripheral I/O) without any dynamic memory
//! allocations.
//! 2. **No Regular Expressions**: Unlike Go and C++ libraries which depend on
//! heavy, runtime-compiled regex engines, this library implements fast,
//! deterministic, table-driven linear scans accelerated by a portable SWAR
//! word scanner (or `core::simd` with the nightly-only `simd` feature).
//! This minimizes code size and CPU usage; the default build works on
//! stable Rust with no nightly features.
//! 3. **Borrowed Safe Types Everywhere**: The `#[repr(transparent)]` borrowed
//! types ([`SafeHtmlStr`], [`SafeUrlStr`], [`SafeScriptStr`],
//! [`SafeStyleStr`], [`SafeStyleSheetStr`], [`TrustedResourceUrlStr`])
//! carry the safety contracts without any allocation, so type-driven
//! security works even without `alloc`. Their `from_constant` constructors
//! are `const` and usable in `static` items.
//! 4. **Optional `alloc` Feature**: The high-level owned types ([`SafeHtml`],
//! [`SafeUrl`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
//! [`TrustedResourceUrl`]) which enforce safety boundaries via type-safety
//! are gated under the `alloc` feature (enabled by default). They store
//! `Cow<'static, str>`, so `from_constant`/`empty` are `const` and
//! allocation-free; each owned type [`Deref`](core::ops::Deref)s to its
//! borrowed counterpart. Disable default features
//! (`default-features = false`) to compile in a pure, alloc-free
//! environment.
//! 5. **Optional `serde` Feature**: Provides optional
//! serialization/deserialization with built-in validation checks.
//!
//! ## Feature Flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `alloc` | yes | Heap-allocated wrapper types and `String`-returning convenience functions. |
//! | `serde` | no | `Serialize`/`Deserialize` implementations for the wrapper types. |
//! | `simd` | no | `core::simd` scanners (16 bytes/step); requires a nightly toolchain. |
//!
//! ## Security Model
//!
//! Each wrapper type carries a contract: holding an instance means its string
//! value is safe to use in the corresponding sink without further escaping.
//! Instances are created through validating/escaping constructors; the
//! `unsafe fn from_string_unchecked` escape hatches place the burden of proof
//! on the caller and are greppable by design.
//!
//! ## Migration Hazard: Double Escaping
//!
//! `String`/`&str` values interpolated as parts (in [`safe_html_cat!`],
//! [`safe_html_write!`], [`safe_html_format!`], [`safe_html_format_to!`],
//! and [`SafeHtmlBuilder::push`]) are **always HTML-escaped** — that is the
//! right default, because a bare string carries no safety contract.
//!
//! During incremental migration of an existing codebase, however, helper
//! functions often still return *already-escaped* `String`s (e.g. a legacy
//! `money()` or `select()` helper built on `format!`). Passing such a value
//! as a part escapes it **again**: it compiles cleanly and only shows up at
//! runtime as visible `&amp;` / `&lt;` artifacts. The type system
//! cannot catch this, precisely because `String` must stay "untrusted".
//!
//! The fix is to move the trust boundary into the helper: have it return
//! [`SafeHtml`] (built with [`safe_html_format!`]/[`safe_html_cat!`], or —
//! after an audit — `unsafe { SafeHtml::from_string_unchecked(..) }`)
//! instead of `String`. Until a helper is converted, do **not** pass its
//! output as a part. Rule of thumb: any `String` crossing a part boundary
//! must be raw, unescaped text.
//!
//! **Serde caveat**: deserializing [`SafeUrl`] re-validates the value and
//! fails on unsafe input, but deserializing [`SafeHtml`], [`SafeScript`], and
//! [`TrustedResourceUrl`] trusts the input (there is no cheap way to verify
//! "already-safe HTML"). Only deserialize these types from trusted storage or
//! internal services — never directly from user-controlled request bodies.
//!
//! ## Example: Embedded/Alloc-Free Usage
//!
//! ```rust
//! use safehtml::{escape_html_and_coerce_to, is_safe_url_restrictive};
//!
//! // Write HTML directly into a custom buffer (which implements core::fmt::Write)
//! struct SimpleBuffer {
//! storage: [u8; 128],
//! len: usize,
//! }
//!
//! impl core::fmt::Write for SimpleBuffer {
//! fn write_str(&mut self, s: &str) -> core::fmt::Result {
//! let bytes = s.as_bytes();
//! if self.len + bytes.len() > self.storage.len() {
//! return Err(core::fmt::Error);
//! }
//! self.storage[self.len..self.len + bytes.len()].copy_from_slice(bytes);
//! self.len += bytes.len();
//! Ok(())
//! }
//! }
//!
//! let mut buf = SimpleBuffer { storage: [0; 128], len: 0 };
//! escape_html_and_coerce_to("Hello <World>", &mut buf).unwrap();
//!
//! // Validate a URL safely without dynamic allocation:
//! let untrusted_url = "https://example.com/api";
//! if is_safe_url_restrictive(untrusted_url) {
//! // URL is safe to use in href contexts
//! }
//! ```
pub extern crate alloc;
// Compile the README examples as doctests so the documentation cannot drift
// out of sync with the API.
;
pub use SafeHtmlBuilder;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
/// Implementation details of the crate macros ([`safe_html_cat!`],
/// [`safe_html_format!`], [`safe_html_format_to!`]).
///
/// Not public API: there are no semver guarantees, and calling these
/// directly can mint safe-type values without their contracts being
/// upheld. The `unsafe` needed by the macro expansions lives here (and in
/// [`SafeHtmlBuilder`]) so that consumer crates with
/// `#![forbid(unsafe_code)]` can use the macros.
pub use ;
/// Concatenates multiple values (both `SafeHtml` and raw values that will be
/// HTML-escaped) into a single `SafeHtml`.
///
/// Automatically escapes standard types and keeps safe types unescaped.
/// Strings are *always* escaped — never pass a pre-escaped `String` (see
/// "Migration Hazard: Double Escaping" in the crate docs). For
/// template-shaped construction prefer
/// [`safe_html_format!`](crate::safe_html_format).
/// Writes multiple values (both safe types and raw values that will be
/// HTML-escaped) into any [`core::fmt::Write`] — the `no_std`,
/// zero-allocation sibling of [`safe_html_cat!`].
///
/// The first argument is the writer; the rest are parts implementing
/// [`SafeHtmlPart`]. Safe types ([`SafeHtml`], [`SafeHtmlStr`],
/// [`Identifier`]) pass through verbatim; strings and characters are
/// escaped; numbers and booleans are formatted. Evaluates to
/// [`core::fmt::Result`], so a full [`SliceWriter`] surfaces as `Err`.
///
/// ```rust
/// use safehtml::{SafeHtmlStr, SliceWriter, safe_html_write};
///
/// let mut buf = [0u8; 64];
/// let mut w = SliceWriter::new(&mut buf);
/// safe_html_write!(w, SafeHtmlStr::from_constant("<b>"), "5 < 6", 42).unwrap();
/// assert_eq!(w.as_str(), "<b>5 < 642");
/// ```