topcoat-view 0.6.0

A modular, batteries-included Rust web framework for server-rendered apps.
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
use core::fmt;

#[cfg(feature = "http")]
use http::{HeaderMap, StatusCode};
use topcoat_core::context::Cx;

use crate::{HtmlContext, HtmlWriter, View, buffer::ViewBuffer};

/// A boxed view part that writes its output at render time.
///
/// Implement this for values whose output is only known when the view
/// renders, such as resolved asset URLs. The writer passed to
/// [`render`](Self::render) already carries the [`HtmlContext`] of the
/// position the part was pushed into, so everything written through it is
/// escaped or validated for that position.
pub trait DynViewPart: 'static + fmt::Debug + Send + Sync {
    /// Writes this part's output into `w`.
    #[track_caller]
    fn render(&self, cx: &Cx, w: &mut HtmlWriter<'_, '_>);

    /// Returns an estimate of the number of bytes this part will write.
    ///
    /// Used to pre-allocate the output buffer, so aim for a close estimate. A
    /// slight over-estimate is usually preferable to an under-estimate.
    #[inline]
    fn size_hint(&self) -> usize {
        0
    }
}

macro_rules! impl_push_primitive {
    ($method:ident, $ty:ty, $size_hint:expr) => {
        #[doc = concat!("Appends a `", stringify!($ty), "` rendered as text.")]
        ///
        /// Its rendered form contains no character that is significant in any
        /// HTML context, so no escaping applies.
        #[inline]
        pub fn $method(&mut self, value: $ty) -> &mut Self {
            self.size_hint += $size_hint;
            self.buffer.$method(value);
            self
        }
    };
}

/// A context-carrying writer over an instruction buffer, created per
/// position.
///
/// The `view!` macro creates a `PartsWriter` for each dynamic position it
/// fills and hands it to the matching position trait:
/// [`NodeViewParts`](crate::NodeViewParts),
/// [`AttributeValueViewParts`](crate::AttributeValueViewParts),
/// [`AttributeKeyViewParts`](crate::AttributeKeyViewParts),
/// [`ElementNameViewParts`](crate::ElementNameViewParts), or
/// [`AttributeViewParts`](crate::AttributeViewParts).
///
/// Implementations of those traits make a value renderable by pushing it
/// through the `push_*` methods, which seal the pushed text with the
/// [`HtmlContext`] of the position so rendering escapes or validates it
/// correctly, or by delegating to another implementation of the same
/// position trait. The `push_*_unescaped` methods are the only way to opt
/// out of that protection.
///
/// The writer also accumulates a size hint: an estimate of the number of
/// bytes everything pushed so far will write when rendered. The estimate
/// becomes the built view's size hint, which pre-allocates the output buffer
/// at render time.
pub struct PartsWriter<'a> {
    buffer: &'a mut ViewBuffer,
    context: HtmlContext,
    size_hint: usize,
}

impl<'a> PartsWriter<'a> {
    /// Creates a writer that seals everything pushed into it with `context`.
    #[inline]
    fn new(buffer: &'a mut ViewBuffer, context: HtmlContext) -> Self {
        Self {
            buffer,
            context,
            size_hint: 0,
        }
    }

