Skip to main content

soml/
duration.rs

1use crate::Error;
2use core::fmt::NumBuffer;
3use std::fmt::{self, Display};
4use std::str::FromStr;
5use std::time::Duration as StdDuration;
6
7/**
8A SOML duration: a signed length of time, as a whole number of nanoseconds in the `i64` range, which is about 292 years either way.
9
10Unlike `std::time::Duration`, it can be negative, so it is meant to be used qualified, as `soml::Duration`.
11
12`Display` writes the canonical form, in hours, minutes, and seconds with a fraction:
13
14```rust
15let duration: soml::Duration = "90m".parse()?;
16assert_eq!(duration.to_string(), "1h30m");
17
18let duration = soml::Duration::from_nanoseconds(-1_500_000_000);
19assert_eq!(duration.to_string(), "-1.5s");
20# Ok::<(), soml::Error>(())
21```
22
23With serde, it reads only from a SOML duration, not from a string, and it is written as a SOML duration. Other formats, such as JSON, see its canonical text.
24*/
25#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
26pub struct Duration {
27	nanoseconds: i64,
28}
29
30/**
31The name that tells the SOML serializer and deserializer that a newtype struct is a duration. Other formats treat a newtype struct as its content, so they see the canonical text.
32*/
33pub(crate) const TOKEN: &str = "$soml::Duration";
34
35/**
36The unit names in the order a duration must write them, for diagnostic suggestions.
37*/
38const UNITS: [&str; 6] = ["h", "m", "s", "ms", "us", "ns"];
39
40impl Duration {
41	/**
42	The most negative duration, `-9223372036854775808ns`.
43	*/
44	pub const MIN: Self = Self::from_nanoseconds(i64::MIN);
45
46	/**
47	The longest duration, `9223372036854775807ns`.
48	*/
49	pub const MAX: Self = Self::from_nanoseconds(i64::MAX);
50
51	/**
52	The zero duration, `0s`.
53	*/
54	pub const ZERO: Self = Self::from_nanoseconds(0);
55
56	/**
57	Creates a duration from a signed count of nanoseconds.
58	*/
59	#[must_use]
60	pub const fn from_nanoseconds(nanoseconds: i64) -> Self {
61		Self { nanoseconds }
62	}
63
64	/**
65	The signed count of nanoseconds.
66	*/
67	#[must_use]
68	pub const fn nanoseconds(self) -> i64 {
69		self.nanoseconds
70	}
71
72	/**
73	Whether the duration is less than zero.
74	*/
75	#[must_use]
76	pub const fn is_negative(self) -> bool {
77		self.nanoseconds < 0
78	}
79
80	/**
81	Reads a duration in SOML syntax, with the reason it is invalid as the error.
82
83	Every part is read before the value is checked, so a syntax error is reported before an error about the value, and it names the part it is about.
84	*/
85	pub(crate) fn parse(text: &str) -> Result<Self, String> {
86		let fail = |reason: &str| {
87			Err(format!(
88				"Invalid duration {}: {reason}",
89				crate::abbreviate(text, 40)
90			))
91		};
92		let bytes = text.as_bytes();
93		let is_negative = bytes.first() == Some(&b'-');
94		let mut index = usize::from(is_negative);
95
96		if index == bytes.len() {
97			return fail("a duration needs at least one part, as in 30s");
98		}
99		let mut previous_rank = None;
100		// The magnitude, which goes past the `i64` range only to be reported as out of range.
101		let mut total: u64 = 0;
102		// The fraction of the last part without trailing zeros, and that part's unit length. Only the last part may have one, so the value checks wait until every part is read.
103		let mut fraction: &[u8] = &[];
104		let mut unit_length: u64 = 0;
105
106		while index < bytes.len() {
107			let digits_end = crate::scalar::skip_integer_part(bytes, index);
108			let next = bytes.get(digits_end).copied();
109
110			if digits_end == index {
111				if bytes[index] == b'-' && bytes.get(index + 1).is_some_and(u8::is_ascii_digit) {
112					return fail("only the whole duration takes a sign, as in -1h30m");
113				}
114
115				if bytes[index] == b'+' {
116					return fail("a “+” sign is not allowed");
117				}
118
119				return fail(&format!(
120					"expected a number at “{}”",
121					crate::abbreviate(&text[index..], 10)
122				));
123			}
124
125			if bytes[index] == b'0'
126				&& next.is_some_and(|byte| byte.is_ascii_digit() || byte == b'_')
127			{
128				return fail("leading zeros are not allowed");
129			}
130
131			if next == Some(b'_') {
132				return fail("an underscore must be between two digits");
133			}
134
135			fraction = &[];
136			let mut unit_start = digits_end;
137
138			if next == Some(b'.') {
139				unit_start = crate::scalar::skip_digits(bytes, digits_end + 1, u8::is_ascii_digit);
140
141				if unit_start == digits_end + 1 {
142					return fail("a “.” must be followed by a digit");
143				}
144
145				if bytes.get(unit_start) == Some(&b'_') {
146					return fail("an underscore must be between two digits");
147				}
148
149				fraction = &bytes[digits_end + 1..unit_start];
150			}
151
152			let limit = bytes.len().min(unit_start + 11);
153			let unit_end = crate::scalar::run_end(&bytes[..limit], unit_start, |byte| {
154				byte.is_ascii_alphabetic()
155			});
156
157			let unit = &text[unit_start..unit_end];
158
159			let (rank, length) = match unit {
160				"h" => (0, 3_600_000_000_000),
161				"m" => (1, 60_000_000_000),
162				"s" => (2, 1_000_000_000),
163				"ms" => (3, 1_000_000),
164				"us" => (4, 1000),
165				"ns" => (5, 1),
166				_ => return fail(&describe_bad_unit(unit, text)),
167			};
168
169			if previous_rank.is_some_and(|previous| rank <= previous) {
170				return fail(
171					"the units are in the order h, m, s, ms, us, ns, and each appears at most once",
172				);
173			}
174
175			if next == Some(b'.') && bytes.get(unit_end).is_some_and(u8::is_ascii_digit) {
176				return fail("only the last part may have a fraction");
177			}
178
179			unit_length = length;
180			total = total.saturating_add(
181				integer_digits(&bytes[index..digits_end]).saturating_mul(unit_length),
182			);
183			index = unit_end;
184			previous_rank = Some(rank);
185		}
186
187		// Trailing zeros change nothing, and leaving them out keeps the arithmetic small however many there are.
188		let fraction = &fraction[..fraction
189			.iter()
190			.rposition(|&byte| byte != b'0' && byte != b'_')
191			.map_or(0, |last| last + 1)];
192		let fraction_digits = fraction
193			.iter()
194			.filter(|&&byte| byte != b'_')
195			.take(14)
196			.count();
197
198		// No unit has more than 13 factors of 2 or of 5, so more than 13 significant fraction digits is never a whole number of nanoseconds.
199		if fraction_digits > 13 {
200			return fail("it is not a whole number of nanoseconds");
201		}
202
203		if !fraction.is_empty() {
204			let scale = 10u128.pow(fraction_digits as u32);
205			let fraction_nanoseconds =
206				u128::from(integer_digits(fraction)) * u128::from(unit_length);
207
208			if !fraction_nanoseconds.is_multiple_of(scale) {
209				return fail("it is not a whole number of nanoseconds");
210			}
211
212			total = total.saturating_add((fraction_nanoseconds / scale) as u64);
213		}
214
215		if is_negative && total == 0 {
216			return fail("“-” is not allowed before zero, because zero has one spelling: 0s");
217		}
218
219		// Checked subtraction accepts the magnitude of `i64::MIN`, which is one more than `i64::MAX`.
220		let nanoseconds = if is_negative {
221			0i64.checked_sub_unsigned(total)
222		} else {
223			i64::try_from(total).ok()
224		};
225
226		let Some(nanoseconds) = nanoseconds else {
227			return fail(
228				"it is outside the 64-bit range of nanoseconds, about 292 years either way",
229			);
230		};
231
232		Ok(Self::from_nanoseconds(nanoseconds))
233	}
234}
235
236/**
237The value of decimal digits with optional underscores, which saturates past the `u64` range. Every caller treats a value that large as out of range.
238*/
239fn integer_digits(digits: &[u8]) -> u64 {
240	// Note: Not using a saturating fold because it would keep scanning digits after overflow.
241	digits
242		.iter()
243		.filter(|&&byte| byte != b'_')
244		.try_fold(0u64, |value, &byte| {
245			let (value, carry) = value.carrying_mul(10, u64::from(byte - b'0'));
246			(carry == 0).then_some(value)
247		})
248		.unwrap_or(u64::MAX)
249}
250
251/**
252Whether `unit` is a year unit in any case, such as `y` or `Years`, which a year not being a fixed length rules out.
253*/
254pub(crate) fn is_year_unit(unit: &[u8]) -> bool {
255	["y", "yr", "yrs", "year", "years"]
256		.iter()
257		.any(|name| name.as_bytes().eq_ignore_ascii_case(unit))
258}
259
260fn describe_bad_unit<'a>(unit: &'a str, text: &str) -> std::borrow::Cow<'a, str> {
261	match unit {
262		"" => "every number needs a unit: h, m, s, ms, us, or ns".into(),
263		"d" | "day" | "days" => "there is no day unit, because a day is not a fixed length. Write 24h for a fixed 24 hours".into(),
264		"w" | "week" | "weeks" => "there is no week unit, because a day is not a fixed length. Write 168h for a fixed 168 hours".into(),
265		_ if is_year_unit(unit.as_bytes()) => "there is no year unit, because a year is not a fixed length. Write 8760h for a fixed 365 days".into(),
266		"M" => {
267			// A number with `M` alone, as in `memory: 512M`, is more often a size than a duration, and `512m` would read as minutes.
268			let is_size = text.len() <= crate::scalar::MAX_DIAGNOSED_LENGTH && text.ends_with('M') && text[..text.len() - 1].bytes().all(|byte| byte.is_ascii_digit() || byte == b'_');
269			let size_hint = if is_size {
270				format!(". A size, such as 512M, is a string: '{}'", crate::abbreviate(text, 40))
271			} else {
272				String::new()
273			};
274			format!("there is no month unit, because a month is not a fixed length{size_hint}").into()
275		}
276		_ if let Some(name) = UNITS.iter().find(|name| name.eq_ignore_ascii_case(unit)) => format!("the units are lowercase: {name}").into(),
277		_ => format!("“{}” is not a unit. The units are h, m, s, ms, us, and ns, and a string must be quoted", crate::abbreviate(unit, 10)).into(),
278	}
279}
280
281/**
282Writes the canonical form: `-` when negative, then the hours, minutes, and seconds, each left out when zero, with the seconds' fraction written like an instant's. Zero is `0s`.
283*/
284impl Display for Duration {
285	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
286		const SECOND: u64 = 1_000_000_000;
287		let magnitude = self.nanoseconds.unsigned_abs();
288
289		if magnitude == 0 {
290			return formatter.write_str("0s");
291		}
292
293		if self.nanoseconds < 0 {
294			formatter.write_str("-")?;
295		}
296
297		let whole_seconds = magnitude / SECOND;
298		let hours = whole_seconds / 3600;
299		let minutes = whole_seconds / 60 % 60;
300		let seconds = whole_seconds % 60;
301		let nanoseconds = (magnitude % SECOND) as u32;
302
303		// The digits are written without `write!`, which is several times slower, as for an instant.
304		let mut digits = NumBuffer::new();
305
306		if hours > 0 {
307			formatter.write_str(hours.format_into(&mut digits))?;
308			formatter.write_str("h")?;
309		}
310
311		if minutes > 0 {
312			formatter.write_str(minutes.format_into(&mut digits))?;
313			formatter.write_str("m")?;
314		}
315
316		if seconds > 0 || nanoseconds > 0 {
317			formatter.write_str(seconds.format_into(&mut digits))?;
318			crate::instant::write_fraction(formatter, nanoseconds)?;
319			formatter.write_str("s")?;
320		}
321
322		Ok(())
323	}
324}
325
326impl fmt::Debug for Duration {
327	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328		write!(formatter, "Duration({self})")
329	}
330}
331
332/**
333Reads a duration in SOML syntax.
334
335```rust
336let duration: soml::Duration = "1.5s".parse()?;
337assert_eq!(duration.nanoseconds(), 1_500_000_000);
338
339assert!("1d".parse::<soml::Duration>().is_err());
340# Ok::<(), soml::Error>(())
341```
342*/
343impl FromStr for Duration {
344	type Err = Error;
345
346	fn from_str(text: &str) -> Result<Self, Error> {
347		Self::parse(text).map_err(Error::syntax)
348	}
349}
350
351impl TryFrom<StdDuration> for Duration {
352	type Error = Error;
353
354	/**
355	Fails when the duration is longer than `i64::MAX` nanoseconds, about 292 years.
356	*/
357	fn try_from(duration: StdDuration) -> Result<Self, Error> {
358		i64::try_from(duration.as_nanos())
359			.map(Self::from_nanoseconds)
360			.map_err(|_| {
361				Error::data(format!(
362					"The duration {duration:?} is outside the SOML range of about 292 years"
363				))
364			})
365	}
366}
367
368impl TryFrom<Duration> for StdDuration {
369	type Error = Error;
370
371	/**
372	Fails when the duration is negative, because a `std::time::Duration` cannot be.
373	*/
374	fn try_from(duration: Duration) -> Result<Self, Error> {
375		u64::try_from(duration.nanoseconds)
376			.map(Self::from_nanos)
377			.map_err(|_| {
378				Error::data(format!(
379					"The duration {duration} is negative, which a std::time::Duration cannot be"
380				))
381			})
382	}
383}
384
385serde_temporal_scalar!(Duration, "a duration");