rama-http 0.3.0-rc1

rama http layers, services and other utilities
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
//! Private (internal) implementation of the HTML rendering primitives.
//!
//! This module is a lightly simplified, permanent fork of
//! [`vy-core`](https://github.com/JonahLund/vy). The original `Either*`
//! types have been removed in favour of [`rama_core::combinators::Either`]
//! and friends (see [`super::either_impls`]). `no_std` support, `Cow`,
//! `IpAddr`, etc. impls have been dropped — we have full `std`/`alloc`
//! available and `rama-http` already provides richer ways of plugging in
//! arbitrary values.

#![expect(
    clippy::allow_attributes,
    reason = "vendored from `vy-core`: macro-internal `#[allow(non_snake_case)]` attrs whose underlying lint fires only for some tuple-arity expansions"
)]

use std::{
    borrow::Cow,
    fmt::{self, Write as _},
};

/// A type that can be rendered as a fragment of HTML.
///
/// This is the central trait of the HTML templating support. Built-in
/// scalars (e.g. `&str`, `String`, `bool`, integers, floats) all
/// implement it; new types can implement it either by returning a
/// composition of other [`IntoHtml`] values, or — for "leaf" types —
/// by overriding [`IntoHtml::escape_and_write`] directly.
///
/// # Examples
///
/// Compose nested HTML elements using macros:
///
/// ```ignore
/// use rama_http::protocols::html::*;
///
/// struct Article { title: String, content: String, author: String }
///
/// impl IntoHtml for Article {
///     fn into_html(self) -> impl IntoHtml {
///         article!(
///             h1!(self.title),
///             p!(class = "content", self.content),
///             footer!("Written by ", self.author),
///         )
///     }
/// }
/// ```
///
/// For leaf types, **return `self`** to terminate the rendering chain
/// and override [`IntoHtml::escape_and_write`]:
///
/// ```ignore
/// use rama_http::protocols::html::{IntoHtml, escape_into};
///
/// struct TextNode(String);
///
/// impl IntoHtml for TextNode {
///     fn into_html(self) -> impl IntoHtml { self }
///     fn escape_and_write(self, buf: &mut String) { escape_into(buf, &self.0); }
///     fn size_hint(&self) -> usize { self.0.len() }
/// }
/// ```
pub trait IntoHtml {
    /// Convert this value into another [`IntoHtml`] value. Used for
    /// composition; leaf types should return `self`.
    fn into_html(self) -> impl IntoHtml;

    /// Append the rendered (escaped) HTML to `buf`.
    #[inline]
    fn escape_and_write(self, buf: &mut String)
    where
        Self: Sized,
    {
        self.into_html().escape_and_write(buf);
    }

    /// Best-effort estimate of the rendered byte length, used to
    /// pre-allocate the output buffer.
    #[inline]
    fn size_hint(&self) -> usize {
        0
    }

    /// Render to a freshly allocated `String`.
    fn into_string(self) -> String
    where
        Self: Sized,
    {
        let html = self.into_html();
        let size = html.size_hint();
        let mut buf = String::with_capacity(size + (size / 10));
        html.escape_and_write(&mut buf);
        buf
    }
}

/// HTML-escape `input` into `output` (`&`, `<`, `>`, `"`, `'`).
///
/// Escaping `'` as `&#x27;` is required so that interpolating untrusted
/// strings into single-quoted attribute contexts (e.g. `<input value='…'>`)
/// is safe. `&apos;` is intentionally not used because it is not part of
/// HTML4 and some older agents do not recognize it.
#[inline]
pub fn escape_into(output: &mut String, input: &str) {
    let bytes = input.as_bytes();
    let mut start = 0;
    for (i, &b) in bytes.iter().enumerate() {
        let replacement = match b {
            b'&' => "&amp;",
            b'<' => "&lt;",
            b'>' => "&gt;",
            b'"' => "&quot;",
            b'\'' => "&#x27;",
            _ => continue,
        };
        // Every escapable is ASCII, so `i` is a char boundary.
        output.push_str(&input[start..i]);
        output.push_str(replacement);
        start = i + 1;
    }
    output.push_str(&input[start..]);
}