    /// Appends one view's instruction block to `buffer`, filled by `f`
    /// through a writer in text context.
    ///
    /// Records the entry address, runs `f`, and terminates the block with a
    /// return instruction. Returns the handle to the block, carrying the
    /// writer's accumulated size hint.
    pub(crate) fn block(buffer: &mut ViewBuffer, f: impl FnOnce(&mut PartsWriter<'_>)) -> View {
        let entry = buffer.next_ptr();
        let mut parts = PartsWriter::new(buffer, HtmlContext::Text);
        f(&mut parts);
        let size_hint = parts.size_hint();
        buffer.push_ret();
        View::from_scope(buffer.id(), entry, size_hint)
    }

    /// Returns the accumulated size hint of everything pushed so far.
    #[inline]
    pub(crate) fn size_hint(&self) -> usize {
        self.size_hint
    }

    /// Runs `f` with this writer sealing for a different context, then
    /// restores the current context.
    ///
    /// In-crate compositions that span more than one position use this to
    /// transition between the positions they cover, such as
    /// [`Attribute`](crate::Attribute) moving from a key to a value or
    /// [`push_comment`](Self::push_comment) sealing a comment body.
    #[inline]
    pub(crate) fn in_context<R>(
        &mut self,
        context: HtmlContext,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let previous = std::mem::replace(&mut self.context, context);
        let result = f(self);
        self.context = previous;
        result
    }

    /// Estimates the bytes `value` writes when rendered in `context`.
    fn str_size_hint(value: &str, context: HtmlContext) -> usize {
        match context {
            HtmlContext::Unescaped => value.len(),
            // Assume some characters escape into multi-byte sequences.
            _ => value.len() + value.len() / 8,
        }
    }

    /// Appends a borrowed string, sealed with this writer's context.
    #[inline]
    pub fn push_str(&mut self, value: &str) -> &mut Self {
        self.size_hint += Self::str_size_hint(value, self.context);
        self.buffer.push_str(value, self.context);
        self
    }

    /// Appends a static string, sealed with this writer's context.
    #[inline]
    pub fn push_static_str(&mut self, value: &'static str) -> &mut Self {
        self.size_hint += Self::str_size_hint(value, self.context);
        self.buffer.push_static_str(value, self.context);
        self
    }

    /// Appends a static string held by reference, sealed with this writer's
    /// context.
    ///
    /// Pass `&"..."`, which Rust promotes to a reference into the binary's
    /// read-only data. The string stays out of the buffer's constants, so
    /// prefer this over [`push_static_str`](Self::push_static_str) whenever
    /// the string is written as a literal.
    #[inline]
    pub fn push_promoted_str(&mut self, value: &'static &'static str) -> &mut Self {
        self.size_hint += Self::str_size_hint(value, self.context);
        self.buffer.push_promoted_str(value, self.context);
        self
    }

    /// Appends an owned string, sealed with this writer's context.
    #[inline]
    pub fn push_string(&mut self, value: String) -> &mut Self {
        self.size_hint += Self::str_size_hint(&value, self.context);
        self.buffer.push_string(value, self.context);
        self
    }

    /// Appends a borrowed string that renders verbatim, bypassing this
    /// writer's context.
    ///
    /// Use this only for trusted markup. Passing untrusted input defeats the
    /// runtime's escaping and can lead to XSS vulnerabilities.
    #[inline]
    pub fn push_str_unescaped(&mut self, value: &str) -> &mut Self {
        self.size_hint += value.len();
        self.buffer.push_str(value, HtmlContext::Unescaped);
        self
    }

    /// Appends a static string that renders verbatim, bypassing this
    /// writer's context.
    ///
    /// Use this only for trusted markup. Passing untrusted input defeats the
    /// runtime's escaping and can lead to XSS vulnerabilities.
    #[inline]
    pub fn push_static_str_unescaped(&mut self, value: &'static str) -> &mut Self {
        self.size_hint += value.len();
        self.buffer.push_static_str(value, HtmlContext::Unescaped);
        self
    }

    /// Appends a static string held by reference that renders verbatim,
    /// bypassing this writer's context.
    ///
    /// Pass `&"..."`, which Rust promotes to a reference into the binary's
    /// read-only data. The string stays out of the buffer's constants, so
    /// prefer this over
    /// [`push_static_str_unescaped`](Self::push_static_str_unescaped)
    /// whenever the string is written as a literal.
    ///
    /// Use this only for trusted markup. Passing untrusted input defeats the
    /// runtime's escaping and can lead to XSS vulnerabilities.
    #[inline]
    pub fn push_promoted_str_unescaped(&mut self, value: &'static &'static str) -> &mut Self {
        self.size_hint += value.len();
        self.buffer.push_promoted_str(value, HtmlContext::Unescaped);
        self
    }

    /// Appends an owned string that renders verbatim, bypassing this
    /// writer's context.
    ///
    /// Use this only for trusted markup. Passing untrusted input defeats the
    /// runtime's escaping and can lead to XSS vulnerabilities.
    #[inline]
    pub fn push_string_unescaped(&mut self, value: String) -> &mut Self {
        self.size_hint += value.len();
        self.buffer.push_string(value, HtmlContext::Unescaped);
        self
    }

    /// Appends an HTML comment whose body is built through `build`.
    ///
    /// The `<!-- ` and ` -->` delimiters are written verbatim, while the
    /// writer handed to `build` seals everything pushed into it for the
    /// [`Comment`](HtmlContext::Comment) context. Because that context
    /// escapes `>`, the body can never contain `-->` and terminate the
    /// comment, so a marker can be built from untrusted data with
    /// [`push_str`](Self::push_str) and no separate escaping step.
    ///
    /// # Panics
    ///
    /// Panics if used in a non-text HTML context.
    #[inline]
    pub fn push_comment(&mut self, build: impl FnOnce(&mut PartsWriter<'_>)) -> &mut Self {
        assert!(
            self.context == HtmlContext::Text,
            "tried to push comment in html context {:?}",
            self.context,
        );
        self.push_promoted_str_unescaped(&"<!-- ");
        self.in_context(HtmlContext::Comment, build);
        self.push_promoted_str_unescaped(&" -->");
        self
    }

    /// Appends a character, sealed with this writer's context.
    #[inline]
    pub fn push_char(&mut self, value: char) -> &mut Self {
        // One to four UTF-8 bytes, or an escape sequence.
        self.size_hint += 3;
        self.buffer.push_char(value, self.context);
        self
    }

    // Each numeric size hint is the midpoint, rounded up, between the
    // shortest and widest output the type can render, including the leading
    // `-` for signed types (`isize`/`usize` assume a 64-bit target). A
    // float's rendered width is unbounded for extreme magnitudes, so the
    // upper end is the shortest round-trip form of a typical value.

    impl_push_primitive!(push_bool, bool, 5);
    impl_push_primitive!(push_i8, i8, 3);
    impl_push_primitive!(push_i16, i16, 4);
    impl_push_primitive!(push_i32, i32, 6);
    impl_push_primitive!(push_i64, i64, 11);
    impl_push_primitive!(push_i128, i128, 21);
    impl_push_primitive!(push_isize, isize, 11);
    impl_push_primitive!(push_u8, u8, 2);
    impl_push_primitive!(push_u16, u16, 3);
    impl_push_primitive!(push_u32, u32, 6);
    impl_push_primitive!(push_u64, u64, 11);
    impl_push_primitive!(push_u128, u128, 20);
    impl_push_primitive!(push_usize, usize, 11);
    impl_push_primitive!(push_f32, f32, 9);
    impl_push_primitive!(push_f64, f64, 13);

    /// Appends a part that writes its output at render time, sealed with
    /// this writer's context.
    #[inline]
    pub fn push_dyn(&mut self, part: Box<dyn DynViewPart>) -> &mut Self {
        self.size_hint += part.size_hint();
        self.buffer.push_dyn(part, self.context);
        self
    }

    /// Appends a nested view.
    ///
    /// The view's content was already sealed with the contexts it was built
    /// for; this writer's context does not apply. The view's size hint joins
    /// this writer's, so a view spliced twice counts its output twice.
    ///
    /// # Panics
    ///
    /// Panics if the view was built in a different, still building buffer.
    #[inline]
    pub(crate) fn push_view(&mut self, view: View) -> &mut Self {
        self.size_hint += view.size_hint();
        self.buffer.push_view(view);
        self
    }

    /// Records a response status code; renders no content.
    #[cfg(feature = "http")]
    #[inline]
    pub fn push_status_code(&mut self, status_code: StatusCode) -> &mut Self {
        self.buffer.push_status_code(status_code);
        self
    }

    /// Records response headers; renders no content.
    #[cfg(feature = "http")]
    #[inline]
    pub fn push_headers(&mut self, headers: HeaderMap) -> &mut Self {
        self.buffer.push_headers(headers);
        self
    }
}

#[cfg(test)]
mod tests {
    use std::{
        future::Future,
        pin::pin,
        task::{Context, Poll, Waker},
    };

    use super::*;
    use crate::{
        buffer::ViewBufferScope,
        internal::{build_sync, write_block},
    };

    /// Drives `fut` to completion on the current thread.
    ///
    /// The futures under test never wait on external events, so polling in a
    /// tight loop is sufficient.
    fn block_on<F: Future>(fut: F) -> F::Output {
        let mut fut = pin!(fut);
        let mut task = Context::from_waker(Waker::noop());
        loop {
            if let Poll::Ready(output) = fut.as_mut().poll(&mut task) {
                return output;
            }
        }
    }

    /// Runs `f` with a request context inside a fresh view scope.
    fn in_scope<R>(f: impl AsyncFnOnce(&Cx) -> R) -> R {
        block_on(ViewBufferScope::scope(async { f(&Cx::default()).await })).0
    }

    /// Builds a view inside a fresh scope through a writer sealed with
    /// `context` and renders it.
    fn render_with(context: HtmlContext, f: impl FnOnce(&mut PartsWriter<'_>)) -> String {
        in_scope(async |cx| {
            build_sync(|| write_block(|parts| parts.in_context(context, f))).render(cx)
        })
    }

    #[test]
    fn push_str_seals_the_writer_context() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_str("<b> & \"q\"");
        });
        assert_eq!(out, "&lt;b&gt; &amp; \"q\"");

        let out = render_with(HtmlContext::AttributeValue, |w| {
            w.push_str("<b> & \"q\"");
        });
        assert_eq!(out, "<b> &amp; &quot;q&quot;");
    }

