trillium-http 1.8.1

the http implementation for the trillium toolkit
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
use super::{HeaderName, HeaderNameInner::UnknownHeader};
use crate::compact_cow::CompactCow;
use hashbrown::{Equivalent, HashMap, HashSet};
use std::{
    cell::RefCell,
    cmp::Ordering,
    fmt::{self, Debug, Display, Formatter},
    hash::{Hash, Hasher},
    ops::Deref,
    sync::{OnceLock, RwLock},
};

#[derive(Clone)]
pub(crate) struct UnknownHeaderName<'a>(CompactCow<'a>);

impl UnknownHeaderName<'_> {
    pub(crate) fn is_valid_lower(&self) -> bool {
        // Lowercase tchar — the uppercase-letter branch is dropped because HTTP/2 and
        // HTTP/3 require field names to be lowercase on the wire. Otherwise matches
        // `is_tchar`.
        !self.is_empty()
            && self.chars().all(|c| {
                matches!(c,
                    'a'..='z'
                    | '0'..='9'
                    | '!'
                    | '#'
                    | '$'
                    | '%'
                    | '&'
                    | '\''
                    | '*'
                    | '+'
                    | '-'
                    | '.'
                    | '^'
                    | '_'
                    | '`'
                    | '|'
                    | '~',
                )
            })
    }

    pub(crate) fn into_lower(self) -> Self {
        match self.0 {
            CompactCow::Borrowed(borrowed) => {
                if let Some(first_upper) = borrowed.chars().position(|c| c.is_ascii_uppercase()) {
                    Self(CompactCow::Owned(
                        borrowed[..first_upper]
                            .chars()
                            .chain(
                                borrowed[first_upper..]
                                    .chars()
                                    .map(|c| c.to_ascii_lowercase()),
                            )
                            .collect(),
                    ))
                } else {
                    Self(CompactCow::Borrowed(borrowed))
                }
            }
            CompactCow::Owned(mut compact_string) => {
                compact_string.make_ascii_lowercase();
                Self(CompactCow::Owned(compact_string))
            }
            CompactCow::Shared(shared) => {
                if shared.bytes().any(|b| b.is_ascii_uppercase()) {
                    Self(CompactCow::Owned(shared.to_ascii_lowercase().into()))
                } else {
                    Self(CompactCow::Shared(shared))
                }
            }
        }
    }
}

impl PartialOrd for UnknownHeaderName<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for UnknownHeaderName<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&*other.0)
    }
}

impl PartialEq for UnknownHeaderName<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}

impl Eq for UnknownHeaderName<'_> {}

impl Hash for UnknownHeaderName<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for c in self.0.as_bytes() {
            c.to_ascii_lowercase().hash(state);
        }
    }
}

impl Debug for UnknownHeaderName<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for UnknownHeaderName<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<'a> From<UnknownHeaderName<'a>> for HeaderName<'a> {
    fn from(value: UnknownHeaderName<'a>) -> Self {
        HeaderName(UnknownHeader(value))
    }
}

impl<'a> From<&'a UnknownHeaderName<'_>> for HeaderName<'a> {
    fn from(value: &'a UnknownHeaderName<'_>) -> Self {
        HeaderName(UnknownHeader(value.reborrow()))
    }
}

fn is_tchar(c: char) -> bool {
    matches!(
        c,
        'a'..='z'
        | 'A'..='Z'
        | '0'..='9'
        | '!'
        | '#'
        | '$'
        | '%'
        | '&'
        | '\''
        | '*'
        | '+'
        | '-'
        | '.'
        | '^'
        | '_'
        | '`'
        | '|'
        | '~'
    )
}

impl UnknownHeaderName<'_> {
    pub(crate) fn is_valid(&self) -> bool {
        !self.is_empty() && self.0.chars().all(is_tchar)
    }

    pub(crate) fn into_owned(self) -> UnknownHeaderName<'static> {
        UnknownHeaderName(self.0.into_owned())
    }
}

impl<'a> UnknownHeaderName<'a> {
    pub(crate) fn reborrow<'b: 'a>(&'b self) -> UnknownHeaderName<'b> {
        Self(CompactCow::Borrowed(&self.0))
    }
}

impl From<String> for UnknownHeaderName<'static> {
    fn from(value: String) -> Self {
        Self(value.into())
    }
}

impl<'a> From<&'a str> for UnknownHeaderName<'a> {
    fn from(value: &'a str) -> Self {
        Self(value.into())
    }
}

