Debian Codegraph @

debian/missing-sources/proptest/examples/dateparser_v2.rs

raw
1 //-
2 // Copyright 2017 Jason Lingle
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use proptest::prelude::*;
11
12 fn parse_date(s: &str) -> Option<(u32, u32, u32)> {
13 if 10 != s.len() {
14 return None;
15 }
16
17 // NEW: Ignore non-ASCII strings so we don't need to deal with Unicode.
18 if !s.is_ascii() {
19 return None;
20 }
21
22 if "-" != &s[4..5] || "-" != &s[7..8] {
23 return None;
24 }
25
26 let year = &s[0..4];
27 let month = &s[6..7]; // !
28 let day = &s[8..10];
29
30 year.parse::<u32>().ok().and_then(|y| {
31 month
32 .parse::<u32>()
33 .ok()
34 .and_then(|m| day.parse::<u32>().ok().map(|d| (y, m, d)))
35 })
36 }
37
38 // NB We omit #[test] on these functions so that main() can call them.
39 proptest! {
40 fn doesnt_crash(s in "\\PC*") {
41 parse_date(&s);
42 }
43
44 fn parses_all_valid_dates(s in "[0-9]{4}-[0-9]{2}-[0-9]{2}") {
45 parse_date(&s).unwrap();
46 }
47
48 fn parses_date_back_to_original(y in 0u32..10_000,
49 m in 1u32..13, d in 1u32..32) {
50 let (y2, m2, d2) = parse_date(
51 &format!("{:04}-{:02}-{:02}", y, m, d)).unwrap();
52 prop_assert_eq!((y, m, d), (y2, m2, d2));
53 }
54 }
55
56 fn main() {
57 assert_eq!(None, parse_date("2017-06-1"));
58 assert_eq!(None, parse_date("2017-06-170"));
59 assert_eq!(None, parse_date("2017006-17"));
60 assert_eq!(None, parse_date("2017-06017"));
61 assert_eq!(Some((2017, 6, 17)), parse_date("2017-06-17"));
62
63 doesnt_crash();
64 parses_all_valid_dates();
65 parses_date_back_to_original();
66 }