use flow_value::{Decimal, Duration, Instant};
use num_bigint::BigInt;
use num_integer::Integer;
const SECONDS_PER_DAY: i64 = 86_400;
pub(crate) fn instant(text: &str) -> Option<Instant> {
let mut cursor = Cursor(text);
let sign = cursor.sign();
let year = cursor.digits();
if year.len() < 4 || (year.len() > 4 && sign.is_none()) {
return None;
}
let year: BigInt = year.parse().ok()?;
let year = if sign == Some(-1) { -year } else { year };
cursor.expect('-')?;
let month = cursor.fixed(2, 1, 12)?;
cursor.expect('-')?;
let day = cursor.fixed(2, 1, days_in_month(&year, month))?;
cursor.expect('T')?;
let hour = cursor.fixed(2, 0, 23)?;
cursor.expect(':')?;
let minute = cursor.fixed(2, 0, 59)?;
cursor.expect(':')?;
let second = cursor.fixed(2, 0, 59)?;
let fraction = if cursor.eat('.') {
let digits = cursor.digits();
if digits.is_empty() {
return None;
}
decimal(&format!("0.{digits}"))?
} else {
decimal("0")?
};
let offset = if cursor.eat('Z') {
0
} else {
let sign = cursor.sign()?;
let hours = cursor.fixed(2, 0, 23)?;
cursor.expect(':')?;
let minutes = cursor.fixed(2, 0, 59)?;
sign * (hours * 3600 + minutes * 60)
};
if !cursor.0.is_empty() {
return None;
}
let days = days_from_civil(year, month, day);
let whole = days * SECONDS_PER_DAY + (hour * 3600 + minute * 60 + second - offset);
let seconds = Decimal::new(whole, 0).ok()?.add(&fraction).ok()?;
Some(Instant::from_unix_seconds(seconds))
}
pub(crate) fn duration(text: &str) -> Option<Duration> {
let mut cursor = Cursor(text);
let negative = cursor.eat('-');
cursor.expect('P')?;
let mut total = decimal("0")?;
let mut any = false;
if let Some(days) = cursor.component('D', false) {
total = total.add(&days.mul(&decimal("86400")?).ok()?).ok()?;
any = true;
}
if cursor.eat('T') {
let mut timed = false;
for (unit, scale, fraction) in [('H', "3600", false), ('M', "60", false), ('S', "1", true)]
{
if let Some(count) = cursor.component(unit, fraction) {
total = total.add(&count.mul(&decimal(scale)?).ok()?).ok()?;
timed = true;
}
}
if !timed {
return None;
}
any = true;
}
if !any || !cursor.0.is_empty() {
return None;
}
Some(Duration::from_seconds(if negative {
total.neg()
} else {
total
}))
}
fn decimal(spelling: &str) -> Option<Decimal> {
Decimal::parse(spelling)
}
struct Cursor<'t>(&'t str);
impl<'t> Cursor<'t> {
fn eat(&mut self, expected: char) -> bool {
match self.0.strip_prefix(expected) {
Some(rest) => {
self.0 = rest;
true
}
None => false,
}
}
fn expect(&mut self, expected: char) -> Option<()> {
self.eat(expected).then_some(())
}
fn sign(&mut self) -> Option<i64> {
if self.eat('+') {
Some(1)
} else if self.eat('-') {
Some(-1)
} else {
None
}
}
fn digits(&mut self) -> &'t str {
let end = self
.0
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(self.0.len());
let (digits, rest) = self.0.split_at(end);
self.0 = rest;
digits
}
fn fixed(&mut self, width: usize, low: i64, high: i64) -> Option<i64> {
let digits = self.0.get(..width)?;
if !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
self.0 = &self.0[width..];
let number: i64 = digits.parse().ok()?;
(low..=high).contains(&number).then_some(number)
}
fn component(&mut self, unit: char, fraction: bool) -> Option<Decimal> {
let saved = self.0;
let found = self.number(fraction).filter(|_| self.eat(unit));
if found.is_none() {
self.0 = saved;
}
found
}
fn number(&mut self, fraction: bool) -> Option<Decimal> {
let negative = self.eat('-');
let whole = self.digits();
if whole.is_empty() {
return None;
}
let mut spelling = format!("{}{whole}", if negative { "-" } else { "" });
if fraction && self.eat('.') {
let digits = self.digits();
if digits.is_empty() {
return None;
}
spelling.push('.');
spelling.push_str(digits);
}
decimal(&spelling)
}
}
fn is_leap(year: &BigInt) -> bool {
let divides = |n: u32| year.mod_floor(&BigInt::from(n)) == BigInt::from(0);
divides(4) && (!divides(100) || divides(400))
}
fn days_in_month(year: &BigInt, month: i64) -> i64 {
match month {
2 if is_leap(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn days_from_civil(year: BigInt, month: i64, day: i64) -> BigInt {
let year = if month <= 2 { year - 1 } else { year };
let (era, year_of_era) = year.div_mod_floor(&BigInt::from(400));
let year_of_era: i64 = i64::try_from(&year_of_era).expect("a remainder below 400");
let shifted_month = if month > 2 { month - 3 } else { month + 9 };
let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}