impl<'a> From<CompactCow<'a>> for UnknownHeaderName<'a> {
    fn from(value: CompactCow<'a>) -> Self {
        Self(value)
    }
}

impl<'a> From<UnknownHeaderName<'a>> for CompactCow<'a> {
    fn from(value: UnknownHeaderName<'a>) -> Self {
        value.0
    }
}

impl Deref for UnknownHeaderName<'_> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Equivalent<UnknownHeaderName<'_>> for &UnknownHeaderName<'_> {
    fn equivalent(&self, key: &UnknownHeaderName<'_>) -> bool {
        key.eq_ignore_ascii_case(self)
    }
}

/// Process-global table of canonical lowercased `&'static str` for literal
/// header names that contained uppercase characters in source. Pure-lowercase
/// literals bypass this table entirely (no need to intern — they're already
/// `&'static`).
///
/// It is written once per literal and read once per literal per thread, after which
/// [`LOCAL_INTERN`] answers, so an `RwLock` is plenty. The hasher is case-insensitive so
/// we can probe with the original uppercase input without first allocating its
/// lowercased form.
///
/// Bounded above by distinct uppercase-containing lowercased literal names in
/// the binary.
static LOWER_INTERN: OnceLock<RwLock<HashSet<InternKey>>> = OnceLock::new();

/// Wrapper around `&'static str` whose `Hash`/`Eq` are case-insensitive on
/// ASCII. Lets the interner store the canonical lowercased form once and probe
/// with the original casing without rebuilding the lowercased string just to
/// look it up.
#[derive(Copy, Clone, Eq)]
struct InternKey(&'static str);

impl PartialEq for InternKey {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(other.0)
    }
}

impl Hash for InternKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for b in self.0.bytes() {
            state.write_u8(b.to_ascii_lowercase());
        }
    }
}

fn intern_table() -> &'static RwLock<HashSet<InternKey>> {
    LOWER_INTERN.get_or_init(|| RwLock::new(HashSet::new()))
}

thread_local! {
    /// Per-thread front for [`LOWER_INTERN`], keyed by a literal's address and length, which
    /// together identify its contents. Even an uncontended `RwLock::read` writes to a lock word
    /// that every core shares, so a thread that has already seen a literal skips the table.
    static LOCAL_INTERN: RefCell<HashMap<(usize, usize), &'static str>> =
        RefCell::new(HashMap::new());
}

