use std::str::FromStr;
use redup_primitives::Timestamp;
use time::{Date, Month, Time};
use crate::node::{Node, Shape, Unbuilt, read_scalar, replaced, sampled};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;
const SAMPLE_YEAR: i32 = 1970;
const DATE_LEN: usize = 10;
const TIME_LEN: usize = 5;
const TIME_WITH_SECONDS_LEN: usize = 8;
const DATE_FORM: &str = "a date in the form `YYYY-MM-DD` is expected";
const TIME_FORM: &str = "a time in the form `HH:MM:SS` is expected";
fn pair(bytes: &[u8], at: usize) -> Option<u32> {
let tens = bytes
.get(at)
.copied()
.filter(|byte| byte.is_ascii_digit())?;
let ones = bytes
.get(at + 1)
.copied()
.filter(|byte| byte.is_ascii_digit())?;
Some(u32::from(tens - b'0') * 10 + u32::from(ones - b'0'))
}
fn quad(bytes: &[u8], at: usize) -> Option<i32> {
let mut value: i32 = 0;
for index in at..at + 4 {
let digit = i32::from(
bytes
.get(index)
.copied()
.filter(|byte| byte.is_ascii_digit())?,
) - i32::from(b'0');
value = value * 10 + digit;
}
Some(value)
}
fn parse_date(text: &str) -> Result<Date, &'static str> {
let bytes = text.as_bytes();
if bytes.len() != DATE_LEN {
return Err(DATE_FORM);
}
let separator = bytes.get(4).copied();
let second = bytes.get(7).copied();
match (separator, second) {
(Some(separator @ (b'-' | b'.')), Some(second)) if second == separator => {}
_ => return Err(DATE_FORM),
}
let year = quad(bytes, 0).ok_or(DATE_FORM)?;
let month = pair(bytes, 5).ok_or(DATE_FORM)?;
let day = pair(bytes, 8).ok_or(DATE_FORM)?;
let month = u8::try_from(month)
.ok()
.and_then(|month| Month::try_from(month).ok())
.ok_or(DATE_FORM)?;
let day = u8::try_from(day).map_err(|_| DATE_FORM)?;
Date::from_calendar_date(year, month, day).map_err(|_| DATE_FORM)
}
fn parse_time(text: &str) -> Result<Time, &'static str> {
let bytes = text.as_bytes();
let with_seconds = match bytes.len() {
TIME_LEN => false,
TIME_WITH_SECONDS_LEN => bytes.get(5) == Some(&b':'),
_ => return Err(TIME_FORM),
};
if bytes.get(2) != Some(&b':') {
return Err(TIME_FORM);
}
let hour = pair(bytes, 0).ok_or(TIME_FORM)?;
let minute = pair(bytes, 3).ok_or(TIME_FORM)?;
let second = if with_seconds {
pair(bytes, 6).ok_or(TIME_FORM)?
} else {
0
};
let (Ok(hour), Ok(minute), Ok(second)) = (
u8::try_from(hour),
u8::try_from(minute),
u8::try_from(second),
) else {
return Err(TIME_FORM);
};
Time::from_hms(hour, minute, second).map_err(|_| TIME_FORM)
}
impl Node for Date {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
read_scalar(raw, path, problems, "a date", parse_date)
}
replaced!();
sampled!(Date::from_calendar_date(SAMPLE_YEAR, Month::January, 1).ok());
fn shape(&self) -> Shape<'_> {
Shape::Scalar(format!(
"{:04}.{:02}.{:02}",
self.year(),
u8::from(self.month()),
self.day()
))
}
}
impl Node for Time {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
read_scalar(raw, path, problems, "a time", parse_time)
}
replaced!();
sampled!(Some(Time::MIDNIGHT));
fn shape(&self) -> Shape<'_> {
Shape::Scalar(format!(
"{:02}:{:02}:{:02}",
self.hour(),
self.minute(),
self.second()
))
}
}
impl Node for Timestamp {
fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
read_scalar(raw, path, problems, "a date-time", Timestamp::from_str)
}
replaced!();
sampled!(Some(Timestamp::UNIX_EPOCH));
fn shape(&self) -> Shape<'_> {
Shape::Scalar(self.to_string())
}
}
#[cfg(test)]
mod tests {
use redup_primitives::Timestamp;
use time::{Date, Month, Time};
use super::{DATE_FORM, TIME_FORM};
use crate::node::{Node, Shape};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;
fn read<T: Node>(text: &str) -> Result<T, String> {
let raw = Raw::scalar(text, crate::mark::Mark::Model);
let mut problems = Problems::new();
match T::read(&raw, &Path::new(), &mut problems) {
Ok(value) => Ok(value),
Err(_) => Err(problems.to_string()),
}
}
fn text_of(value: &impl Node) -> String {
match value.shape() {
Shape::Scalar(text) => text,
_ => String::from("not a scalar"),
}
}
#[test]
fn date_is_read_in_both_forms_and_written_with_dots() -> Result<(), String> {
let cases = [
("2024-01-02", "2024.01.02"),
("2024.01.02", "2024.01.02"),
("0000-01-01", "0000.01.01"),
("9999-12-31", "9999.12.31"),
("2024-02-29", "2024.02.29"),
];
for (text, written) in cases {
let date: Date = read(text)?;
assert_eq!(text_of(&date), written, "read {text:?}");
assert_eq!(read::<Date>(&text_of(&date)), Ok(date), "read back");
}
assert_eq!(
Date::from_calendar_date(1970, Month::January, 1)
.ok()
.map(|value| text_of(&value)),
<Date as Node>::sample().map(|value| text_of(&value))
);
Ok(())
}
#[test]
fn date_rejects_other_writings() {
for text in [
"",
"2024-1-2",
"2024.1.2",
"20240102",
"2024/01/02",
"2024-2024-01-02",
"2024.01-02",
"2024-13-01",
"2024-00-10",
"2024-02-30",
"2023-02-29",
"2024-01-02T00:00:00",
" 2024-01-02",
"2024-01-02 ",
] {
let error = read::<Date>(text).unwrap_err();
assert!(error.ends_with(DATE_FORM), "{text:?}: {error}");
assert!(error.contains(" is not a date: "), "{text:?}: {error}");
}
}
#[test]
fn time_is_read_with_or_without_seconds_and_written_with_them() -> Result<(), String> {
let cases = [
("03:04:05", "03:04:05"),
("03:04", "03:04:00"),
("00:00:00", "00:00:00"),
("23:59:59", "23:59:59"),
];
for (text, written) in cases {
let time: Time = read(text)?;
assert_eq!(text_of(&time), written, "read {text:?}");
}
assert_eq!(
<Time as Node>::sample().map(|time| text_of(&time)),
Some("00:00:00".to_owned())
);
Ok(())
}
#[test]
fn time_rejects_other_writings() {
for text in [
"",
"3:4:5",
"03:4:05",
"03:04:5",
"03:04:60",
"03:60:00",
"03-04:05",
"03:04:05.5",
"03:04:05PM",
"03",
"03:04:05Z",
"03:041",
] {
let error = read::<Time>(text).unwrap_err();
assert!(error.ends_with(TIME_FORM), "{text:?}: {error}");
assert!(error.contains(" is not a time: "), "{text:?}: {error}");
}
}
#[test]
fn moment_keeps_its_own_writing() {
let moment: Timestamp = read("2024-01-02 06:04:05+03:00").unwrap();
assert_eq!(text_of(&moment), "2024-01-02 03:04:05Z");
assert_eq!(
<Timestamp as Node>::sample().map(|moment| text_of(&moment)),
Some("1970-01-01 00:00:00Z".to_owned())
);
let error = read::<Timestamp>("notadate").unwrap_err();
assert!(
error.starts_with("\"notadate\" is not a date-time: "),
"{error}"
);
}
}