use std::io::Read;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use cfb::CompoundFile;
pub fn earliest_created_timestamp<F: Read + std::io::Seek>(
comp: &mut CompoundFile<F>,
) -> Option<String> {
comp.walk()
.map(|entry| entry.created())
.filter(|t| *t > UNIX_EPOCH)
.min()
.map(system_time_to_rfc3339)
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = (doy - (153 * mp + 2) / 5 + 1) as u32; let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32; (if m <= 2 { y + 1 } else { y }, m, d)
}
fn system_time_to_rfc3339(t: SystemTime) -> String {
let dur = t.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
let total_secs = dur.as_secs() as i64;
let millis = dur.subsec_millis();
let days = total_secs.div_euclid(86_400);
let sec_of_day = total_secs.rem_euclid(86_400);
let (year, month, day) = civil_from_days(days);
let hour = sec_of_day / 3600;
let minute = (sec_of_day % 3600) / 60;
let second = sec_of_day % 60;
if millis > 0 {
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
} else {
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}
}
#[cfg(test)]
mod tests {
use super::system_time_to_rfc3339;
use std::time::{Duration, UNIX_EPOCH};
#[test]
fn formats_known_instant_without_millis() {
let t = UNIX_EPOCH + Duration::from_secs(1_560_067_692);
assert_eq!(system_time_to_rfc3339(t), "2019-06-09T08:08:12Z");
}
#[test]
fn formats_known_instant_with_millis() {
let t = UNIX_EPOCH + Duration::from_millis(1_560_067_692_517);
assert_eq!(system_time_to_rfc3339(t), "2019-06-09T08:08:12.517Z");
}
}