raoh 0.1.0

Decoders that turn untyped JSON into typed domain values, reporting every issue with its path
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
use super::ip;
use super::steps::Steps;
use super::unexpected;
use crate::decoder::Decoder;
use crate::issue::{Issue, Issues};
use crate::java;
use crate::path::Path;
use crate::{codes, message_keys};
use serde_json::Value;
use std::marker::PhantomData;
use std::str::FromStr;

const MAX_EMAIL_LENGTH: usize = 254;

/// A decoder of a JSON string.
///
/// Missing or `null` is `required`; any other type is `type_mismatch`. Constraints and
/// transformations run in the order they are written, and the first constraint to fail is the one
/// reported. An empty string is accepted unless [`non_blank`](Self::non_blank) says otherwise.
///
/// What counts as whitespace, a character and the order of strings are as in Raoh for Java; see
/// each method.
///
/// ```
/// use raoh::json::prelude::*;
///
/// let name = string().trim().non_blank().max_length(5);
/// assert_eq!(name.decode(&json!("  Ken ")).unwrap(), "Ken");
/// assert_eq!(name.decode(&json!("   ")).unwrap_err().iter().next().unwrap().code(), "blank");
/// ```
#[derive(Clone, Debug, Default)]
pub struct StringDecoder {
    steps: Steps<String>,
}

/// A decoder of a JSON string.
pub fn string() -> StringDecoder {
    StringDecoder::default()
}

impl Decoder<Value> for StringDecoder {
    type Output = String;

    fn decode_at(&self, input: &Value, path: &Path<'_>) -> Result<String, Issues> {
        match input {
            Value::String(s) => self.steps.run(s.clone(), path),
            other => Err(self.steps.base_issue(unexpected(path, "string", other))),
        }
    }
}

/// The number of characters, as Raoh for Java counts them: code points.
fn char_count(s: &str) -> usize {
    s.chars().count()
}

fn invalid_format(key: &'static str) -> Issue {
    Issue::new(codes::INVALID_FORMAT).with_message_key(key)
}

impl StringDecoder {
    fn transform(mut self, f: fn(&str) -> String) -> Self {
        self.steps.transform(move |s| f(&s));
        self
    }

    fn format(
        mut self,
        ok: impl Fn(&str) -> bool + Send + Sync + 'static,
        key: &'static str,
    ) -> Self {
        self.steps
            .require(move |s| ok(s), move |_| invalid_format(key));
        self
    }

