use crate::prelude::{Epoch, ParsingError};
pub(crate) fn format_header(epoch: Epoch) -> String {
let (y, m, d, hh, mm, ss, _nanos) = epoch.to_gregorian(epoch.time_scale);
format!(
"{:04} {:>2} {:>2} {:>2} {:>2} {:>2}",
y, m, d, hh, mm, ss
)
}
pub(crate) fn format_body(epoch: Epoch) -> String {
let (y, m, d, hh, mm, ss, _nanos) = epoch.to_gregorian(epoch.time_scale);
format!(
" {:04} {:>2} {:>2} {:>2} {:>2} {:>2}",
y, m, d, hh, mm, ss
)
}
pub(crate) fn parse_utc(s: &str) -> Result<Epoch, ParsingError> {
let (mut y, mut m, mut d, mut hh, mut mm, mut ss) = (0_i32, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8);
for (index, field) in s.split_ascii_whitespace().enumerate() {
match index {
0 => {
y = field
.trim()
.parse::<i32>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
1 => {
m = field
.trim()
.parse::<u8>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
2 => {
d = field
.trim()
.parse::<u8>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
3 => {
hh = field
.trim()
.parse::<u8>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
4 => {
mm = field
.trim()
.parse::<u8>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
5 => {
ss = field
.trim()
.parse::<u8>()
.map_err(|_| ParsingError::DatetimeParsing)?;
},
_ => {},
}
}
Ok(Epoch::from_gregorian_utc(y, m, d, hh, mm, ss, 0))
}
#[cfg(test)]
mod test {
use super::*;
use hifitime::Epoch;
use std::str::FromStr;
#[test]
fn datetime_parsing() {
for (desc, expected) in [(
" 2022 1 2 0 0 0 ",
Epoch::from_str("2022-01-02T00:00:00 UTC").unwrap(),
)] {
let epoch = parse_utc(desc).unwrap_or_else(|e| {
panic!("Failed to parse datetime from \"{}\": {}", desc, e);
});
assert_eq!(epoch, expected);
}
}
}