/// HTML-escape `value` into a byte buffer for a double-quoted attribute
/// context, where only `&` and `"` need escaping. Bulk-copies the runs
/// between escapables.
pub(crate) fn escape_attr_value_into(output: &mut Vec<u8>, value: &[u8]) {
    let mut start = 0;
    for (i, &b) in value.iter().enumerate() {
        let replacement: &[u8] = match b {
            b'&' => b"&amp;",
            b'"' => b"&quot;",
            _ => continue,
        };
        output.extend_from_slice(&value[start..i]);
        output.extend_from_slice(replacement);
        start = i + 1;
    }
    output.extend_from_slice(&value[start..]);
}

/// HTML-escape `input`, returning a [`Cow::Borrowed`] of the original
/// when nothing needs escaping — common in practice — and otherwise a
/// freshly allocated [`Cow::Owned`] with the escaped form.
#[inline]
pub fn escape(input: &str) -> Cow<'_, str> {
    // All escapables are ASCII, so a byte scan on UTF-8 is correct.
    if !input
        .bytes()
        .any(|b| matches!(b, b'&' | b'<' | b'>' | b'"' | b'\''))
    {
        return Cow::Borrowed(input);
    }
    let mut output = String::with_capacity(input.len() + 8);
    escape_into(&mut output, input);
    Cow::Owned(output)
}

/// The longest entity name (without `&`/`;`) we attempt to decode; bounds the
/// look-ahead for a terminating `;` so stray `&`s stay cheap.
const MAX_ENTITY_LEN: usize = 32;

/// Decode HTML character references in `input` — all numeric references
/// (`&#169;`, `&#xA9;`) plus the common named ones (`&amp;`, `&mdash;`, …).
///
/// Returns [`Cow::Borrowed`] when there is nothing to decode. Unknown or
/// malformed references are left verbatim. This is the companion to
/// [`escape`]/[`escape_into`] for consumers of the raw, undecoded text the
/// [`tokenizer`](super::tokenizer) emits.
#[must_use]
pub fn decode_entities(input: &str) -> Cow<'_, str> {
    let Some(first) = input.find('&') else {
        return Cow::Borrowed(input);
    };
    let mut out = String::with_capacity(input.len());
    out.push_str(&input[..first]);
    let mut rest = &input[first..];
    loop {
        // `rest` starts at an `&`.
        let after = &rest[1..];
        if let Some(semi) = after.find(';').filter(|&i| i <= MAX_ENTITY_LEN)
            && let Some(ch) = decode_entity(&after[..semi])
        {
            out.push(ch);
            rest = &after[semi + 1..];
        } else {
            out.push('&');
            rest = after;
        }
        let Some(next) = rest.find('&') else {
            out.push_str(rest);
            break;
        };
        out.push_str(&rest[..next]);
        rest = &rest[next..];
    }
    Cow::Owned(out)
}

/// Decode a single entity body (the bytes between `&` and `;`). `None` for an
/// unknown name or out-of-range numeric reference (left verbatim by the caller).
fn decode_entity(body: &str) -> Option<char> {
    if let Some(num) = body.strip_prefix('#') {
        let code = match num.strip_prefix(['x', 'X']) {
            Some(hex) => u32::from_str_radix(hex, 16).ok()?,
            None => num.parse::<u32>().ok()?,
        };
        return char::from_u32(code);
    }
    Some(match body {
        "amp" => '&',
        "lt" => '<',
        "gt" => '>',
        "quot" => '"',
        "apos" => '\'',
        "nbsp" => '\u{a0}',
        "hellip" => '',
        "mdash" => '',
        "ndash" => '',
        "lsquo" => '\u{2018}',
        "rsquo" => '\u{2019}',
        "ldquo" => '\u{201C}',
        "rdquo" => '\u{201D}',
        "laquo" => '«',
        "raquo" => '»',
        "copy" => '©',
        "reg" => '®',
        "trade" => '',
        "deg" => '°',
        "middot" | "bull" => '',
        "euro" => '',
        "pound" => '£',
        "cent" => '¢',
        "sect" => '§',
        "times" => '×',
        "divide" => '÷',
        _ => return None,
    })
}