    /// Gives the most recent constraint written before this, or the type check when there is
    /// none, a custom message that every language shows as written. Transformations such as
    /// [`trim`](Self::trim) are passed over, as they cannot fail.
    ///
    /// ```
    /// use raoh::json::prelude::*;
    ///
    /// let code = string().min_length(3).message("too short a code");
    /// let issues = code.decode(&json!("ab")).unwrap_err();
    /// assert_eq!(issues.iter().next().unwrap().message(), "too short a code");
    ///
    /// let name = string().trim().message("give a name");
    /// let issues = name.decode(&Value::Null).unwrap_err();
    /// assert_eq!(issues.iter().next().unwrap().message(), "give a name");
    /// ```
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.steps.set_message(message.into());
        self
    }

    /// Removes whitespace from both ends: the characters with Unicode's `White_Space` property,
    /// which include U+3000 and U+00A0 and not control characters such as NUL. It is the set
    /// [`non_blank`](Self::non_blank) uses, and the one Raoh for Java uses from 0.8 on.
    pub fn trim(self) -> Self {
        self.transform(|s| s.trim().to_owned())
    }

    /// Converts to lower case with Unicode's case mapping, as Raoh for Java does with
    /// `Locale.ROOT`.
    pub fn lowercase(self) -> Self {
        self.transform(str::to_lowercase)
    }

    /// Converts to upper case with Unicode's case mapping, as Raoh for Java does with
    /// `Locale.ROOT`.
    pub fn uppercase(self) -> Self {
        self.transform(str::to_uppercase)
    }

    /// Requires a character that is not whitespace, in the sense [`trim`](Self::trim) uses:
    /// `blank`. An empty string is blank.
    pub fn non_blank(mut self) -> Self {
        self.steps.require(
            |s| !s.chars().all(char::is_whitespace),
            |_| Issue::new(codes::BLANK),
        );
        self
    }

    /// Requires at least `n` characters, counted as code points: `too_short` with `min` and
    /// `actual`.
    pub fn min_length(mut self, n: usize) -> Self {
        self.steps.require(
            move |s| char_count(s) >= n,
            move |s| {
                Issue::new(codes::TOO_SHORT)
                    .with_meta("min", n)
                    .with_meta("actual", char_count(s))
            },
        );
        self
    }

    /// Allows at most `n` characters, counted as code points: `too_long` with `max` and `actual`.
    pub fn max_length(mut self, n: usize) -> Self {
        self.steps.require(
            move |s| char_count(s) <= n,
            move |s| {
                Issue::new(codes::TOO_LONG)
                    .with_meta("max", n)
                    .with_meta("actual", char_count(s))
            },
        );
        self
    }

    /// Requires exactly `n` characters, counted as code points: `invalid_length` with `expected`
    /// and `actual`.
    pub fn length(mut self, n: usize) -> Self {
        self.steps.require(
            move |s| char_count(s) == n,
            move |s| {
                Issue::new(codes::INVALID_LENGTH)
                    .with_meta("expected", n)
                    .with_meta("actual", char_count(s))
            },
        );
        self
    }

    /// Requires the string to start with `prefix`: `invalid_format` with `prefix`.
    pub fn starts_with(mut self, prefix: impl Into<String>) -> Self {
        let prefix = prefix.into();
        let expected = prefix.clone();
        self.steps.require(
            move |s| s.starts_with(expected.as_str()),
            move |_| {
                invalid_format(message_keys::INVALID_FORMAT_STARTS_WITH)
                    .with_meta("prefix", prefix.clone())
            },
        );
        self
    }

    /// Requires the string to end with `suffix`: `invalid_format` with `suffix`.
    pub fn ends_with(mut self, suffix: impl Into<String>) -> Self {
        let suffix = suffix.into();
        let expected = suffix.clone();
        self.steps.require(
            move |s| s.ends_with(expected.as_str()),
            move |_| {
                invalid_format(message_keys::INVALID_FORMAT_ENDS_WITH)
                    .with_meta("suffix", suffix.clone())
            },
        );
        self
    }

    /// Requires the string to contain `substring`: `invalid_format` with `substring`.
    pub fn contains(mut self, substring: impl Into<String>) -> Self {
        let substring = substring.into();
        let expected = substring.clone();
        self.steps.require(
            move |s| s.contains(expected.as_str()),
            move |_| {
                invalid_format(message_keys::INVALID_FORMAT_INCLUDES)
                    .with_meta("substring", substring.clone())
            },
        );
        self
    }

    /// Requires one of `allowed`: `not_allowed` with `allowed` sorted by code point, and `actual`.
    pub fn one_of<S: Into<String>>(mut self, allowed: impl IntoIterator<Item = S>) -> Self {
        let mut allowed: Vec<String> = allowed.into_iter().map(Into::into).collect();
        allowed.sort();
        allowed.dedup();
        let check = allowed.clone();
        self.steps.require(
            move |s| check.contains(s),
            move |s| {
                Issue::new(codes::NOT_ALLOWED)
                    .with_meta("allowed", allowed.clone())
                    .with_meta("actual", s.clone())
            },
        );
        self
    }

    /// Requires the form of an email address, as Raoh for Java checks it: `invalid_format`.
    pub fn email(self) -> Self {
        self.format(is_email, message_keys::INVALID_FORMAT_EMAIL)
    }

    /// Requires an IPv4 address in dotted decimal: `invalid_format`.
    pub fn ipv4(self) -> Self {
        self.format(ip::is_ipv4, message_keys::INVALID_FORMAT_IPV4)
    }

    /// Requires an IPv6 address in the RFC 4291 text form, as Raoh for Java checks it:
    /// `invalid_format`. An embedded dotted quad (`::ffff:192.0.2.1`) is allowed and brackets
    /// (`[::1]`) are not. A zone ID (`fe80::1%eth0`) is allowed on a link-local or non-global
    /// multicast address and decided by its text alone, not by the host's interfaces.
    pub fn ipv6(self) -> Self {
        self.format(ip::is_ipv6, message_keys::INVALID_FORMAT_IPV6)
    }

    /// Requires an address [`ipv4`](Self::ipv4) or [`ipv6`](Self::ipv6) accepts:
    /// `invalid_format`.
    pub fn ip(self) -> Self {
        self.format(
            |s| ip::is_ipv4(s) || ip::is_ipv6(s),
            message_keys::INVALID_FORMAT_IP,
        )
    }

    /// Requires a ULID, 26 characters of Crockford's base 32 in upper case: `invalid_format`.
    pub fn ulid(self) -> Self {
        self.format(
            |s| {
                s.len() == 26
                    && s.bytes().all(|b| {
                        b.is_ascii_digit()
                            || (b.is_ascii_uppercase() && !matches!(b, b'I' | b'L' | b'O' | b'U'))
                    })
            },
            message_keys::INVALID_FORMAT_ULID,
        )
    }

    /// Requires a CUID, `c` followed by 24 lower-case letters or digits: `invalid_format`.
    pub fn cuid(self) -> Self {
        self.format(
            |s| {
                s.len() == 25
                    && s.starts_with('c')
                    && s[1..]
                        .bytes()
                        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
            },
            message_keys::INVALID_FORMAT_CUID,
        )
    }

    /// Requires the whole string to match `pattern`: `invalid_format` with `pattern`.
    ///
    /// The pattern is written in the syntax of the [`regex`](https://docs.rs/regex) crate, not
    /// Java's, and is anchored at both ends as Java's `Matcher.matches` is. The two differ: here
    /// `\d`, `\w` and `\s` match any Unicode digit, word character and space, where Java's match
    /// ASCII only; write `[0-9]` for an ASCII digit. Lookaround and backreferences are not
    /// available.
    ///
    /// # Panics
    ///
    /// When `pattern` is not a valid regular expression.
    #[cfg(feature = "regex")]
    pub fn pattern(mut self, pattern: &str) -> Self {
        let anchored = regex::Regex::new(&format!("^(?:{pattern})$"))
            .unwrap_or_else(|e| panic!("invalid pattern {pattern:?}: {e}"));
        let pattern = pattern.to_owned();
        self.steps.require(
            move |s| anchored.is_match(s),
            move |_| Issue::new(codes::INVALID_FORMAT).with_meta("pattern", pattern.clone()),
        );
        self
    }

    /// A decoder that parses the string into a `T` with [`FromStr`]: `invalid_format` when it does
    /// not parse.
    ///
    /// ```
    /// use raoh::json::prelude::*;
    /// use std::net::IpAddr;
    ///
    /// let addr = string().parse::<IpAddr>();
    /// assert!(addr.decode(&json!("::1")).is_ok());
    /// ```
    pub fn parse<T: FromStr>(self) -> Parse<T> {
        Parse {
            string: self,
            message: None,
            target: PhantomData,
        }
    }

    /// A decoder that reads the string as a UUID with the `uuid` crate: `invalid_format` when it
    /// is not one.
    ///
    /// The `uuid` crate accepts the hyphenated form, the 32 digits without hyphens, and those in
    /// braces or after `urn:uuid:`. Java's `UUID.fromString` accepts only hyphenated groups, but
    /// also groups shorter than the standard ones, such as `1-1-1-1-1`.
    #[cfg(feature = "uuid")]
    pub fn uuid(self) -> UuidDecoder {
        UuidDecoder {
            string: self,
            message: None,
        }
    }

    /// A decoder that reads the string as an `http` or `https` URL with a host, parsed by the
    /// `url` crate: `invalid_format` when it is not one.
    ///
    /// The `url` crate follows the WHATWG URL Standard, as browsers do, where Java's `URI` follows
    /// RFC 2396. It accepts a host holding `_` and non-ASCII characters, which Java's `URI` does
    /// not, and gives the URL normalised: `https://example.com` becomes `https://example.com/`.
    #[cfg(feature = "url")]
    pub fn url(self) -> UrlDecoder {
        UrlDecoder {
            string: self,
            message: None,
        }
    }
}

