1use std::time::{SystemTime, UNIX_EPOCH};
7
8use pltrs_codec::png;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct Timestamp(pub i64);
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16struct Civil {
17 year: i64,
18 month: u32,
19 day: u32,
20 hour: u32,
21 minute: u32,
22 second: u32,
23 weekday: usize,
25}
26
27const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
28const MONTHS: [&str; 12] = [
29 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
30];
31
32impl Timestamp {
33 pub fn now() -> Self {
35 let seconds = match SystemTime::now().duration_since(UNIX_EPOCH) {
36 Ok(elapsed) => elapsed.as_secs() as i64,
37 Err(before) => -(before.duration().as_secs() as i64),
38 };
39 Self(seconds)
40 }
41
42 pub fn source_date_or_now() -> Self {
45 std::env::var("SOURCE_DATE_EPOCH")
46 .ok()
47 .and_then(|value| value.trim().parse().ok())
48 .map_or_else(Self::now, Self)
49 }
50
51 fn civil(self) -> Civil {
53 let days = self.0.div_euclid(86_400);
54 let secs = self.0.rem_euclid(86_400) as u32;
55 let z = days + 719_468;
56 let era = z.div_euclid(146_097);
57 let doe = z.rem_euclid(146_097);
58 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
59 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
60 let mp = (5 * doy + 2) / 153;
61 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
62 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
63 let year = yoe + era * 400 + i64::from(month <= 2);
64 Civil {
65 year,
66 month,
67 day,
68 hour: secs / 3600,
69 minute: secs / 60 % 60,
70 second: secs % 60,
71 weekday: (days + 3).rem_euclid(7) as usize,
73 }
74 }
75
76 pub fn iso8601(self) -> String {
79 let c = self.civil();
80 format!(
81 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}+00:00",
82 c.year, c.month, c.day, c.hour, c.minute, c.second
83 )
84 }
85
86 pub fn pdf(self) -> String {
88 let c = self.civil();
89 format!(
90 "D:{:04}{:02}{:02}{:02}{:02}{:02}Z",
91 c.year, c.month, c.day, c.hour, c.minute, c.second
92 )
93 }
94
95 pub fn ctime(self) -> String {
98 let c = self.civil();
99 format!(
100 "{} {} {:02} {:02}:{:02}:{:02} {}",
101 WEEKDAYS[c.weekday],
102 MONTHS[c.month as usize - 1],
103 c.day,
104 c.hour,
105 c.minute,
106 c.second,
107 c.year
108 )
109 }
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
115pub enum Trapped {
116 True,
118 False,
120 Unknown,
122}
123
124impl Trapped {
125 pub const fn name(self) -> &'static str {
127 match self {
128 Self::True => "True",
129 Self::False => "False",
130 Self::Unknown => "Unknown",
131 }
132 }
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct Metadata {
143 pub title: Option<String>,
145 pub creator: Option<String>,
147 pub producer: Option<String>,
149 pub date: Option<Timestamp>,
151 pub author: Option<String>,
153 pub subject: Option<String>,
155 pub keywords: Option<String>,
157 pub modified: Option<Timestamp>,
159 pub trapped: Option<Trapped>,
161 pub pdf_info: Option<Vec<(String, Vec<u8>)>>,
166 pub svg: SvgMetadata,
168 pub png: PngMetadata,
170}
171
172impl Default for Metadata {
173 fn default() -> Self {
177 let version = env!("CARGO_PKG_VERSION");
178 Self {
179 creator: Some(format!("pltrs v{version}")),
180 producer: Some(format!("pltrs v{version}")),
181 date: Some(Timestamp::source_date_or_now()),
182 svg: SvgMetadata::default(),
183 png: PngMetadata::default(),
184 ..Self::none()
185 }
186 }
187}
188
189impl Metadata {
190 pub const fn none() -> Self {
192 Self {
193 title: None,
194 creator: None,
195 producer: None,
196 date: None,
197 author: None,
198 subject: None,
199 keywords: None,
200 modified: None,
201 trapped: None,
202 pdf_info: None,
203 svg: SvgMetadata::none(),
204 png: PngMetadata::none(),
205 }
206 }
207}
208
209#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct SvgMetadata {
215 pub resource_type: Option<String>,
217 pub format: Option<String>,
219 pub coverage: Option<String>,
221 pub description: Option<String>,
223 pub identifier: Option<String>,
225 pub language: Option<String>,
227 pub relation: Option<String>,
229 pub source: Option<String>,
231 pub creators: Vec<String>,
234 pub contributors: Vec<String>,
236 pub publishers: Vec<String>,
238 pub rights: Vec<String>,
240 pub keywords: Vec<String>,
243 pub dates: Vec<String>,
246}
247
248impl Default for SvgMetadata {
249 fn default() -> Self {
251 Self {
252 resource_type: Some("http://purl.org/dc/dcmitype/StillImage".to_owned()),
253 format: Some("image/svg+xml".to_owned()),
254 ..Self::none()
255 }
256 }
257}
258
259impl SvgMetadata {
260 pub const fn none() -> Self {
262 Self {
263 resource_type: None,
264 format: None,
265 coverage: None,
266 description: None,
267 identifier: None,
268 language: None,
269 relation: None,
270 source: None,
271 creators: Vec::new(),
272 contributors: Vec::new(),
273 publishers: Vec::new(),
274 rights: Vec::new(),
275 keywords: Vec::new(),
276 dates: Vec::new(),
277 }
278 }
279}
280
281pub const PNG_SOFTWARE: &str = concat!("pltrs v", env!("CARGO_PKG_VERSION"));
284
285#[derive(Clone, Debug, PartialEq, Eq)]
304pub struct PngMetadata {
305 entries: Vec<(String, String)>,
307}
308
309impl Default for PngMetadata {
310 fn default() -> Self {
313 Self::none().with("Software", PNG_SOFTWARE)
314 }
315}
316
317impl PngMetadata {
318 pub const fn none() -> Self {
320 Self {
321 entries: Vec::new(),
322 }
323 }
324
325 #[must_use]
329 pub fn with(mut self, keyword: impl Into<String>, text: impl Into<String>) -> Self {
330 let (keyword, text) = (keyword.into(), text.into());
331 match self.entries.iter_mut().find(|(key, _)| *key == keyword) {
332 Some(entry) => entry.1 = text,
333 None => self.entries.push((keyword, text)),
334 }
335 self
336 }
337
338 #[must_use]
341 pub fn without(mut self, keyword: &str) -> Self {
342 self.entries.retain(|(key, _)| key != keyword);
343 self
344 }
345
346 pub fn entries(&self) -> &[(String, String)] {
348 &self.entries
349 }
350
351 pub fn apply_to(&self, encoder: png::Encoder) -> png::Encoder {
353 self.entries
354 .iter()
355 .fold(encoder, |encoder, (keyword, text)| {
356 encoder.text(keyword, text)
357 })
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 #[test]
366 fn formats_dates() {
367 let t = Timestamp(1_792_222_020);
368 assert_eq!(t.iso8601(), "2026-10-17T07:27:00+00:00");
369 assert_eq!(t.pdf(), "D:20261017072700Z");
370 assert_eq!(t.ctime(), "Sat Oct 17 07:27:00 2026");
371 assert_eq!(Timestamp(0).ctime(), "Thu Jan 01 00:00:00 1970");
372 assert_eq!(Timestamp(-1).iso8601(), "1969-12-31T23:59:59+00:00");
373 assert_eq!(Timestamp(951_782_400).pdf(), "D:20000229000000Z");
374 }
375
376 #[test]
377 fn defaults_name_pltrs() {
378 let metadata = Metadata::default();
379 assert!(metadata.creator.is_some_and(|c| c.starts_with("pltrs")));
380 assert_eq!(Metadata::none().date, None);
381 }
382
383 #[test]
384 fn png_entries_merge_like_matplotlib_dictionaries() {
385 let png = PngMetadata::default()
386 .with("Title", "a")
387 .with("Software", "b")
388 .with("Title", "c");
389 let entries: Vec<(&str, &str)> = png
390 .entries()
391 .iter()
392 .map(|(key, text)| (key.as_str(), text.as_str()))
393 .collect();
394 assert_eq!(entries, [("Software", "b"), ("Title", "c")]);
395 let emptied = png.without("Software").without("Title");
396 assert_eq!(emptied.entries(), []);
397 assert_eq!(Metadata::none().png, PngMetadata::none());
398 assert_eq!(PngMetadata::default().entries()[0].1, PNG_SOFTWARE);
399 }
400}