use std::time::{SystemTime, UNIX_EPOCH};
use pltrs_codec::png;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Civil {
year: i64,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
weekday: usize,
}
const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
impl Timestamp {
pub fn now() -> Self {
let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(elapsed) => elapsed.as_secs() as i64,
Err(before) => -(before.duration().as_secs() as i64),
};
Self(seconds)
}
pub fn source_date_or_now() -> Self {
std::env::var("SOURCE_DATE_EPOCH")
.ok()
.and_then(|value| value.trim().parse().ok())
.map_or_else(Self::now, Self)
}
fn civil(self) -> Civil {
let days = self.0.div_euclid(86_400);
let secs = self.0.rem_euclid(86_400) as u32;
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
Civil {
year,
month,
day,
hour: secs / 3600,
minute: secs / 60 % 60,
second: secs % 60,
weekday: (days + 3).rem_euclid(7) as usize,
}
}
pub fn iso8601(self) -> String {
let c = self.civil();
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}+00:00",
c.year, c.month, c.day, c.hour, c.minute, c.second
)
}
pub fn pdf(self) -> String {
let c = self.civil();
format!(
"D:{:04}{:02}{:02}{:02}{:02}{:02}Z",
c.year, c.month, c.day, c.hour, c.minute, c.second
)
}
pub fn ctime(self) -> String {
let c = self.civil();
format!(
"{} {} {:02} {:02}:{:02}:{:02} {}",
WEEKDAYS[c.weekday],
MONTHS[c.month as usize - 1],
c.day,
c.hour,
c.minute,
c.second,
c.year
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Trapped {
True,
False,
Unknown,
}
impl Trapped {
pub const fn name(self) -> &'static str {
match self {
Self::True => "True",
Self::False => "False",
Self::Unknown => "Unknown",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Metadata {
pub title: Option<String>,
pub creator: Option<String>,
pub producer: Option<String>,
pub date: Option<Timestamp>,
pub author: Option<String>,
pub subject: Option<String>,
pub keywords: Option<String>,
pub modified: Option<Timestamp>,
pub trapped: Option<Trapped>,
pub pdf_info: Option<Vec<(String, Vec<u8>)>>,
pub svg: SvgMetadata,
pub png: PngMetadata,
}
impl Default for Metadata {
fn default() -> Self {
let version = env!("CARGO_PKG_VERSION");
Self {
creator: Some(format!("pltrs v{version}")),
producer: Some(format!("pltrs v{version}")),
date: Some(Timestamp::source_date_or_now()),
svg: SvgMetadata::default(),
png: PngMetadata::default(),
..Self::none()
}
}
}
impl Metadata {
pub const fn none() -> Self {
Self {
title: None,
creator: None,
producer: None,
date: None,
author: None,
subject: None,
keywords: None,
modified: None,
trapped: None,
pdf_info: None,
svg: SvgMetadata::none(),
png: PngMetadata::none(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SvgMetadata {
pub resource_type: Option<String>,
pub format: Option<String>,
pub coverage: Option<String>,
pub description: Option<String>,
pub identifier: Option<String>,
pub language: Option<String>,
pub relation: Option<String>,
pub source: Option<String>,
pub creators: Vec<String>,
pub contributors: Vec<String>,
pub publishers: Vec<String>,
pub rights: Vec<String>,
pub keywords: Vec<String>,
pub dates: Vec<String>,
}
impl Default for SvgMetadata {
fn default() -> Self {
Self {
resource_type: Some("http://purl.org/dc/dcmitype/StillImage".to_owned()),
format: Some("image/svg+xml".to_owned()),
..Self::none()
}
}
}
impl SvgMetadata {
pub const fn none() -> Self {
Self {
resource_type: None,
format: None,
coverage: None,
description: None,
identifier: None,
language: None,
relation: None,
source: None,
creators: Vec::new(),
contributors: Vec::new(),
publishers: Vec::new(),
rights: Vec::new(),
keywords: Vec::new(),
dates: Vec::new(),
}
}
}
pub const PNG_SOFTWARE: &str = concat!("pltrs v", env!("CARGO_PKG_VERSION"));
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PngMetadata {
entries: Vec<(String, String)>,
}
impl Default for PngMetadata {
fn default() -> Self {
Self::none().with("Software", PNG_SOFTWARE)
}
}
impl PngMetadata {
pub const fn none() -> Self {
Self {
entries: Vec::new(),
}
}
#[must_use]
pub fn with(mut self, keyword: impl Into<String>, text: impl Into<String>) -> Self {
let (keyword, text) = (keyword.into(), text.into());
match self.entries.iter_mut().find(|(key, _)| *key == keyword) {
Some(entry) => entry.1 = text,
None => self.entries.push((keyword, text)),
}
self
}
#[must_use]
pub fn without(mut self, keyword: &str) -> Self {
self.entries.retain(|(key, _)| key != keyword);
self
}
pub fn entries(&self) -> &[(String, String)] {
&self.entries
}
pub fn apply_to(&self, encoder: png::Encoder) -> png::Encoder {
self.entries
.iter()
.fold(encoder, |encoder, (keyword, text)| {
encoder.text(keyword, text)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_dates() {
let t = Timestamp(1_792_222_020);
assert_eq!(t.iso8601(), "2026-10-17T07:27:00+00:00");
assert_eq!(t.pdf(), "D:20261017072700Z");
assert_eq!(t.ctime(), "Sat Oct 17 07:27:00 2026");
assert_eq!(Timestamp(0).ctime(), "Thu Jan 01 00:00:00 1970");
assert_eq!(Timestamp(-1).iso8601(), "1969-12-31T23:59:59+00:00");
assert_eq!(Timestamp(951_782_400).pdf(), "D:20000229000000Z");
}
#[test]
fn defaults_name_pltrs() {
let metadata = Metadata::default();
assert!(metadata.creator.is_some_and(|c| c.starts_with("pltrs")));
assert_eq!(Metadata::none().date, None);
}
#[test]
fn png_entries_merge_like_matplotlib_dictionaries() {
let png = PngMetadata::default()
.with("Title", "a")
.with("Software", "b")
.with("Title", "c");
let entries: Vec<(&str, &str)> = png
.entries()
.iter()
.map(|(key, text)| (key.as_str(), text.as_str()))
.collect();
assert_eq!(entries, [("Software", "b"), ("Title", "c")]);
let emptied = png.without("Software").without("Title");
assert_eq!(emptied.entries(), []);
assert_eq!(Metadata::none().png, PngMetadata::none());
assert_eq!(PngMetadata::default().entries()[0].1, PNG_SOFTWARE);
}
}