/// The decoder [`StringDecoder::parse`] returns.
pub struct Parse<T> {
    string: StringDecoder,
    message: Option<String>,
    target: PhantomData<fn() -> T>,
}

impl<T> std::fmt::Debug for Parse<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Parse")
            .field("string", &self.string)
            .field("target", &std::any::type_name::<T>())
            .finish()
    }
}

impl<T> Clone for Parse<T> {
    fn clone(&self) -> Self {
        Self {
            string: self.string.clone(),
            message: self.message.clone(),
            target: PhantomData,
        }
    }
}

impl<T> Parse<T> {
    /// Gives the issue a string that does not parse is reported with a custom message.
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

fn conversion_failed(path: &Path<'_>, key: &'static str, custom: &Option<String>) -> Issues {
    let issue = Issue::at_path(path, codes::INVALID_FORMAT).with_message_key(key);
    match custom {
        Some(custom) => issue.with_message(custom.clone()).into(),
        None => issue.into(),
    }
}

impl<T: FromStr> Decoder<Value> for Parse<T> {
    type Output = T;

    fn decode_at(&self, input: &Value, path: &Path<'_>) -> Result<T, Issues> {
        let s = self.string.decode_at(input, path)?;
        s.parse()
            .map_err(|_| conversion_failed(path, codes::INVALID_FORMAT, &self.message))
    }
}

/// The decoder [`StringDecoder::uuid`] returns.
#[cfg(feature = "uuid")]
#[derive(Clone, Debug)]
pub struct UuidDecoder {
    string: StringDecoder,
    message: Option<String>,
}

#[cfg(feature = "uuid")]
impl UuidDecoder {
    /// Gives the issue a string that is not a UUID is reported with a custom message.
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

#[cfg(feature = "uuid")]
impl Decoder<Value> for UuidDecoder {
    type Output = uuid::Uuid;

