oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
use std::{collections::HashSet, fmt, fmt::Write as _, ops};

use super::html::decode_utf8;

/// Options accepted by PHP's `json_encode`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct JsonFlags(u32);

impl JsonFlags {
    /// Escape angle brackets.
    pub const HEX_TAG: Self = Self(1);
    /// Escape ampersands.
    pub const HEX_AMP: Self = Self(2);
    /// Escape apostrophes.
    pub const HEX_APOS: Self = Self(4);
    /// Escape double quotes as Unicode escapes.
    pub const HEX_QUOT: Self = Self(8);
    /// Encode arrays as objects.
    pub const FORCE_OBJECT: Self = Self(16);
    /// Convert numeric string values to numbers.
    pub const NUMERIC_CHECK: Self = Self(32);
    /// Indent containers with four spaces.
    pub const PRETTY_PRINT: Self = Self(128);
    /// Leave forward slashes unescaped.
    pub const UNESCAPED_SLASHES: Self = Self(64);
    /// Leave non-ASCII text unescaped.
    pub const UNESCAPED_UNICODE: Self = Self(256);
    /// Substitute invalid values and encode past the requested depth.
    pub const PARTIAL_OUTPUT_ON_ERROR: Self = Self(512);
    /// Keep a fractional part when serializing an integral float.
    pub const PRESERVE_ZERO_FRACTION: Self = Self(1024);
    /// Leave U+2028 and U+2029 unescaped with `UNESCAPED_UNICODE`.
    pub const UNESCAPED_LINE_TERMINATORS: Self = Self(2048);
    /// Drop malformed UTF-8 sequences.
    pub const INVALID_UTF8_IGNORE: Self = Self(1 << 20);
    /// Replace malformed UTF-8 sequences with U+FFFD.
    pub const INVALID_UTF8_SUBSTITUTE: Self = Self(1 << 21);
    /// Request PHP's exception mode. Rust reports encoding errors through `Result`.
    pub const THROW_ON_ERROR: Self = Self(1 << 22);
    /// Blade's default `@json` flags, replaced by an explicit flag list.
    pub const BLADE_DEFAULT: Self = Self(15);

    /// Look up the snake_case flag name used in oxblade templates.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "hex_tag" => Self::HEX_TAG,
            "hex_amp" => Self::HEX_AMP,
            "hex_apos" => Self::HEX_APOS,
            "hex_quot" => Self::HEX_QUOT,
            "force_object" => Self::FORCE_OBJECT,
            "numeric_check" => Self::NUMERIC_CHECK,
            "pretty_print" => Self::PRETTY_PRINT,
            "unescaped_slashes" => Self::UNESCAPED_SLASHES,
            "unescaped_unicode" => Self::UNESCAPED_UNICODE,
            "partial_output_on_error" => Self::PARTIAL_OUTPUT_ON_ERROR,
            "preserve_zero_fraction" => Self::PRESERVE_ZERO_FRACTION,
            "unescaped_line_terminators" => Self::UNESCAPED_LINE_TERMINATORS,
            "invalid_utf8_ignore" => Self::INVALID_UTF8_IGNORE,
            "invalid_utf8_substitute" => Self::INVALID_UTF8_SUBSTITUTE,
            "throw_on_error" => Self::THROW_ON_ERROR,
            _ => return None,
        })
    }

    /// Check whether all the given flags are present.
    pub fn contains(self, flags: Self) -> bool {
        self.0 & flags.0 == flags.0
    }

    /// Combine the flags in a template flag list, returning the first unknown name as an error.
    pub fn from_names<'a>(names: impl IntoIterator<Item = &'a str>) -> Result<Self, &'a str> {
        names.into_iter().try_fold(Self::default(), |flags, name| {
            Self::from_name(name).map(|flag| flags | flag).ok_or(name)
        })
    }
}

