joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
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
use std::collections::BTreeMap;
use std::fmt;

use crate::error::{Error, Result};

/// A JSON value.
///
/// Objects are a `BTreeMap`, so serialising the same value twice produces
/// byte-identical output. That costs the original key order and buys
/// responses you can diff, cache and checksum.
///
/// Numbers come in two variants because JSON's one number type does not
/// survive `f64`. Above 2^53 an integer stops being exactly representable, so a
/// single `Number(f64)` turns the id `9007199254740993` into `...992` on the
/// way through. [`Json::Int`] holds an `i64` unchanged and [`Json::Float`] holds
/// everything with a fraction or an exponent. They are distinct values:
/// `Json::from(1i64) != Json::from(1.0)`.
///
/// The enum is `#[non_exhaustive]`, so a `match` on it needs a `_` arm.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Json {
    Null,
    Bool(bool),
    /// An integer, exactly as given.
    Int(i64),
    /// A number with a fraction or an exponent, or one too large for an `i64`.
    Float(f64),
    String(String),
    Array(Vec<Json>),
    Object(BTreeMap<String, Json>),
}

impl Json {
    /// Build an object from pairs.
    pub fn object<K: Into<String>>(pairs: Vec<(K, Json)>) -> Json {
        let mut map = BTreeMap::new();
        for (k, v) in pairs {
            map.insert(k.into(), v);
        }
        Json::Object(map)
    }

    pub fn is_null(&self) -> bool {
        matches!(self, Json::Null)
    }

    /// A field of an object, or `None` for any other kind of value.
    pub fn get(&self, key: &str) -> Option<&Json> {
        match self {
            Json::Object(map) => map.get(key),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Json::String(s) => Some(s),
            _ => None,
        }
    }

    /// Any number as an `f64`. An integer above 2^53 is rounded on the way out,
    /// which is the loss [`Json::Int`] exists to avoid: reach for
    /// [`Json::as_i64`] when the value is an identifier rather than a quantity.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Json::Float(n) => Some(*n),
            Json::Int(i) => Some(*i as f64),
            _ => None,
        }
    }

    /// Any number that is exactly an integer an `i64` can hold. A float still
    /// answers, since `{"n":1.0}` and `{"n":1}` mean the same thing to a caller
    /// asking for an integer.
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Json::Int(i) => Some(*i),
            // The bounds are what stop an out-of-range cast saturating quietly
            // to i64::MAX and reporting a number the document never contained.
            Json::Float(n) if n.fract() == 0.0 && *n >= i64::MIN as f64 && *n < i64::MAX as f64 => {
                Some(*n as i64)
            }
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Json::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[Json]> {
        match self {
            Json::Array(v) => Some(v),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&BTreeMap<String, Json>> {
        match self {
            Json::Object(m) => Some(m),
            _ => None,
        }
    }

    /// Parse a JSON document. Trailing content after the value is an error, so
    /// a truncated or doubled body is rejected rather than half-accepted.
    pub fn parse(input: &str) -> Result<Json> {
        let mut p = Parser {
            bytes: input.as_bytes(),
            pos: 0,
            depth: 0,
        };
        p.skip_whitespace();
        let value = p.value()?;
        p.skip_whitespace();
        if p.pos != p.bytes.len() {
            return Err(Error::Json(format!(
                "unexpected trailing input at byte {}",
                p.pos
            )));
        }
        Ok(value)
    }
}

impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Json::Null => f.write_str("null"),
            Json::Bool(true) => f.write_str("true"),
            Json::Bool(false) => f.write_str("false"),
            Json::Int(i) => write!(f, "{i}"),
            Json::Float(n) => write_float(f, *n),
            Json::String(s) => write_escaped(f, s),
            Json::Array(items) => {
                f.write_str("[")?;
                for (i, item) in items.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write!(f, "{item}")?;
                }
                f.write_str("]")
            }
            Json::Object(map) => {
                f.write_str("{")?;
                for (i, (k, v)) in map.iter().enumerate() {
                    if i > 0 {
                        f.write_str(",")?;
                    }
                    write_escaped(f, k)?;
                    f.write_str(":")?;
                    write!(f, "{v}")?;
                }
                f.write_str("}")
            }
        }
    }
}

fn write_float(f: &mut fmt::Formatter<'_>, n: f64) -> fmt::Result {
    if !n.is_finite() {
        // JSON has no infinity or NaN. Emitting null is what every other
        // serialiser does, and it keeps the output parseable.
        return f.write_str("null");
    }
    let text = n.to_string();
    f.write_str(&text)?;
    // A float that prints as `3` would read back as an integer, and keeping the
    // two apart is the whole reason there are two variants.
    if !text.contains(['.', 'e', 'E']) {
        f.write_str(".0")?;
    }
    Ok(())
}