    fn decode_at(&self, input: &Value, path: &Path<'_>) -> Result<uuid::Uuid, Issues> {
        let s = self.string.decode_at(input, path)?;
        uuid::Uuid::parse_str(&s)
            .map_err(|_| conversion_failed(path, message_keys::INVALID_FORMAT_UUID, &self.message))
    }
}

/// The decoder [`StringDecoder::url`] returns.
#[cfg(feature = "url")]
#[derive(Clone, Debug)]
pub struct UrlDecoder {
    string: StringDecoder,
    message: Option<String>,
}

#[cfg(feature = "url")]
impl UrlDecoder {
    /// Gives the issue a string that is not a URL is reported with a custom message.
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

#[cfg(feature = "url")]
impl Decoder<Value> for UrlDecoder {
    type Output = url::Url;

    fn decode_at(&self, input: &Value, path: &Path<'_>) -> Result<url::Url, Issues> {
        let s = self.string.decode_at(input, path)?;
        let fail = || conversion_failed(path, message_keys::INVALID_FORMAT_URL, &self.message);
        let url = url::Url::parse(&s).map_err(|_| fail())?;
        let web = matches!(url.scheme(), "http" | "https");
        let has_host = url.host_str().is_some_and(|h| !h.is_empty());
        if web && has_host {
            Ok(url)
        } else {
            Err(fail())
        }
    }
}

/// `^[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]{1,255}\.[a-zA-Z]{2,}$`, at most 254 UTF-16 units, as
/// Raoh for Java checks it.
fn is_email(s: &str) -> bool {
    if java::utf16_len(s) > MAX_EMAIL_LENGTH {
        return false;
    }
    let Some((local, domain)) = s.split_once('@') else {
        return false;
    };
    let local_ok = (1..=64).contains(&local.len())
        && local
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'%' | b'+' | b'-'));
    let Some((host, tld)) = domain.rsplit_once('.') else {
        return false;
    };
    let host_ok = (1..=255).contains(&host.len())
        && host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'));
    let tld_ok = tld.len() >= 2 && tld.bytes().all(|b| b.is_ascii_alphabetic());
    local_ok && host_ok && tld_ok
}

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