/// Return a canonical lowercased `&'static str` for `s`.
///
/// - If `s` is already all-lowercase: returns `s` directly. No lock, no alloc.
/// - If this thread has interned `s` before: returns the canonical pointer from [`LOCAL_INTERN`].
/// - Otherwise: probes the intern table with a case-insensitive hash. On hit, returns the stored
///   canonical pointer. On miss, allocates the lowercased form, leaks it to obtain a `&'static
///   str`, and inserts.
///
/// The leak is bounded by the number of distinct uppercase-containing lowercased
/// literals in the binary — typically zero or single digits for well-behaved code.
fn intern_lowercase(s: &'static str) -> &'static str {
    if !s.bytes().any(|b| b.is_ascii_uppercase()) {
        return s;
    }
    let key = (s.as_ptr().addr(), s.len());
    if let Some(interned) = LOCAL_INTERN.with_borrow(|local| local.get(&key).copied()) {
        return interned;
    }
    let interned = intern_lowercase_shared(s);
    LOCAL_INTERN.with_borrow_mut(|local| local.insert(key, interned));
    interned
}

fn intern_lowercase_shared(s: &'static str) -> &'static str {
    let probe = InternKey(s);
    let table = intern_table();
    {
        let read = table.read().expect("intern table poisoned");
        if let Some(hit) = read.get(&probe) {
            return hit.0;
        }
    }
    // Allocate-and-leak inside the write lock so two threads racing for the same
    // uppercase literal don't both leak: the second arrival finds the first's
    // insert via the post-acquire `get` and bails before allocating.
    let mut write = table.write().expect("intern table poisoned");
    if let Some(hit) = write.get(&probe) {
        return hit.0;
    }
    let lowered: String = s.chars().map(|c| c.to_ascii_lowercase()).collect();
    let leaked: &'static str = Box::leak(lowered.into_boxed_str());
    write.insert(InternKey(leaked));
    leaked
}

impl UnknownHeaderName<'static> {
    /// Recover the underlying `&'static str` if this name is backed by a borrowed
    /// reference into static memory (a literal or an interned lowercased literal).
    /// Returns `None` for runtime-allocated names (`CompactCow::Owned`).
    pub(crate) fn as_static_str(&self) -> Option<&'static str> {
        match self.0 {
            CompactCow::Borrowed(s) => Some(s),
            CompactCow::Owned(_) | CompactCow::Shared(_) => None,
        }
    }

    /// Like [`Self::into_lower`], but for the uppercase-borrowed-static case it
    /// interns the lowercased form via [`intern_lowercase`] instead of allocating
    /// an Owned copy. The result is therefore *always* `CompactCow::Borrowed` (and
    /// hence `&'static str`-recoverable via [`as_static_str`]) when the input was
    /// `CompactCow::Borrowed`. `Owned` inputs fall back to the regular
    /// [`Self::into_lower`] path and are not interned.
    ///
    /// [`as_static_str`]: Self::as_static_str
    pub(crate) fn into_lower_static(self) -> Self {
        match self.0 {
            CompactCow::Borrowed(s) => {
                if s.bytes().any(|b| b.is_ascii_uppercase()) {
                    Self(CompactCow::Borrowed(intern_lowercase(s)))
                } else {
                    Self(CompactCow::Borrowed(s))
                }
            }
            CompactCow::Owned(_) | CompactCow::Shared(_) => self.into_lower(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ensure_interned(s: &'static str) -> &'static str {
        intern_lowercase(s)
    }

    #[test]
    fn interned_names_are_canonical_across_threads_and_addresses() {
        let here = ensure_interned("X-Thread-Front");
        let there = std::thread::spawn(|| ensure_interned("X-Thread-Front"))
            .join()
            .unwrap();
        let elsewhere = ensure_interned(String::from("X-THREAD-FRONT").leak());
        assert_eq!(here, "x-thread-front");
        assert_eq!(here.as_ptr(), there.as_ptr());
        assert_eq!(here.as_ptr(), elsewhere.as_ptr());
    }

    #[test]
    fn intern_idempotent() {
        let a = ensure_interned("X-Idempotent-Header");
        let b = ensure_interned("X-Idempotent-Header");
        assert_eq!(a, "x-idempotent-header");
        assert!(
            std::ptr::eq(a, b),
            "intern must return identical &'static str on repeat uppercase input",
        );
    }

    #[test]
    fn intern_lowercase_input_is_passthrough() {
        // Pure-lowercase input bypasses the intern table — caller's pointer is
        // returned directly.
        let original: &'static str = "x-already-lowercase";
        let got = ensure_interned(original);
        assert!(
            std::ptr::eq(got, original),
            "pure-lowercase literal should bypass interning entirely",
        );
    }

    #[test]
    fn intern_uppercase_then_lowercase_content_equal() {
        let upper = ensure_interned("X-Cross-Casing-Header");
        let lower = ensure_interned("x-cross-casing-header");
        assert_eq!(upper, lower);
        // Pointer identity may or may not hold depending on which call ran first.
    }

    #[test]
    fn intern_case_insensitive_hash_collapses_uppercase_variants() {
        // Two different uppercase castings of the same lowercased content must
        // intern to the same pointer.
        let a = ensure_interned("X-Mixed-Casing");
        let b = ensure_interned("x-MIXED-casing");
        assert!(
            std::ptr::eq(a, b),
            "case-insensitive hash must collapse uppercase variants",
        );
    }

    #[test]
    fn into_lower_static_borrowed_uppercase() {
        let n = UnknownHeaderName(CompactCow::Borrowed("X-Static-Upper")).into_lower_static();
        assert_eq!(n.as_static_str(), Some("x-static-upper"));
    }

    #[test]
    fn into_lower_static_borrowed_lowercase_passthrough() {
        let original: &'static str = "x-static-lower";
        let n = UnknownHeaderName(CompactCow::Borrowed(original)).into_lower_static();
        let got = n.as_static_str().unwrap();
        assert!(
            std::ptr::eq(got, original),
            "already-lowercase literal should pass through without interning",
        );
    }

    #[test]
    fn into_lower_static_owned_stays_owned() {
        let owned = UnknownHeaderName::from(String::from("X-Owned-Upper"));
        let lowered = owned.into_lower_static();
        assert_eq!(lowered.as_static_str(), None);
        assert_eq!(&*lowered, "x-owned-upper");
    }
}