Skip to main content

fontoxide_misc/
time_tools.rs

1//! Port of `fontTools.misc.timeTools`: OpenType timestamps (seconds since
2//! 1904-01-01 00:00:00 UTC).
3
4/// Seconds from 1970-01-01 to 1904-01-01 (`epoch_diff`); negative.
5pub const EPOCH_DIFF: i64 = -2_082_844_800;
6
7const DAYNAMES: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
8const MONTHNAMES: [&str; 12] = [
9	"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
10];
11
12/// A broken-down UTC time, like Python's `time.struct_time` from `gmtime()`.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Tm {
15	/// Full year, e.g. 1970.
16	pub year: i64,
17	/// 1–12.
18	pub month: u32,
19	/// 1–31.
20	pub day: u32,
21	/// 0–23.
22	pub hour: u32,
23	/// 0–59.
24	pub minute: u32,
25	/// 0–59.
26	pub second: u32,
27	/// 0 = Monday … 6 = Sunday.
28	pub weekday: u32,
29}
30
31/// Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm).
32fn civil_from_days(z: i64) -> (i64, u32, u32) {
33	let z = z + 719_468;
34	let era = z.div_euclid(146_097);
35	let doe = z.rem_euclid(146_097);
36	let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
37	let y = yoe + era * 400;
38	let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
39	let mp = (5 * doy + 2) / 153;
40	let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
41	let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
42	(if m <= 2 { y + 1 } else { y }, m, d)
43}
44
45/// A civil date to days since 1970-01-01.
46fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
47	let y = if m <= 2 { y - 1 } else { y };
48	let era = y.div_euclid(400);
49	let yoe = y.rem_euclid(400);
50	let m = m as i64;
51	let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d as i64 - 1;
52	let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
53	era * 146_097 + doe - 719_468
54}
55
56/// `time.gmtime(seconds)`.
57pub fn gmtime(seconds: i64) -> Tm {
58	let days = seconds.div_euclid(86_400);
59	let secs = seconds.rem_euclid(86_400) as u32;
60	let (year, month, day) = civil_from_days(days);
61	Tm {
62		year,
63		month,
64		day,
65		hour: secs / 3600,
66		minute: secs / 60 % 60,
67		second: secs % 60,
68		// 1970-01-01 was a Thursday.
69		weekday: (days + 3).rem_euclid(7) as u32,
70	}
71}
72
73/// Formats a time as `"Thu Jan  1 00:00:00 1970"` (`asctime`).
74pub fn asctime(t: &Tm) -> String {
75	format!(
76		"{} {} {:>2} {:02}:{:02}:{:02} {}",
77		DAYNAMES[t.weekday as usize],
78		MONTHNAMES[(t.month - 1) as usize],
79		t.day,
80		t.hour,
81		t.minute,
82		t.second,
83		// strftime("%Y") pads to at least four digits.
84		if t.year >= 0 {
85			format!("{:04}", t.year)
86		} else {
87			t.year.to_string()
88		}
89	)
90}
91
92/// Formats an OpenType timestamp (`timestampToString`). Timestamps before the Unix
93/// epoch are clamped to it, as fontTools does.
94pub fn timestamp_to_string(value: i64) -> String {
95	asctime(&gmtime(value.saturating_add(EPOCH_DIFF).max(0)))
96}
97
98/// Parses a timestamp written by [`timestamp_to_string`] (`timestampFromString`).
99/// Returns `None` if the string is malformed or the weekday is inconsistent.
100pub fn timestamp_from_string(value: &str) -> Option<i64> {
101	let head = value.get(..7)?;
102	let mut parts = head.split_whitespace();
103	let wkday = parts.next()?;
104	let month = parts.next()?;
105	if parts.next().is_some() {
106		return None;
107	}
108	// The rest is " %d %H:%M:%S %Y"; strptime allows flexible whitespace.
109	let mut rest = value[7..].split_whitespace();
110	let day: u32 = rest.next()?.parse().ok()?;
111	let mut hms = rest.next()?.split(':');
112	let hour: u32 = hms.next()?.parse().ok()?;
113	let minute: u32 = hms.next()?.parse().ok()?;
114	let second: u32 = hms.next()?.parse().ok()?;
115	let year: i64 = rest.next()?.parse().ok()?;
116	if hms.next().is_some() || rest.next().is_some() {
117		return None;
118	}
119	let month = MONTHNAMES.iter().position(|m| *m == month)? as u32 + 1;
120	if !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 61 {
121		return None;
122	}
123	let days = days_from_civil(year, month, day);
124	if civil_from_days(days) != (year, month, day) {
125		return None;
126	}
127	let weekday = (days + 3).rem_euclid(7) as usize;
128	if DAYNAMES.iter().position(|d| *d == wkday)? != weekday {
129		return None;
130	}
131	let seconds = days * 86_400 + (hour * 3600 + minute * 60 + second) as i64;
132	Some(seconds - EPOCH_DIFF)
133}
134
135/// The clock set by [`set_clock`].
136static CLOCK: std::sync::RwLock<Option<fn() -> f64>> = std::sync::RwLock::new(None);
137
138/// Sets the clock of [`timestamp_now`], a function returning the seconds since the
139/// Unix epoch, in place of the system clock.
140///
141/// `std::time::SystemTime` is unavailable on `wasm32-unknown-unknown`, so set one
142/// there (for example from `js_sys::Date::now() / 1000.0`) before writing fonts
143/// whose `recalc_timestamp` is on.
144pub fn set_clock(clock: fn() -> f64) {
145	*CLOCK.write().unwrap_or_else(|e| e.into_inner()) = Some(clock);
146}
147
148/// The current time as an OpenType timestamp (`timestampNow`). Honors
149/// `SOURCE_DATE_EPOCH` for reproducible builds, then the clock of [`set_clock`];
150/// returns `None` if `SOURCE_DATE_EPOCH` is set but not an integer (fontTools
151/// raises `ValueError`), or if there is no clock (on `wasm32-unknown-unknown`
152/// without [`set_clock`]).
153pub fn timestamp_now() -> Option<i64> {
154	if let Ok(epoch) = std::env::var("SOURCE_DATE_EPOCH") {
155		return Some(crate::py::parse_int(&epoch)? as i64 - EPOCH_DIFF);
156	}
157	let clock = *CLOCK.read().unwrap_or_else(|e| e.into_inner());
158	let now = match clock {
159		Some(clock) => clock(),
160		None => system_time()?,
161	};
162	Some((now - EPOCH_DIFF as f64) as i64)
163}
164
165#[cfg(not(target_family = "wasm"))]
166fn system_time() -> Option<f64> {
167	Some(
168		std::time::SystemTime::now()
169			.duration_since(std::time::UNIX_EPOCH)
170			.map(|d| d.as_secs_f64())
171			.unwrap_or(0.0),
172	)
173}
174
175#[cfg(target_family = "wasm")]
176fn system_time() -> Option<f64> {
177	None
178}
179
180/// Converts a Unix timestamp to an OpenType timestamp (`timestampSinceEpoch`).
181pub fn timestamp_since_epoch(value: i64) -> i64 {
182	value - EPOCH_DIFF
183}
184
185#[cfg(test)]
186mod tests {
187	//! Port of Tests/misc/timeTools_test.py.
188
189	use super::*;
190
191	#[test]
192	fn test_asctime() {
193		assert_eq!(asctime(&gmtime(0)), "Thu Jan  1 00:00:00 1970");
194	}
195
196	#[test]
197	fn roundtrip() {
198		for ts in [2_082_844_800_i64, 3_000_000_000, 3_786_576_000, 0xFFFF_FFFF] {
199			let s = timestamp_to_string(ts);
200			assert_eq!(timestamp_from_string(&s), Some(ts), "{s}");
201		}
202		assert_eq!(timestamp_to_string(0), "Thu Jan  1 00:00:00 1970");
203		assert_eq!(
204			timestamp_to_string(3_786_576_000),
205			"Thu Dec 28 02:40:00 2023"
206		);
207		assert_eq!(timestamp_from_string("Fri Jan  1 00:00:00 1970"), None);
208		assert_eq!(gmtime(951_782_400).day, 29);
209	}
210
211	// test_source_date_epoch mutates the process environment, which is not
212	// thread-safe in Rust's test harness; the logic is covered by `timestamp_now`
213	// being a direct port.
214
215	/// No other test of this crate reads the clock, so setting it is safe.
216	#[test]
217	fn set_clock_overrides_system_time() {
218		if std::env::var_os("SOURCE_DATE_EPOCH").is_some() {
219			return;
220		}
221		set_clock(|| 1_000_000_000.5);
222		assert_eq!(timestamp_now(), Some(1_000_000_000 - EPOCH_DIFF));
223	}
224}