    fn first<T: std::fmt::Debug>(result: Result<T, Issues>) -> Issue {
        result.unwrap_err().into_iter().next().unwrap()
    }

    #[test]
    fn missing_and_null_are_required_and_other_types_mismatch() {
        assert_eq!(first(string().decode(&Value::Null)).code(), "required");
        let issue = first(string().decode(&json!(1)));
        assert_eq!(issue.code(), "type_mismatch");
        assert_eq!(issue.meta()["actual"], "number");
    }

    #[test]
    fn the_first_failing_constraint_is_reported() {
        let issues = string()
            .min_length(3)
            .email()
            .decode(&json!("a"))
            .unwrap_err();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues.iter().next().unwrap().code(), "too_short");
    }

    #[test]
    fn length_counts_code_points() {
        assert!(string().max_length(2).decode(&json!("日本")).is_ok());
        assert!(string().length(1).decode(&json!("😀")).is_ok());
    }

    #[test]
    fn trim_and_non_blank_share_unicode_white_space() {
        let trim = |s: &str| string().trim().decode(&json!(s)).unwrap();
        assert_eq!(trim("\u{3000}a\u{a0}"), "a");
        assert_eq!(trim("\u{0}a\u{1f}"), "\u{0}a\u{1f}");
        assert_eq!(trim("\u{85}a\u{2028}"), "a");
        assert_eq!(trim("\u{feff}a\u{180e}"), "\u{feff}a\u{180e}");
        for blank in ["", "\u{a0}", "\u{3000}", "\u{2007}"] {
            assert_eq!(
                first(string().non_blank().decode(&json!(blank))).code(),
                "blank"
            );
        }
        for not_blank in ["\u{1c}", "\u{0}", "\u{200b}"] {
            assert!(string().non_blank().decode(&json!(not_blank)).is_ok());
        }
    }

    #[test]
    fn email_follows_the_java_pattern() {
        for ok in ["a@b.co", "first.last+tag@sub.example.com"] {
            assert!(is_email(ok), "{ok}");
        }
        for bad in ["a@b", "@b.co", "a@@b.co", "a@b.c", "a b@c.co", "a@b.c0"] {
            assert!(!is_email(bad), "{bad}");
        }
    }

    #[test]
    fn one_of_sorts_by_code_point() {
        let issue = first(
            string()
                .one_of(["\u{1f600}", "\u{ff21}"])
                .decode(&json!("z")),
        );
        assert_eq!(issue.meta()["allowed"], json!(["\u{ff21}", "\u{1f600}"]));
        assert_eq!(issue.message(), "must be one of [\u{ff21}, \u{1f600}]");
    }

    #[test]
    fn format_issues_name_the_check_in_their_key() {
        let issue = first(string().email().decode(&json!("x")));
        assert_eq!(issue.code(), "invalid_format");
        assert_eq!(issue.message_key(), "invalid_format.email");
        assert_eq!(issue.message(), "not a valid email");
    }

    #[test]
    fn a_message_goes_to_the_latest_constraint_past_transformations() {
        let decoder = string().min_length(3).trim().message("three or more");
        assert_eq!(
            first(decoder.decode(&json!("ab"))).message(),
            "three or more"
        );
        let decoder = string().trim().message("give a name");
        assert_eq!(first(decoder.decode(&Value::Null)).message(), "give a name");
    }
}