impl ops::BitOr for JsonFlags {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

/// A key in an insertion-ordered PHP array or JSON object.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArrayKey<'a> {
    /// A signed integer key.
    Integer(i64),
    /// A string key as UTF-8 bytes.
    String(&'a [u8]),
}

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

/// An iterator in the order keys were inserted.
pub type Entries<'a> = Box<dyn Iterator<Item = (ArrayKey<'a>, &'a dyn JsonValue)> + 'a>;

/// A borrowed view of a value that the encoders can consume.
#[non_exhaustive]
pub enum JsonKind<'a> {
    /// The null value.
    Null,
    /// A Boolean value.
    Bool(bool),
    /// A signed PHP integer.
    Integer(i64),
    /// A JSON integer above the signed 64-bit range.
    Unsigned(u64),
    /// A double-precision PHP float.
    Float(f64),
    /// A string as UTF-8 bytes.
    String(&'a [u8]),
    /// An ordered array. Contiguous integer keys starting at zero produce a JSON list.
    Array(Entries<'a>),
    /// An ordered object with the public members to encode, always as a JSON object.
    Object(Entries<'a>),
}

/// Provide a value to Blade's encoders without converting ordered PHP keys to JSON strings.
pub trait JsonValue {
    /// Borrow the value's encoding representation.
    fn json_kind(&self) -> JsonKind<'_>;
}

impl JsonValue for serde_json::Value {
    fn json_kind(&self) -> JsonKind<'_> {
        match self {
            Self::Null => JsonKind::Null,
            Self::Bool(value) => JsonKind::Bool(*value),
            Self::Number(value) => {
                if let Some(integer) = value.as_i64() {
                    JsonKind::Integer(integer)
                } else if let Some(integer) = value.as_u64() {
                    JsonKind::Unsigned(integer)
                } else {
                    JsonKind::Float(value.as_f64().unwrap_or(f64::INFINITY))
                }
            }
            Self::String(value) => JsonKind::String(value.as_bytes()),
            Self::Array(values) => {
                JsonKind::Array(Box::new(values.iter().zip(0..).map(|(value, index)| {
                    (ArrayKey::Integer(index), value as &dyn JsonValue)
                })))
            }
            Self::Object(values) => {
                JsonKind::Object(Box::new(values.iter().map(|(key, value)| {
                    (ArrayKey::from(key.as_str()), value as &dyn JsonValue)
                })))
            }
        }
    }
}

/// An encoding failure reported by PHP's JSON encoder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncodeError {
    /// A container exceeds the requested depth.
    Depth,
    /// A string or key contains invalid UTF-8.
    InvalidUtf8,
    /// A float is NaN or infinite.
    NonFiniteFloat,
    /// A container recursively references itself.
    Recursion,
    /// Encoding would exceed the available output bytes.
    OutputLimit,
    /// Encoding would expand too many collection entries.
    ExpansionLimit,
}

impl fmt::Display for EncodeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Depth => "Maximum stack depth exceeded",
            Self::InvalidUtf8 => "Malformed UTF-8 characters, possibly incorrectly encoded",
            Self::NonFiniteFloat => "Inf and NaN cannot be JSON encoded",
            Self::Recursion => "Recursion detected",
            Self::OutputLimit => "render output limit exceeded during JSON encoding",
            Self::ExpansionLimit => "collection expansion limit exceeded during JSON encoding",
        })
    }
}

impl std::error::Error for EncodeError {}

/// Encode a value as Blade's `@json`. Omit flags and depth for the Blade defaults.
///
/// Encoding failures return an error so the caller can attach template context. PHP's
/// non-throwing `@json` prints an empty string on failure.
pub fn json(
    value: &dyn JsonValue,
    flags: Option<JsonFlags>,
    depth: Option<i32>,
) -> Result<String, EncodeError> {
    encode_json(value, flags, depth, EncodingLimits::UNBOUNDED).map(|(text, _)| text)
}

/// Encode a value as Laravel's `Js::from` (Blade's `@js`).
///
/// Caller flags augment Laravel's required flags. Strings use single quotes, and
/// nonempty arrays and objects use `JSON.parse('…')`.
pub fn js(
    value: &dyn JsonValue,
    flags: JsonFlags,
    depth: Option<i32>,
) -> Result<String, EncodeError> {
    encode_js(value, flags, depth, EncodingLimits::UNBOUNDED).map(|(text, _)| text)
}

#[derive(Clone, Copy)]
pub(crate) struct EncodingLimits {
    pub(crate) output: usize,
    pub(crate) expansion: usize,
}

impl EncodingLimits {
    const UNBOUNDED: Self = Self {
        output: usize::MAX,
        expansion: usize::MAX,
    };
}

pub(crate) fn encode_json(
    value: &dyn JsonValue,
    flags: Option<JsonFlags>,
    depth: Option<i32>,
    limits: EncodingLimits,
) -> Result<(String, usize), EncodeError> {
    let flags = flags.unwrap_or(JsonFlags::BLADE_DEFAULT);
    let mut encoder = Encoder::new(flags, depth, limits);
    encoder.value(value, value.json_kind())?;
    Ok((
        encoder.output.text,
        limits.expansion - encoder.remaining_entries,
    ))
}