    #[test]
    fn push_str_unescaped_bypasses_the_context() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_str_unescaped("<b>raw</b>");
        });
        assert_eq!(out, "<b>raw</b>");
    }

    #[test]
    fn push_promoted_str_seals_the_writer_context() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_promoted_str(&"<b> & \"q\"");
        });
        assert_eq!(out, "&lt;b&gt; &amp; \"q\"");

        let out = render_with(HtmlContext::AttributeValue, |w| {
            w.push_promoted_str(&"<b> & \"q\"");
        });
        assert_eq!(out, "<b> &amp; &quot;q&quot;");
    }

    #[test]
    fn push_promoted_str_unescaped_bypasses_the_context() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_promoted_str_unescaped(&"<b>raw</b>");
        });
        assert_eq!(out, "<b>raw</b>");
    }

    #[test]
    fn push_promoted_str_skips_empty_strings() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_promoted_str(&"a").push_promoted_str(&"");
            w.push_promoted_str_unescaped(&"").push_promoted_str(&"b");
        });
        assert_eq!(out, "ab");
    }

    #[test]
    fn push_char_seals_the_writer_context() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_char('<');
        });
        assert_eq!(out, "&lt;");
    }

    #[test]
    #[should_panic(expected = "invalid attribute key")]
    fn ident_context_panics_on_forbidden_characters_at_render() {
        render_with(HtmlContext::AttributeKey, |w| {
            w.push_str("on click");
        });
    }

    #[test]
    fn push_primitives_render_as_text() {
        let out = render_with(HtmlContext::Text, |w| {
            w.push_i32(-42).push_str_unescaped(" ");
            w.push_bool(true).push_str_unescaped(" ");
            w.push_f64(1.5).push_str_unescaped(" ");
            w.push_i128(-1 << 100).push_str_unescaped(" ");
            w.push_u128(1 << 100);
        });
        assert_eq!(
            out,
            "-42 true 1.5 -1267650600228229401496703205376 1267650600228229401496703205376"
        );
    }
}