1use crate::Error;
2use core::fmt::NumBuffer;
3use std::fmt::{self, Display};
4use std::str::FromStr;
5use std::time::Duration as StdDuration;
6
7#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
26pub struct Duration {
27 nanoseconds: i64,
28}
29
30pub(crate) const TOKEN: &str = "$soml::Duration";
34
35const UNITS: [&str; 6] = ["h", "m", "s", "ms", "us", "ns"];
39
40impl Duration {
41 pub const MIN: Self = Self::from_nanoseconds(i64::MIN);
45
46 pub const MAX: Self = Self::from_nanoseconds(i64::MAX);
50
51 pub const ZERO: Self = Self::from_nanoseconds(0);
55
56 #[must_use]
60 pub const fn from_nanoseconds(nanoseconds: i64) -> Self {
61 Self { nanoseconds }
62 }
63
64 #[must_use]
68 pub const fn nanoseconds(self) -> i64 {
69 self.nanoseconds
70 }
71
72 #[must_use]
76 pub const fn is_negative(self) -> bool {
77 self.nanoseconds < 0
78 }
79
80 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 let mut total: u64 = 0;
102 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 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 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 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
236fn integer_digits(digits: &[u8]) -> u64 {
240 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
251pub(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 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
281impl 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 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
332impl 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 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 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");