pub(crate) fn encode_js(
    value: &dyn JsonValue,
    flags: JsonFlags,
    depth: Option<i32>,
    limits: EncodingLimits,
) -> Result<(String, usize), EncodeError> {
    let required =
        flags | JsonFlags::BLADE_DEFAULT | JsonFlags::UNESCAPED_UNICODE | JsonFlags::THROW_ON_ERROR;
    let mut encoder = Encoder::new(required | JsonFlags::INVALID_UTF8_SUBSTITUTE, depth, limits);
    let kind = value.json_kind();
    let is_string = matches!(kind, JsonKind::String(_));
    if is_string && flags.contains(JsonFlags::NUMERIC_CHECK) {
        // Laravel drops the two outside bytes after numeric conversion.
        encoder.output.limit = limits.output.saturating_add(2);
    }
    encoder.value(value, kind)?;
    let encoded = encoder.output.text;
    let entries = limits.expansion - encoder.remaining_entries;
    let mut output = Sink::new(limits.output);
    if is_string {
        let end = encoded.len().saturating_sub(1);
        let contents = encoded.get(1..end).unwrap_or_default();
        output.push('\'')?;
        output.push_str(contents)?;
        output.push('\'')?;
    } else if encoded != "[]" && encoded != "{}" && encoded.starts_with(['"', '{', '[']) {
        output.push_str("JSON.parse('")?;
        write_string(&mut output, &encoded, required, false)?;
        output.push_str("')")?;
    } else {
        return Ok((encoded, entries));
    }
    Ok((output.text, entries))
}

struct Sink {
    text: String,
    limit: usize,
}

impl Sink {
    fn new(limit: usize) -> Self {
        Self {
            text: String::new(),
            limit,
        }
    }

    fn remaining(&self) -> usize {
        self.limit - self.text.len()
    }

    fn push_str(&mut self, text: &str) -> Result<(), EncodeError> {
        if text.len() > self.remaining() {
            return Err(EncodeError::OutputLimit);
        }
        self.text.push_str(text);
        Ok(())
    }

    fn push(&mut self, ch: char) -> Result<(), EncodeError> {
        self.push_str(ch.encode_utf8(&mut [0; 4]))
    }

    fn formatted(&mut self, args: fmt::Arguments<'_>) -> Result<(), EncodeError> {
        self.write_fmt(args).map_err(|_| EncodeError::OutputLimit)
    }
}

impl fmt::Write for Sink {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        self.push_str(text).map_err(|_| fmt::Error)
    }
}

struct Encoder {
    flags: JsonFlags,
    max_depth: usize,
    remaining_entries: usize,
    output: Sink,
}

struct Container<'a> {
    entries: Entries<'a>,
    list: bool,
    first: bool,
    entries_reserved: bool,
}

impl Encoder {
    fn new(flags: JsonFlags, depth: Option<i32>, limits: EncodingLimits) -> Self {
        Self {
            flags,
            max_depth: depth.unwrap_or(512).try_into().unwrap_or(0),
            remaining_entries: limits.expansion,
            output: Sink::new(limits.output),
        }
    }

    fn charge_entry(&mut self) -> Result<(), EncodeError> {
        self.remaining_entries = self
            .remaining_entries
            .checked_sub(1)
            .ok_or(EncodeError::ExpansionLimit)?;
        Ok(())
    }