fn write_escaped(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
    f.write_str("\"")?;
    for ch in s.chars() {
        match ch {
            '"' => f.write_str("\\\"")?,
            '\\' => f.write_str("\\\\")?,
            '\n' => f.write_str("\\n")?,
            '\r' => f.write_str("\\r")?,
            '\t' => f.write_str("\\t")?,
            '\u{08}' => f.write_str("\\b")?,
            '\u{0c}' => f.write_str("\\f")?,
            c if (c as u32) < 0x20 => write!(f, "\\u{:04x}", c as u32)?,
            // write_char lives on the fmt::Write trait; write! uses Formatter's
            // own inherent write_fmt, so nothing extra has to be imported.
            c => write!(f, "{c}")?,
        }
    }
    f.write_str("\"")
}

impl From<&str> for Json {
    fn from(v: &str) -> Json {
        Json::String(v.to_string())
    }
}
impl From<String> for Json {
    fn from(v: String) -> Json {
        Json::String(v)
    }
}
impl From<bool> for Json {
    fn from(v: bool) -> Json {
        Json::Bool(v)
    }
}
impl From<f64> for Json {
    fn from(v: f64) -> Json {
        Json::Float(v)
    }
}
impl From<i64> for Json {
    fn from(v: i64) -> Json {
        Json::Int(v)
    }
}
impl From<usize> for Json {
    fn from(v: usize) -> Json {
        match i64::try_from(v) {
            Ok(i) => Json::Int(i),
            // Past i64::MAX there is no exact variant left to land in, and a
            // rounded float beats refusing to build the value at all.
            Err(_) => Json::Float(v as f64),
        }
    }
}
impl From<Vec<Json>> for Json {
    fn from(v: Vec<Json>) -> Json {
        Json::Array(v)
    }
}

/// Nesting cap. A deeply nested document would otherwise recurse until the
/// thread's stack runs out, which is a denial of service on a public endpoint.
const MAX_DEPTH: usize = 128;

struct Parser<'a> {
    bytes: &'a [u8],
    pos: usize,
    depth: usize,
}