/// Emit a `<?marker name="…">` processing instruction for use as a
/// placeholder in a [Chrome declarative partial updates] shell. The name is
/// HTML-escaped via [`escape_into`] on render.
///
/// [Chrome declarative partial updates]: https://developer.chrome.com/blog/declarative-partial-updates
#[inline]
pub fn marker<S: AsRef<str>>(name: S) -> Marker<S> {
    Marker(name)
}

/// Renderer for [`marker`]. Holds the name by-value and writes the PI
/// directly into the output buffer at render time.
#[derive(Debug, Clone, Copy)]
pub struct Marker<S>(pub S);

impl<S: AsRef<str>> IntoHtml for Marker<S> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(r#"<?marker name=""#);
        escape_into(buf, self.0.as_ref());
        buf.push_str(r#"">"#);
    }
    fn size_hint(&self) -> usize {
        // length of `<?marker name="">` + name; escape may grow it a bit.
        17 + self.0.as_ref().len()
    }
}

/// Emit a `<?start name="…">` processing instruction — the opening of the
/// *range* form of declarative partial updates. Whatever HTML sits between
/// `<?start name="x">` and the matching [`end`] (often a skeleton or
/// spinner) is replaced wholesale when the `<template for="x">` arrives, so
/// the placeholder content goes away on swap without any CSS bookkeeping.
/// The name is HTML-escaped via [`escape_into`] on render.
#[inline]
pub fn start<S: AsRef<str>>(name: S) -> Start<S> {
    Start(name)
}

/// Renderer for [`start`].
#[derive(Debug, Clone, Copy)]
pub struct Start<S>(pub S);

impl<S: AsRef<str>> IntoHtml for Start<S> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(r#"<?start name=""#);
        escape_into(buf, self.0.as_ref());
        buf.push_str(r#"">"#);
    }
    fn size_hint(&self) -> usize {
        // length of `<?start name="">` + name; escape may grow it a bit.
        16 + self.0.as_ref().len()
    }
}

/// Emit a `<?end>` processing instruction — the closing of a range opened
/// by [`start`]. Takes no name: `<?end>` always closes the most recent
/// unclosed `<?start>` at the same nesting level.
#[inline]
pub fn end() -> End {
    End
}

/// Renderer for [`end`].
#[derive(Debug, Clone, Copy)]
pub struct End;

impl IntoHtml for End {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(r#"<?end>"#);
    }
    fn size_hint(&self) -> usize {
        6 // length of `<?end>`
    }
}

/// Wrapper that marks its inner value as already-escaped HTML — i.e. it
/// will be written verbatim instead of going through [`escape_into`].
///
/// This is the type the macros emit for the static (literal) parts of a
/// template; users normally only construct it explicitly when they want
/// to splice trusted HTML into a template (e.g. an icon SVG).
#[derive(Debug, Clone, Copy)]
pub struct PreEscaped<T>(pub T);

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

impl IntoHtml for PreEscaped<&str> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(self.0);
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.0.len()
    }
}

impl IntoHtml for PreEscaped<String> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(&self.0);
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.0.len()
    }
}

impl IntoHtml for PreEscaped<char> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        buf.push(self.0);
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.0.len_utf8()
    }
}

impl IntoHtml for PreEscaped<Cow<'static, str>> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(&self.0);
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.0.len()
    }
}

impl IntoHtml for PreEscaped<Box<str>> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        buf.push_str(&self.0);
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.0.len()
    }
}

// ---- scalar / std impls ----------------------------------------------------

