Skip to content

Commit 55badc9

Browse files
committed
Support weekdays in parse_datetime
This commit resolves issue #23. Adds parse_weekday function that uses chrono weekday parser with a map for edge cases. Adds tests cases to make sure it works correctly.
1 parent 2737b4a commit 55badc9

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
target/
2+
fuzz/corpus

src/parse_weekday.rs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
use chrono::{ParseWeekdayError, Weekday};
2+
3+
const WEEKDAY_CONVERSION_MAP: [(&str, &str); 3] =
4+
[("tues", "tue"), ("thurs", "thu"), ("thus", "thu")];
5+
6+
pub(crate) fn parse_weekday(s: &str) -> Result<Weekday, ParseWeekdayError> {
7+
let mut s = s.trim().to_lowercase();
8+
for (before, after) in WEEKDAY_CONVERSION_MAP {
9+
if s == before {
10+
s = String::from(after);
11+
}
12+
}
13+
14+
s.trim().parse::<Weekday>()
15+
}
16+
17+
#[cfg(test)]
18+
mod tests {
19+
20+
use chrono::Weekday::*;
21+
22+
use crate::parse_weekday::parse_weekday;
23+
#[test]
24+
fn test_valid_weekdays() {
25+
let days = [
26+
("mon", Mon),
27+
("monday", Mon),
28+
("tue", Tue),
29+
("tues", Tue),
30+
("tuesday", Tue),
31+
("wed", Wed),
32+
("wednesday", Wed),
33+
("thu", Thu),
34+
("thursday", Thu),
35+
("fri", Fri),
36+
("friday", Fri),
37+
("sat", Sat),
38+
("saturday", Sat),
39+
("sun", Sun),
40+
("sunday", Sun),
41+
];
42+
43+
for day in days.iter() {
44+
let mut test_strings = vec![];
45+
test_strings.push(String::from(day.0));
46+
test_strings.push(format!(" {}", day.0));
47+
test_strings.push(format!(" {} ", day.0));
48+
test_strings.push(format!("{} ", day.0));
49+
test_strings.push(format!(" {}", day.0.to_uppercase()));
50+
51+
let (left, right) = day.0.split_at(1);
52+
test_strings.push(format!("{}{}", left.to_uppercase(), right.to_lowercase()));
53+
test_strings.push(format!("{}{}", left.to_lowercase(), right.to_uppercase()));
54+
55+
for str in test_strings.iter() {
56+
assert!(parse_weekday(str).is_ok());
57+
assert_eq!(parse_weekday(str).unwrap(), day.1);
58+
}
59+
}
60+
}
61+
62+
#[test]
63+
fn test_invalid_weekdays() {
64+
let days = [
65+
"mond",
66+
"tuesda",
67+
"we",
68+
"th",
69+
"fr",
70+
"sa",
71+
"su",
72+
"garbageday",
73+
"tomorrow",
74+
"yesterday",
75+
];
76+
for day in days {
77+
assert!(parse_weekday(day).is_err());
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)