impl<'a> Parser<'a> {
    fn err<T>(&self, msg: &str) -> Result<T> {
        Err(Error::Json(format!("{msg} at byte {}", self.pos)))
    }

    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.pos).copied()
    }

    fn skip_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn expect(&mut self, b: u8) -> Result<()> {
        if self.peek() == Some(b) {
            self.pos += 1;
            Ok(())
        } else {
            self.err(&format!("expected '{}'", b as char))
        }
    }

    fn value(&mut self) -> Result<Json> {
        if self.depth > MAX_DEPTH {
            return self.err("nesting too deep");
        }
        match self.peek() {
            None => self.err("unexpected end of input"),
            Some(b'n') => self.literal("null", Json::Null),
            Some(b't') => self.literal("true", Json::Bool(true)),
            Some(b'f') => self.literal("false", Json::Bool(false)),
            Some(b'"') => Ok(Json::String(self.string()?)),
            Some(b'[') => self.array(),
            Some(b'{') => self.object(),
            Some(_) => self.number(),
        }
    }

    fn literal(&mut self, word: &str, value: Json) -> Result<Json> {
        if self.bytes[self.pos..].starts_with(word.as_bytes()) {
            self.pos += word.len();
            Ok(value)
        } else {
            self.err("invalid literal")
        }
    }

    fn string(&mut self) -> Result<String> {
        self.expect(b'"')?;
        let mut out = String::new();
        loop {
            let b = match self.peek() {
                Some(b) => b,
                None => return self.err("unterminated string"),
            };
            self.pos += 1;
            match b {
                b'"' => return Ok(out),
                b'\\' => {
                    let esc = match self.peek() {
                        Some(e) => e,
                        None => return self.err("unterminated escape"),
                    };
                    self.pos += 1;
                    match esc {
                        b'"' => out.push('"'),
                        b'\\' => out.push('\\'),
                        b'/' => out.push('/'),
                        b'b' => out.push('\u{08}'),
                        b'f' => out.push('\u{0c}'),
                        b'n' => out.push('\n'),
                        b'r' => out.push('\r'),
                        b't' => out.push('\t'),
                        b'u' => out.push(self.unicode_escape()?),
                        _ => return self.err("invalid escape"),
                    }
                }
                // Control characters must be escaped in JSON strings.
                0x00..=0x1f => return self.err("unescaped control character"),
                _ => {
                    // Copy the whole UTF-8 sequence starting at this byte.
                    let start = self.pos - 1;
                    let len = utf8_len(b);
                    if start + len > self.bytes.len() {
                        return self.err("truncated utf-8 sequence");
                    }
                    self.pos = start + len;
                    match std::str::from_utf8(&self.bytes[start..self.pos]) {
                        Ok(s) => out.push_str(s),
                        Err(_) => return self.err("invalid utf-8"),
                    }
                }
            }
        }
    }

    fn unicode_escape(&mut self) -> Result<char> {
        let high = self.hex4()?;
        // A surrogate pair is two escapes; a lone surrogate is not a character.
        if (0xD800..0xDC00).contains(&high) {
            if self.peek() != Some(b'\\') {
                return self.err("expected a low surrogate");
            }
            self.pos += 1;
            if self.peek() != Some(b'u') {
                return self.err("expected a low surrogate");
            }
            self.pos += 1;
            let low = self.hex4()?;
            if !(0xDC00..0xE000).contains(&low) {
                return self.err("invalid low surrogate");
            }
            let combined = 0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00);
            return match char::from_u32(combined) {
                Some(c) => Ok(c),
                None => self.err("invalid code point"),
            };
        }
        match char::from_u32(high) {
            Some(c) => Ok(c),
            None => self.err("invalid code point"),
        }
    }

    fn hex4(&mut self) -> Result<u32> {
        if self.pos + 4 > self.bytes.len() {
            return self.err("truncated \\u escape");
        }
        let slice = &self.bytes[self.pos..self.pos + 4];
        let text = match std::str::from_utf8(slice) {
            Ok(t) => t,
            Err(_) => return self.err("invalid \\u escape"),
        };
        match u32::from_str_radix(text, 16) {
            Ok(v) => {
                self.pos += 4;
                Ok(v)
            }
            Err(_) => self.err("invalid \\u escape"),
        }
    }

    fn number(&mut self) -> Result<Json> {
        let start = self.pos;
        if self.peek() == Some(b'-') {
            self.pos += 1;
        }
        while let Some(b) = self.peek() {
            if b.is_ascii_digit() || b == b'.' || b == b'e' || b == b'E' || b == b'+' || b == b'-' {
                self.pos += 1;
            } else {
                break;
            }
        }
        if start == self.pos {
            return self.err("expected a value");
        }
        let text = match std::str::from_utf8(&self.bytes[start..self.pos]) {
            Ok(t) => t,
            Err(_) => return self.err("invalid number"),
        };
        // An integer literal keeps its exact value. One too large for an i64
        // falls through to f64 and is rounded, which loses precision but parses
        // the document rather than rejecting a number JSON allows.
        if !text.contains(['.', 'e', 'E']) {
            if let Ok(i) = text.parse::<i64>() {
                return Ok(Json::Int(i));
            }
        }
        match text.parse::<f64>() {
            Ok(n) => Ok(Json::Float(n)),
            Err(_) => self.err("invalid number"),
        }
    }

    fn array(&mut self) -> Result<Json> {
        self.expect(b'[')?;
        self.depth += 1;
        let mut items = Vec::new();
        self.skip_whitespace();
        if self.peek() == Some(b']') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(Json::Array(items));
        }
        loop {
            self.skip_whitespace();
            items.push(self.value()?);
            self.skip_whitespace();
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b']') => {
                    self.pos += 1;
                    self.depth -= 1;
                    return Ok(Json::Array(items));
                }
                _ => return self.err("expected ',' or ']'"),
            }
        }
    }

    fn object(&mut self) -> Result<Json> {
        self.expect(b'{')?;
        self.depth += 1;
        let mut map = BTreeMap::new();
        self.skip_whitespace();
        if self.peek() == Some(b'}') {
            self.pos += 1;
            self.depth -= 1;
            return Ok(Json::Object(map));
        }
        loop {
            self.skip_whitespace();
            let key = self.string()?;
            self.skip_whitespace();
            self.expect(b':')?;
            self.skip_whitespace();
            let value = self.value()?;
            map.insert(key, value);
            self.skip_whitespace();
            match self.peek() {
                Some(b',') => self.pos += 1,
                Some(b'}') => {
                    self.pos += 1;
                    self.depth -= 1;
                    return Ok(Json::Object(map));
                }
                _ => return self.err("expected ',' or '}'"),
            }
        }
    }
}