impl IntoHtml for &str {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, self)
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.len()
    }
}

impl IntoHtml for char {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, self.encode_utf8(&mut [0; 4]));
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.len_utf8()
    }
}

impl IntoHtml for String {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, &self)
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.len()
    }
}

impl IntoHtml for &String {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, self)
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.len()
    }
}

impl IntoHtml for Box<str> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, &self)
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.len()
    }
}

impl IntoHtml for Cow<'static, str> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        escape_into(buf, self.as_ref())
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.as_ref().len()
    }
}

impl IntoHtml for bool {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        if self { "true" } else { "false" }
    }
    #[inline]
    fn size_hint(&self) -> usize {
        5
    }
}

impl<T: IntoHtml> IntoHtml for Option<T> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        if let Some(x) = self {
            x.escape_and_write(buf)
        }
    }
    #[inline]
    fn size_hint(&self) -> usize {
        match self {
            Some(x) => x.size_hint(),
            None => 0,
        }
    }
}

impl IntoHtml for () {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, _: &mut String) {}
}

impl<F: FnOnce(&mut String)> IntoHtml for F {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        (self)(buf)
    }
}

impl<B: IntoHtml, I: ExactSizeIterator, F> IntoHtml for std::iter::Map<I, F>
where
    F: FnMut(I::Item) -> B,
{
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        let len = self.len();
        for (i, x) in self.enumerate() {
            if i == 0 {
                buf.reserve(len * x.size_hint());
            }
            x.escape_and_write(buf);
        }
    }
}

impl<T: IntoHtml> IntoHtml for Vec<T> {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        for x in self {
            x.escape_and_write(buf);
        }
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.iter().map(IntoHtml::size_hint).sum()
    }
}

impl<T: IntoHtml, const N: usize> IntoHtml for [T; N] {
    #[inline]
    fn into_html(self) -> impl IntoHtml {
        self
    }
    #[inline]
    fn escape_and_write(self, buf: &mut String) {
        for x in self {
            x.escape_and_write(buf);
        }
    }
    #[inline]
    fn size_hint(&self) -> usize {
        self.iter().map(IntoHtml::size_hint).sum()
    }
}

// ---- tuples ----------------------------------------------------------------

macro_rules! impl_tuple {
    ( ( $($i:ident,)+ ) ) => {
        impl<$($i,)+> IntoHtml for ($($i,)+)
        where
            $($i: IntoHtml,)+
        {
            #[inline]
            fn into_html(self) -> impl IntoHtml {
                #[allow(non_snake_case)]
                let ($($i,)+) = self;
                ($($i.into_html(),)+)
            }

            #[inline]
            fn escape_and_write(self, buf: &mut String) {
                #[allow(non_snake_case)]
                let ($($i,)+) = self;
                $( $i.escape_and_write(buf); )+
            }

            #[inline]
            fn size_hint(&self) -> usize {
                #[allow(non_snake_case)]
                let ($($i,)+) = self;
                let mut n = 0;
                $( n += $i.size_hint(); )+
                n
            }
        }
    };
    ($f:ident) => {
        impl_tuple!(($f,));
    };
    ($f:ident $($i:ident)+) => {
        impl_tuple!(($f, $($i,)+));
        impl_tuple!($($i)+);
    };
}

impl_tuple!(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A_ B_ C_ D_ E_ F_ G_ H_ I_ J_ K_);

// ---- numbers ---------------------------------------------------------------

// Numeric impls. None of `Display` for these types can produce a character
// that needs HTML-escaping, so we write directly into `buf`.
macro_rules! via_display {
    ($($ty:ty)*) => {
        $(
            impl IntoHtml for $ty {
                #[inline]
                fn into_html(self) -> impl IntoHtml { self }
                #[inline]
                fn escape_and_write(self, buf: &mut String) {
                    _ = write!(buf, "{self}");
                }
            }
        )*
    };
}

via_display! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 f32 f64 }