    fn array<'a>(&mut self, entries: Entries<'a>) -> Result<Container<'a>, EncodeError> {
        if self.flags.contains(JsonFlags::FORCE_OBJECT) {
            return Ok(Container {
                entries,
                list: false,
                first: true,
                entries_reserved: false,
            });
        }
        let mut items = Vec::new();
        let mut list = true;
        for (key, value) in entries {
            self.charge_entry()?;
            // Even the shortest JSON representation needs a byte per entry.
            if items.len() >= self.output.remaining() {
                return Err(EncodeError::OutputLimit);
            }
            list &= key == ArrayKey::Integer(items.len() as i64);
            items.push((key, value));
        }
        Ok(Container {
            entries: Box::new(items.into_iter()),
            list,
            first: true,
            entries_reserved: true,
        })
    }

    fn value<'a>(
        &mut self,
        value: &'a dyn JsonValue,
        kind: JsonKind<'a>,
    ) -> Result<(), EncodeError> {
        let Some(container) = self.write_value(kind, 0)? else {
            return Ok(());
        };
        let root = std::ptr::from_ref(value);
        let mut ancestors = HashSet::from([root]);
        let mut containers = vec![(root, container)];
        while let Some(depth) = containers.len().checked_sub(1) {
            let (origin, frame) = &mut containers[depth];
            if let Some((key, value)) = frame.entries.next() {
                if !frame.entries_reserved {
                    self.charge_entry()?;
                }
                if !frame.first {
                    self.output.push(',')?;
                }
                frame.first = false;
                self.indent(depth + 1)?;
                if !frame.list {
                    match key {
                        ArrayKey::Integer(key) => {
                            self.output.formatted(format_args!("\"{key}\""))?;
                        }
                        ArrayKey::String(key) => self.string(key, true)?,
                    }
                    self.output.push(':')?;
                    if self.flags.contains(JsonFlags::PRETTY_PRINT) {
                        self.output.push(' ')?;
                    }
                }
                let origin = std::ptr::from_ref(value);
                if ancestors.contains(&origin) {
                    if !self.flags.contains(JsonFlags::PARTIAL_OUTPUT_ON_ERROR) {
                        return Err(EncodeError::Recursion);
                    }
                    self.output.push_str("null")?;
                } else if let Some(container) = self.write_value(value.json_kind(), depth + 1)? {
                    ancestors.insert(origin);
                    containers.push((origin, container));
                }
            } else {
                if !frame.first {
                    self.indent(depth)?;
                }
                self.output.push(if frame.list { ']' } else { '}' })?;
                ancestors.remove(origin);
                containers.pop();
            }
        }
        Ok(())
    }

    fn write_value<'a>(
        &mut self,
        kind: JsonKind<'a>,
        depth: usize,
    ) -> Result<Option<Container<'a>>, EncodeError> {
        if matches!(kind, JsonKind::Array(_) | JsonKind::Object(_))
            && depth >= self.max_depth
            && !self.flags.contains(JsonFlags::PARTIAL_OUTPUT_ON_ERROR)
        {
            return Err(EncodeError::Depth);
        }
        let container = match kind {
            JsonKind::Null => {
                self.output.push_str("null")?;
                return Ok(None);
            }
            JsonKind::Bool(value) => {
                self.output.push_str(if value { "true" } else { "false" })?;
                return Ok(None);
            }
            JsonKind::Integer(value) => {
                self.output.formatted(format_args!("{value}"))?;
                return Ok(None);
            }
            JsonKind::Unsigned(value) => {
                self.output.formatted(format_args!("{value}"))?;
                return Ok(None);
            }
            JsonKind::Float(value) => return self.float(value).map(|()| None),
            JsonKind::String(value) => return self.string(value, false).map(|()| None),
            JsonKind::Array(entries) => self.array(entries)?,
            JsonKind::Object(entries) => Container {
                list: false,
                first: true,
                entries,
                entries_reserved: false,
            },
        };
        self.output.push(if container.list { '[' } else { '{' })?;
        Ok(Some(container))
    }

    fn indent(&mut self, depth: usize) -> Result<(), EncodeError> {
        if self.flags.contains(JsonFlags::PRETTY_PRINT) {
            self.output.push('\n')?;
            for _ in 0..depth {
                self.output.push_str("    ")?;
            }
        }
        Ok(())
    }

    fn string(&mut self, input: &[u8], key: bool) -> Result<(), EncodeError> {
        let replacement = if self.flags.contains(JsonFlags::INVALID_UTF8_IGNORE) {
            Some('\0')
        } else if self.flags.contains(JsonFlags::INVALID_UTF8_SUBSTITUTE) {
            Some('\u{fffd}')
        } else {
            None
        };
        if (key || !self.flags.contains(JsonFlags::NUMERIC_CHECK))
            && !self.flags.contains(JsonFlags::PARTIAL_OUTPUT_ON_ERROR)
            && replacement != Some('\0')
            && input.len() / 4 > self.output.remaining()
        {
            return Err(EncodeError::OutputLimit);
        }
        let Some(text) = decode_utf8(input, replacement) else {
            if self.flags.contains(JsonFlags::PARTIAL_OUTPUT_ON_ERROR) {
                self.output.push_str(if key { "\"\"" } else { "null" })?;
                return Ok(());
            }
            return Err(EncodeError::InvalidUtf8);
        };
        if !key
            && self.flags.contains(JsonFlags::NUMERIC_CHECK)
            && let Some(number) = numeric_string(input)
        {
            return match number {
                Numeric::Integer(value) => {
                    self.output.formatted(format_args!("{value}"))?;
                    Ok(())
                }
                Numeric::Float(value) => self.float(value),
            };
        }
        write_string(&mut self.output, &text, self.flags, true)
    }

    fn float(&mut self, value: f64) -> Result<(), EncodeError> {
        if !value.is_finite() {
            if self.flags.contains(JsonFlags::PARTIAL_OUTPUT_ON_ERROR) {
                self.output.push('0')?;
                return Ok(());
            }
            return Err(EncodeError::NonFiniteFloat);
        }
        let shortest = format!("{value:e}");
        let (mantissa, _) = shortest.split_once('e').unwrap_or((&shortest, "0"));
        let fraction_digits = mantissa
            .split_once('.')
            .map_or(0, |(_, fraction)| fraction.len());
        // Rust's shortest formatter rounds midpoint ties up. Formatting to the
        // same precision rounds ties to even, which is what PHP's JSON encoder uses.
        let rounded = format!("{value:.fraction_digits$e}");
        let (mantissa, exponent) = rounded.split_once('e').unwrap_or((&rounded, "0"));
        let exponent = exponent.parse::<i32>().unwrap_or(0);
        if !(-4..17).contains(&exponent) {
            self.output.push_str(mantissa)?;
            if fraction_digits == 0 {
                self.output.push_str(".0")?;
            }
            self.output.formatted(format_args!("e{exponent:+}"))?;
        } else {
            self.decimal(mantissa, exponent)?;
        }
        Ok(())
    }

    fn decimal(&mut self, mantissa: &str, exponent: i32) -> Result<(), EncodeError> {
        let mantissa = match mantissa.strip_prefix('-') {
            Some(mantissa) => {
                self.output.push('-')?;
                mantissa
            }
            None => mantissa,
        };
        let (whole, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
        if exponent < 0 {
            self.output.push_str("0.")?;
            for _ in 0..(-exponent - 1) {
                self.output.push('0')?;
            }
            self.output.push_str(whole)?;
            self.output.push_str(fraction)?;
        } else {
            let places = exponent as usize;
            self.output.push_str(whole)?;
            if places < fraction.len() {
                let (integer, decimals) = fraction.split_at(places);
                self.output.push_str(integer)?;
                self.output.push('.')?;
                self.output.push_str(decimals)?;
            } else {
                self.output.push_str(fraction)?;
                for _ in fraction.len()..places {
                    self.output.push('0')?;
                }
                if self.flags.contains(JsonFlags::PRESERVE_ZERO_FRACTION) {
                    self.output.push_str(".0")?;
                }
            }
        }
        Ok(())
    }
}