fn utf8_len(first: u8) -> usize {
    if first < 0x80 {
        1
    } else if first >> 5 == 0b110 {
        2
    } else if first >> 4 == 0b1110 {
        3
    } else {
        4
    }
}

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

    #[test]
    fn round_trips_scalars() {
        for src in [
            "null",
            "true",
            "false",
            "42",
            "-1.5",
            "1.0",
            "9223372036854775807",
            "-9223372036854775808",
            "\"hi\"",
        ] {
            let v = Json::parse(src).unwrap();
            assert_eq!(Json::parse(&v.to_string()).unwrap(), v, "for {src}");
        }
    }

    #[test]
    fn large_integers_keep_every_digit() {
        // 2^53 + 1, the first integer an f64 cannot hold, and the largest i64.
        for n in [9_007_199_254_740_993i64, i64::MAX, i64::MIN] {
            let value = Json::from(n);
            assert_eq!(value.as_i64(), Some(n));
            let text = value.to_string();
            assert_eq!(text, n.to_string());
            assert_eq!(Json::parse(&text).unwrap().as_i64(), Some(n));
        }
    }

    #[test]
    fn integers_and_floats_are_separate_values() {
        assert_eq!(Json::parse("1").unwrap(), Json::Int(1));
        assert_eq!(Json::parse("1.0").unwrap(), Json::Float(1.0));
        assert_ne!(Json::from(1i64), Json::from(1.0));

        // A float that is exactly an integer keeps its point on the way out, or
        // it would read back as an integer.
        assert_eq!(Json::Float(1.0).to_string(), "1.0");
        assert_eq!(Json::Float(-0.0).to_string(), "-0.0");
        assert_eq!(Json::Int(1).to_string(), "1");
        // An exponent is a float, and prints as the number it denotes.
        assert_eq!(Json::parse("1e2").unwrap(), Json::Float(100.0));
        assert_eq!(Json::parse("1e2").unwrap().to_string(), "100.0");
    }

    #[test]
    fn a_float_that_is_a_whole_number_still_reads_as_an_integer() {
        assert_eq!(Json::parse("3.0").unwrap().as_i64(), Some(3));
        assert_eq!(Json::parse("3.5").unwrap().as_i64(), None);
        // Out of i64's range, so there is no integer to report.
        assert_eq!(Json::parse("1e30").unwrap().as_i64(), None);
        assert_eq!(Json::parse("3").unwrap().as_f64(), Some(3.0));
    }

    #[test]
    fn an_integer_too_large_for_i64_becomes_a_float() {
        let value = Json::parse("18446744073709551616").unwrap();
        assert!(matches!(value, Json::Float(_)));
        assert_eq!(value.as_i64(), None);
    }

    #[test]
    fn parses_nested_structures() {
        let v = Json::parse(r#"{"a":[1,2,{"b":null}],"c":true}"#).unwrap();
        assert_eq!(v.get("c").and_then(Json::as_bool), Some(true));
        let a = v.get("a").and_then(Json::as_array).unwrap();
        assert_eq!(a.len(), 3);
        assert!(a[2].get("b").unwrap().is_null());
    }

    #[test]
    fn object_output_is_deterministic() {
        let src = r#"{"z":1,"a":2,"m":3}"#;
        let once = Json::parse(src).unwrap().to_string();
        for _ in 0..50 {
            assert_eq!(Json::parse(src).unwrap().to_string(), once);
        }
        // Sorted, not insertion-ordered.
        assert_eq!(once, r#"{"a":2,"m":3,"z":1}"#);
    }

    #[test]
    fn escapes_and_unescapes() {
        let v = Json::String("quote \" back \\ newline \n tab \t".into());
        let text = v.to_string();
        assert!(text.contains("\\\""));
        assert!(text.contains("\\n"));
        assert_eq!(Json::parse(&text).unwrap(), v);
    }

    #[test]
    fn handles_surrogate_pairs() {
        let v = Json::parse(r#""🚀""#).unwrap();
        assert_eq!(v.as_str(), Some("🚀"));
    }

    #[test]
    fn rejects_malformed_input() {
        for src in [
            "",
            "{",
            "[1,]",
            "{\"a\":}",
            "tru",
            "\"unterminated",
            "{\"a\":1} trailing",
            "01x",
        ] {
            assert!(Json::parse(src).is_err(), "expected {src:?} to fail");
        }
    }

    #[test]
    fn rejects_runaway_nesting() {
        let deep = format!("{}1{}", "[".repeat(500), "]".repeat(500));
        assert!(Json::parse(&deep).is_err());
    }

    #[test]
    fn non_finite_numbers_serialise_as_null() {
        assert_eq!(Json::Float(f64::NAN).to_string(), "null");
        assert_eq!(Json::Float(f64::INFINITY).to_string(), "null");
    }
}