enum Numeric {
    Integer(i64),
    Float(f64),
}

fn numeric_string(input: &[u8]) -> Option<Numeric> {
    let text = std::str::from_utf8(input)
        .ok()?
        .trim_matches([' ', '\t', '\n', '\r', '\u{b}', '\u{c}']);
    if let Ok(value) = text.parse::<i64>() {
        return Some(Numeric::Integer(value));
    }
    let value = text.parse::<f64>().ok()?;
    value.is_finite().then_some(Numeric::Float(value))
}

fn write_string(
    output: &mut Sink,
    text: &str,
    flags: JsonFlags,
    quotes: bool,
) -> Result<(), EncodeError> {
    if quotes {
        output.push('"')?;
    }
    for ch in text.chars() {
        let escaped = match ch {
            '"' if flags.contains(JsonFlags::HEX_QUOT) => "\\u0022",
            '"' => "\\\"",
            '\\' => "\\\\",
            '/' if !flags.contains(JsonFlags::UNESCAPED_SLASHES) => "\\/",
            '<' if flags.contains(JsonFlags::HEX_TAG) => "\\u003C",
            '>' if flags.contains(JsonFlags::HEX_TAG) => "\\u003E",
            '&' if flags.contains(JsonFlags::HEX_AMP) => "\\u0026",
            '\'' if flags.contains(JsonFlags::HEX_APOS) => "\\u0027",
            '\u{8}' => "\\b",
            '\u{c}' => "\\f",
            '\t' => "\\t",
            '\n' => "\\n",
            '\r' => "\\r",
            '\0'..='\u{1f}' => {
                output.formatted(format_args!("\\u{:04x}", ch as u32))?;
                continue;
            }
            _ if !ch.is_ascii()
                && (!flags.contains(JsonFlags::UNESCAPED_UNICODE)
                    || (matches!(ch, '\u{2028}' | '\u{2029}')
                        && !flags.contains(JsonFlags::UNESCAPED_LINE_TERMINATORS))) =>
            {
                for unit in ch.encode_utf16(&mut [0; 2]) {
                    output.formatted(format_args!("\\u{unit:04x}"))?;
                }
                continue;
            }
            _ => {
                output.push(ch)?;
                continue;
            }
        };
        output.push_str(escaped)?;
    }
    if quotes {
        output.push('"')?;
    }
    Ok(())
}