jiff/fmt/friendly/mod.rs
1/*!
2A bespoke but easy to read format for [`Span`](crate::Span) and
3[`SignedDuration`](crate::SignedDuration).
4
5The "friendly" duration format is meant to be an alternative to [Temporal's
6ISO 8601 duration format](super::temporal) that is both easier to read and can
7losslessly serialize and deserialize all `Span` values.
8
9Here are a variety of examples showing valid friendly durations for `Span`:
10
11```
12use jiff::{Span, ToSpan};
13
14let spans = [
15 ("40d", 40.days()),
16 ("40 days", 40.days()),
17 ("1y1d", 1.year().days(1)),
18 ("1yr 1d", 1.year().days(1)),
19 ("3d4h59m", 3.days().hours(4).minutes(59)),
20 ("3 days, 4 hours, 59 minutes", 3.days().hours(4).minutes(59)),
21 ("3d 4h 59m", 3.days().hours(4).minutes(59)),
22 ("2h30m", 2.hours().minutes(30)),
23 ("2h 30m", 2.hours().minutes(30)),
24 ("1mo", 1.month()),
25 ("1w", 1.week()),
26 ("1 week", 1.week()),
27 ("1w4d", 1.week().days(4)),
28 ("1 wk 4 days", 1.week().days(4)),
29 ("1m", 1.minute()),
30 ("0.0021s", 2.milliseconds().microseconds(100)),
31 ("0s", 0.seconds()),
32 ("0d", 0.seconds()),
33 ("0 days", 0.seconds()),
34 ("3 mins 34s 123ms", 3.minutes().seconds(34).milliseconds(123)),
35 ("3 mins 34.123 secs", 3.minutes().seconds(34).milliseconds(123)),
36 ("3 mins 34,123s", 3.minutes().seconds(34).milliseconds(123)),
37 (
38 "1y1mo1d1h1m1.1s",
39 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
40 ),
41 (
42 "1yr 1mo 1day 1hr 1min 1.1sec",
43 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
44 ),
45 (
46 "1 year, 1 month, 1 day, 1 hour, 1 minute 1.1 seconds",
47 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
48 ),
49 (
50 "1 year, 1 month, 1 day, 01:01:01.1",
51 1.year().months(1).days(1).hours(1).minutes(1).seconds(1).milliseconds(100),
52 ),
53];
54for (string, span) in spans {
55 let parsed: Span = string.parse()?;
56 assert_eq!(
57 span.fieldwise(),
58 parsed.fieldwise(),
59 "result of parsing {string:?}",
60 );
61}
62
63# Ok::<(), Box<dyn std::error::Error>>(())
64```
65
66Note that for a `SignedDuration`, only units up to hours are supported. If you
67need to support bigger units, then you'll need to convert it to a `Span` before
68printing to the friendly format (or parse into a `Span` and then convert to a
69`SignedDuration`).
70
71# Integration points
72
73While this module can of course be used to parse and print durations in the
74friendly format, in most cases, you don't have to. Namely, it is already
75integrated into the `Span` and `SignedDuration` types.
76
77For example, the friendly format can be used by invoking the "alternate"
78format when using the `std::fmt::Display` trait implementation:
79
80```
81use jiff::{SignedDuration, ToSpan};
82
83let span = 2.months().days(35).hours(2).minutes(30);
84assert_eq!(format!("{span}"), "P2M35DT2H30M"); // ISO 8601
85assert_eq!(format!("{span:#}"), "2mo 35d 2h 30m"); // "friendly"
86
87let sdur = SignedDuration::new(2 * 60 * 60 + 30 * 60, 123_456_789);
88assert_eq!(format!("{sdur}"), "PT2H30M0.123456789S"); // ISO 8601
89assert_eq!(format!("{sdur:#}"), "2h 30m 123ms 456µs 789ns"); // "friendly"
90```
91
92Both `Span` and `SignedDuration` use the "friendly" format for its
93`std::fmt::Debug` trait implementation:
94
95```
96use jiff::{SignedDuration, ToSpan};
97
98let span = 2.months().days(35).hours(2).minutes(30);
99assert_eq!(format!("{span:?}"), "2mo 35d 2h 30m");
100
101let sdur = SignedDuration::new(2 * 60 * 60 + 30 * 60, 123_456_789);
102assert_eq!(format!("{sdur:?}"), "2h 30m 123ms 456µs 789ns");
103```
104
105Both `Span` and `SignedDuration` support parsing the ISO 8601 _and_ friendly
106formats via its `std::str::FromStr` trait:
107
108```
109use jiff::{SignedDuration, Span, ToSpan};
110
111let expected = 2.months().days(35).hours(2).minutes(30);
112let span: Span = "2 months, 35 days, 02:30:00".parse()?;
113assert_eq!(span, expected.fieldwise());
114let span: Span = "P2M35DT2H30M".parse()?;
115assert_eq!(span, expected.fieldwise());
116
117let expected = SignedDuration::new(2 * 60 * 60 + 30 * 60, 123_456_789);
118let sdur: SignedDuration = "2h 30m 0,123456789s".parse()?;
119assert_eq!(sdur, expected);
120let sdur: SignedDuration = "PT2h30m0.123456789s".parse()?;
121assert_eq!(sdur, expected);
122
123# Ok::<(), Box<dyn std::error::Error>>(())
124```
125
126If you need to parse _only_ the friendly format, then that would be a good use
127case for using [`SpanParser`] in this module.
128
129Finally, when the `serde` crate feature is enabled, the friendly format is
130automatically supported via the `serde::Deserialize` trait implementation, just
131like for the `std::str::FromStr` trait above. However, for `serde::Serialize`,
132both types use ISO 8601. In order to serialize the friendly format,
133you'll need to write your own serialization function or use one of the
134[`fmt::serde`](crate::fmt::serde) helpers provided by Jiff. For example:
135
136```
137use jiff::{ToSpan, Span};
138
139#[derive(Debug, serde::Deserialize, serde::Serialize)]
140struct Record {
141 #[serde(
142 serialize_with = "jiff::fmt::serde::span::friendly::compact::required"
143 )]
144 span: Span,
145}
146
147let json = r#"{"span":"1 year 2 months 36 hours 1100ms"}"#;
148let got: Record = serde_json::from_str(&json)?;
149assert_eq!(
150 got.span.fieldwise(),
151 1.year().months(2).hours(36).milliseconds(1100),
152);
153
154let expected = r#"{"span":"1y 2mo 36h 1100ms"}"#;
155assert_eq!(serde_json::to_string(&got).unwrap(), expected);
156
157# Ok::<(), Box<dyn std::error::Error>>(())
158```
159
160The ISO 8601 format is used by default since it is part of a standard and is
161more widely accepted. That is, if you need an interoperable interchange format,
162then ISO 8601 is probably the right choice.
163
164# Rounding
165
166The printer in this module has no options for rounding. Instead, it is intended
167for users to round a [`Span`](crate::Span) first, and then print it. The idea
168is that printing a `Span` is a relatively "dumb" operation that just emits
169whatever units are non-zero in the `Span`. This is possible with a `Span`
170because it represents each unit distinctly. (With a [`std::time::Duration`] or
171a [`jiff::SignedDuration`](crate::SignedDuration), more functionality would
172need to be coupled with the printing logic to achieve a similar result.)
173
174For example, if you want to print the duration since someone posted a comment
175to an English speaking end user, precision below one half hour might be "too
176much detail." You can remove this by rounding the `Span` to the nearest half
177hour before printing:
178
179```
180use jiff::{civil, RoundMode, Unit, ZonedDateTimeDifference};
181
182let commented_at = civil::date(2024, 8, 1)
183 .at(19, 29, 13, 123_456_789)
184 .in_tz("America/New_York")?;
185let now = civil::date(2024, 12, 26)
186 .at(12, 49, 0, 0)
187 .in_tz("America/New_York")?;
188
189// The default, with units permitted up to years.
190let span = now.since((Unit::Year, &commented_at))?;
191assert_eq!(format!("{span:#}"), "4mo 24d 17h 19m 46s 876ms 543µs 211ns");
192
193// The same subtraction, but with more options to control
194// rounding the result. We could also do this with `Span::round`
195// directly by providing `now` as our relative zoned datetime.
196let rounded = now.since(
197 ZonedDateTimeDifference::new(&commented_at)
198 .smallest(Unit::Minute)
199 .largest(Unit::Year)
200 .mode(RoundMode::HalfExpand)
201 .increment(30),
202)?;
203assert_eq!(format!("{rounded:#}"), "4mo 24d 17h 30m");
204
205# Ok::<(), Box<dyn std::error::Error>>(())
206```
207
208# Comparison with the [`humantime`] crate
209
210To a first approximation, Jiff should cover all `humantime` use cases,
211including [`humantime-serde`] for serialization support.
212
213To a second approximation, it was a design point of the friendly format to be
214mostly interoperable with what `humantime` supports. For example, any duration
215string formatted by `humantime` at time of writing is also a valid friendly
216duration:
217
218```
219use std::time::Duration;
220
221use jiff::{Span, ToSpan};
222
223// Just a duration that includes as many unit designator labels as possible.
224let dur = Duration::new(
225 2 * 31_557_600 + 1 * 2_630_016 + 15 * 86400 + 5 * 3600 + 59 * 60 + 1,
226 123_456_789,
227);
228let formatted = humantime::format_duration(dur).to_string();
229assert_eq!(formatted, "2years 1month 15days 5h 59m 1s 123ms 456us 789ns");
230
231let span: Span = formatted.parse()?;
232let expected =
233 2.years()
234 .months(1)
235 .days(15)
236 .hours(5)
237 .minutes(59)
238 .seconds(1)
239 .milliseconds(123)
240 .microseconds(456)
241 .nanoseconds(789);
242assert_eq!(span, expected.fieldwise());
243
244# Ok::<(), Box<dyn std::error::Error>>(())
245```
246
247The above somewhat relies on the implementation details of `humantime`. Namely,
248not everything parseable by `humantime` is also parseable by the friendly
249format (and vice versa). For example, `humantime` parses `M` as a label for
250months, but the friendly format specifically eschews `M` because of its
251confusability with minutes:
252
253```
254use std::time::Duration;
255
256let dur = humantime::parse_duration("1M")?;
257// The +38,016 is because `humantime` assigns 30.44 24-hour days to all months.
258assert_eq!(dur, Duration::new(30 * 24 * 60 * 60 + 38_016, 0));
259
260// In contrast, Jiff will reject `1M`:
261assert_eq!(
262 "1M".parse::<jiff::Span>().unwrap_err().to_string(),
263 "failed to parse input in the \"friendly\" duration format: \
264 expected to find unit designator suffix \
265 (e.g., `years` or `secs`) after parsing integer",
266);
267
268# Ok::<(), Box<dyn std::error::Error>>(())
269```
270
271In the other direction, Jiff's default formatting for the friendly duration
272isn't always parsable by `humantime`. This is because, for example, depending
273on the configuration, Jiff may use `mo` and `mos` for months, and `µs` for
274microseconds, none of which are supported by `humantime`. If you need it, to
275ensure `humantime` can parse a Jiff formatted friendly duration, Jiff provides
276a special mode that attempts compatibility with `humantime`:
277
278```
279use jiff::{fmt::friendly::{Designator, SpanPrinter}, ToSpan};
280
281
282let span =
283 2.years()
284 .months(1)
285 .days(15)
286 .hours(5)
287 .minutes(59)
288 .seconds(1)
289 .milliseconds(123)
290 .microseconds(456)
291 .nanoseconds(789);
292
293let printer = SpanPrinter::new().designator(Designator::HumanTime);
294assert_eq!(
295 printer.span_to_string(&span),
296 "2y 1month 15d 5h 59m 1s 123ms 456us 789ns",
297);
298```
299
300It's hard to provide solid guarantees here because `humantime`'s behavior could
301change, but at time of writing, `humantime` has not changed much in quite a
302long time (its last release is almost 4 years ago at time of writing). So the
303current behavior is likely pretty safe to rely upon.
304
305More generally, the friendly format is more flexible than what `humantime`
306supports. For example, the friendly format incorporates `HH:MM:SS` and
307fractional time units. It also supports more unit labels and permits commas
308to separate units.
309
310```
311use jiff::SignedDuration;
312
313// 10 hours and 30 minutes
314let expected = SignedDuration::new(10 * 60 * 60 + 30 * 60, 0);
315assert_eq!(expected, "10h30m".parse()?);
316assert_eq!(expected, "10hrs 30mins".parse()?);
317assert_eq!(expected, "10 hours 30 minutes".parse()?);
318assert_eq!(expected, "10 hours, 30 minutes".parse()?);
319assert_eq!(expected, "10:30:00".parse()?);
320assert_eq!(expected, "10.5 hours".parse()?);
321
322# Ok::<(), Box<dyn std::error::Error>>(())
323```
324
325Finally, it's important to point out that `humantime` only supports parsing
326variable width units like years, months and days by virtue of assigning fixed
327static values to them that aren't always correct. In contrast, Jiff always
328gets this right and specifically prevents you from getting it wrong.
329
330To begin, Jiff returns an error if you try to parse a varying unit into a
331[`SignedDuration`](crate::SignedDuration):
332
333```
334use jiff::SignedDuration;
335
336// works fine
337assert_eq!(
338 "1 hour".parse::<SignedDuration>().unwrap(),
339 SignedDuration::from_hours(1),
340);
341// Jiff is saving you from doing something wrong
342assert_eq!(
343 "1 day".parse::<SignedDuration>().unwrap_err().to_string(),
344 "failed to parse input in the \"friendly\" duration format: \
345 parsing calendar units (days in this case) in this context \
346 is not supported (perhaps try parsing into a `jiff::Span` instead)",
347);
348```
349
350As the error message suggests, parsing into a [`Span`](crate::Span) works fine:
351
352```
353use jiff::Span;
354
355assert_eq!("1 day".parse::<Span>().unwrap(), Span::new().days(1).fieldwise());
356```
357
358Jiff has this behavior because it's not possible to determine, in general,
359how long "1 day" (or "1 month" or "1 year") is without a reference date.
360Since a `SignedDuration` (along with a [`std::time::Duration`]) does not
361support expressing durations in anything other than a 96-bit integer number of
362nanoseconds, it's not possible to represent concepts like "1 month." But a
363[`Span`](crate::Span) can.
364
365To see this more concretely, consider the different behavior resulting from
366using `humantime` to parse durations and adding them to a date:
367
368```
369use jiff::{civil, Span};
370
371let span: Span = "1 month".parse()?;
372let dur = humantime::parse_duration("1 month")?;
373
374let datetime = civil::date(2024, 5, 1).at(0, 0, 0, 0);
375
376// Adding 1 month using a `Span` gives one possible expected result. That is,
377// 2024-06-01T00:00:00 is exactly one month later than 2024-05-01T00:00:00.
378assert_eq!(datetime + span, civil::date(2024, 6, 1).at(0, 0, 0, 0));
379// But if we add the duration representing "1 month" as interpreted by
380// humantime, we get a very odd result. This is because humantime uses
381// a duration of 30.44 days (where every day is 24 hours exactly) for
382// all months.
383assert_eq!(datetime + dur, civil::date(2024, 5, 31).at(10, 33, 36, 0));
384
385# Ok::<(), Box<dyn std::error::Error>>(())
386```
387
388The same is true for days when dealing with zoned date times:
389
390```
391use jiff::{civil, Span};
392
393let span: Span = "1 day".parse()?;
394let dur = humantime::parse_duration("1 day")?;
395
396let zdt = civil::date(2024, 3, 9).at(17, 0, 0, 0).in_tz("America/New_York")?;
397
398// Adding 1 day gives the generally expected result of the same clock
399// time on the following day when adding a `Span`.
400assert_eq!(
401 &zdt + span,
402 civil::date(2024, 3, 10).at(17, 0, 0, 0).in_tz("America/New_York")?,
403);
404// But with humantime, all days are assumed to be exactly 24 hours. So
405// you get an instant in time that is 24 hours later, even when some
406// days are shorter and some are longer.
407assert_eq!(
408 &zdt + dur,
409 civil::date(2024, 3, 10).at(18, 0, 0, 0).in_tz("America/New_York")?,
410);
411
412// Notice also that this inaccuracy can occur merely by a duration that
413// _crosses_ a time zone transition boundary (like DST) at any point. It
414// doesn't require your datetimes to be "close" to when DST occurred.
415let dur = humantime::parse_duration("20 day")?;
416let zdt = civil::date(2024, 3, 1).at(17, 0, 0, 0).in_tz("America/New_York")?;
417assert_eq!(
418 &zdt + dur,
419 civil::date(2024, 3, 21).at(18, 0, 0, 0).in_tz("America/New_York")?,
420);
421
422# Ok::<(), Box<dyn std::error::Error>>(())
423```
424
425It's worth pointing out that in some applications, the fixed values assigned
426by `humantime` might be perfectly acceptable. Namely, they introduce error
427into calculations, but the error might be small enough to be a non-issue in
428some applications. But this error _can_ be avoided and `humantime` commits
429it silently. Indeed, `humantime`'s API is itself not possible without either
430rejecting varying length units or assuming fixed values for them. This is
431because it parses varying length units but returns a duration expressed as a
432single 96-bit integer number of nanoseconds. In order to do this, you _must_
433assume a definite length for those varying units. To do this _correctly_, you
434really need to provide a reference date.
435
436For example, Jiff can parse `1 month` into a `std::time::Duration` too, but
437it requires parsing into a `Span` and then converting into a `Duration` by
438providing a reference date:
439
440```
441use std::time::Duration;
442
443use jiff::{civil, Span};
444
445let span: Span = "1 month".parse()?;
446// converts to signed duration
447let sdur = span.to_duration(civil::date(2024, 5, 1))?;
448// converts to standard library unsigned duration
449let dur = Duration::try_from(sdur)?;
450// exactly 31 days where each day is 24 hours long.
451assert_eq!(dur, Duration::from_secs(31 * 24 * 60 * 60));
452
453// Now change the reference date and notice that the
454// resulting duration is changed but still correct.
455let sdur = span.to_duration(civil::date(2024, 6, 1))?;
456let dur = Duration::try_from(sdur)?;
457// exactly 30 days where each day is 24 hours long.
458assert_eq!(dur, Duration::from_secs(30 * 24 * 60 * 60));
459
460# Ok::<(), Box<dyn std::error::Error>>(())
461```
462
463# Motivation
464
465This format was devised, in part, because the standard duration interchange
466format specified by [Temporal's ISO 8601 definition](super::temporal) is
467sub-optimal in two important respects:
468
4691. It doesn't support individual sub-second components.
4702. It is difficult to read.
471
472In the first case, ISO 8601 durations do support sub-second components, but are
473only expressible as fractional seconds. For example:
474
475```text
476PT1.100S
477```
478
479This is problematic in some cases because it doesn't permit distinguishing
480between some spans. For example, `1.second().milliseconds(100)` and
481`1100.milliseconds()` both serialize to the same ISO 8601 duration as shown
482above. At deserialization time, it's impossible to know what the span originally
483looked like. Thus, using the ISO 8601 format means the serialization and
484deserialization of [`Span`](crate::Span) values is lossy.
485
486In the second case, ISO 8601 durations appear somewhat difficult to quickly
487read. For example:
488
489```text
490P1Y2M3DT4H59M1.1S
491P1y2m3dT4h59m1.1S
492```
493
494When all of the unit designators are capital letters in particular (which
495is the default), everything runs together and it's hard for the eye to
496distinguish where digits stop and letters begin. Using lowercase letters for
497unit designators helps somewhat, but this is an extension to ISO 8601 that
498isn't broadly supported.
499
500The "friendly" format resolves both of these problems by permitting sub-second
501components and allowing the use of whitespace and longer unit designator labels
502to improve readability. For example, all of the following are equivalent and
503will parse to the same `Span`:
504
505```text
5061y 2mo 3d 4h 59m 1100ms
5071 year 2 months 3 days 4h59m1100ms
5081 year, 2 months, 3 days, 4h59m1100ms
5091 year, 2 months, 3 days, 4 hours 59 minutes 1100 milliseconds
510```
511
512At the same time, the friendly format continues to support fractional
513time components since they may be desirable in some cases. For example, all
514of the following are equivalent:
515
516```text
5171h 1m 1.5s
5181h 1m 1,5s
51901:01:01.5
52001:01:01,5
521```
522
523The idea with the friendly format is that end users who know how to write
524English durations are happy to both read and write durations in this format.
525And moreover, the format is flexible enough that end users generally don't need
526to stare at a grammar to figure out how to write a valid duration. Most of the
527intuitive things you'd expect to work will work.
528
529# Internationalization
530
531Currently, only US English unit designator labels are supported. In general,
532Jiff resists trying to solve the internationalization problem in favor
533of punting it to another crate, such as [`icu`] via [`jiff-icu`]. Jiff
534_could_ adopt unit designator labels for other languages, but it's not
535totally clear whether that's the right path to follow given the complexity
536of internationalization. If you'd like to discuss it, please
537[file an issue](https://github.com/BurntSushi/jiff/issues).
538
539# Grammar
540
541This section gives a more precise description of the "friendly" duration format
542in the form of a grammar.
543
544```text
545format =
546 format-signed-hms
547 | format-signed-designator
548
549format-signed-hms =
550 sign? format-hms
551
552format-hms =
553 [0-9]+ ':' [0-9]+ ':' [0-9]+ fractional?
554
555format-signed-designator =
556 sign? format-designator-units
557 | format-designator-units direction?
558format-designator-units =
559 years
560 | months
561 | weeks
562 | days
563 | hours
564 | minutes
565 | seconds
566 | milliseconds
567 | microseconds
568 | nanoseconds
569
570# This dance below is basically to ensure a few things:
571# First, that at least one unit appears. That is, that
572# we don't accept the empty string. Secondly, when a
573# fractional component appears in a time value, we don't
574# allow any subsequent units to appear. Thirdly, that
575# `HH:MM:SS[.f{1,9}]?` is allowed after years, months,
576# weeks or days.
577years =
578 unit-value unit-years comma? ws* format-hms
579 | unit-value unit-years comma? ws* months
580 | unit-value unit-years comma? ws* weeks
581 | unit-value unit-years comma? ws* days
582 | unit-value unit-years comma? ws* hours
583 | unit-value unit-years comma? ws* minutes
584 | unit-value unit-years comma? ws* seconds
585 | unit-value unit-years comma? ws* milliseconds
586 | unit-value unit-years comma? ws* microseconds
587 | unit-value unit-years comma? ws* nanoseconds
588 | unit-value unit-years
589months =
590 unit-value unit-months comma? ws* format-hms
591 | unit-value unit-months comma? ws* weeks
592 | unit-value unit-months comma? ws* days
593 | unit-value unit-months comma? ws* hours
594 | unit-value unit-months comma? ws* minutes
595 | unit-value unit-months comma? ws* seconds
596 | unit-value unit-months comma? ws* milliseconds
597 | unit-value unit-months comma? ws* microseconds
598 | unit-value unit-months comma? ws* nanoseconds
599 | unit-value unit-months
600weeks =
601 unit-value unit-weeks comma? ws* format-hms
602 | unit-value unit-weeks comma? ws* days
603 | unit-value unit-weeks comma? ws* hours
604 | unit-value unit-weeks comma? ws* minutes
605 | unit-value unit-weeks comma? ws* seconds
606 | unit-value unit-weeks comma? ws* milliseconds
607 | unit-value unit-weeks comma? ws* microseconds
608 | unit-value unit-weeks comma? ws* nanoseconds
609 | unit-value unit-weeks
610days =
611 unit-value unit-days comma? ws* format-hms
612 | unit-value unit-days comma? ws* hours
613 | unit-value unit-days comma? ws* minutes
614 | unit-value unit-days comma? ws* seconds
615 | unit-value unit-days comma? ws* milliseconds
616 | unit-value unit-days comma? ws* microseconds
617 | unit-value unit-days comma? ws* nanoseconds
618 | unit-value unit-days
619hours =
620 unit-value unit-hours comma? ws* minutes
621 | unit-value unit-hours comma? ws* seconds
622 | unit-value unit-hours comma? ws* milliseconds
623 | unit-value unit-hours comma? ws* microseconds
624 | unit-value unit-hours comma? ws* nanoseconds
625 | unit-value fractional? ws* unit-hours
626minutes =
627 unit-value unit-minutes comma? ws* seconds
628 | unit-value unit-minutes comma? ws* milliseconds
629 | unit-value unit-minutes comma? ws* microseconds
630 | unit-value unit-minutes comma? ws* nanoseconds
631 | unit-value fractional? ws* unit-minutes
632seconds =
633 unit-value unit-seconds comma? ws* milliseconds
634 | unit-value unit-seconds comma? ws* microseconds
635 | unit-value unit-seconds comma? ws* nanoseconds
636 | unit-value fractional? ws* unit-seconds
637milliseconds =
638 unit-value unit-milliseconds comma? ws* microseconds
639 | unit-value unit-milliseconds comma? ws* nanoseconds
640 | unit-value fractional? ws* unit-milliseconds
641microseconds =
642 unit-value unit-microseconds comma? ws* nanoseconds
643 | unit-value fractional? ws* unit-microseconds
644nanoseconds =
645 unit-value fractional? ws* unit-nanoseconds
646
647unit-value = [0-9]+ [ws*]
648unit-years = 'years' | 'year' | 'yrs' | 'yr' | 'y'
649unit-months = 'months' | 'month' | 'mos' | 'mo'
650unit-weeks = 'weeks' | 'week' | 'wks' | 'wk' | 'w'
651unit-days = 'days' | 'day' | 'd'
652unit-hours = 'hours' | 'hour' | 'hrs' | 'hr' | 'h'
653unit-minutes = 'minutes' | 'minute' | 'mins' | 'min' | 'm'
654unit-seconds = 'seconds' | 'second' | 'secs' | 'sec' | 's'
655unit-milliseconds =
656 'milliseconds'
657 | 'millisecond'
658 | 'millis'
659 | 'milli'
660 | 'msecs'
661 | 'msec'
662 | 'ms'
663unit-microseconds =
664 'microseconds'
665 | 'microsecond'
666 | 'micros'
667 | 'micro'
668 | 'usecs'
669 | 'usec'
670 | 'µ' (U+00B5 MICRO SIGN) 'secs'
671 | 'µ' (U+00B5 MICRO SIGN) 'sec'
672 | 'us'
673 | 'µ' (U+00B5 MICRO SIGN) 's'
674unit-nanoseconds =
675 'nanoseconds' | 'nanosecond' | 'nanos' | 'nano' | 'nsecs' | 'nsec' | 'ns'
676
677fractional = decimal-separator decimal-fraction
678decimal-separator = '.' | ','
679decimal-fraction = [0-9]{1,9}
680
681sign = '+' | '-'
682direction = ws 'ago'
683comma = ',' ws
684ws =
685 U+0020 SPACE
686 | U+0009 HORIZONTAL TAB
687 | U+000A LINE FEED
688 | U+000C FORM FEED
689 | U+000D CARRIAGE RETURN
690```
691
692One thing not specified by the grammar above are maximum values. Namely,
693there are no specific maximum values imposed for each individual unit, nor
694a maximum value for the entire duration (say, when converted to nanoseconds).
695Instead, implementations are expected to impose their own limitations.
696
697For Jiff, a `Span` is more limited than a `SignedDuration`. For example, a the
698year component of a `Span` is limited to `[-19,999, 19,999]`. In contrast,
699a `SignedDuration` is a 96-bit signed integer number of nanoseconds with no
700particular limits on the individual units. They just can't combine to something
701that overflows a 96-bit signed integer number of nanoseconds. (And parsing into
702a `SignedDuration` directly only supports units of hours or smaller, since
703bigger units do not have an invariant length.) In general, implementations
704should support a "reasonable" range of values.
705
706[`humantime`]: https://docs.rs/humantime
707[`humantime-serde`]: https://docs.rs/humantime-serde
708[`icu`]: https://docs.rs/icu
709[`jiff-icu`]: https://docs.rs/jiff-icu
710*/
711
712pub use self::{
713 parser::SpanParser,
714 printer::{Designator, Direction, FractionalUnit, Spacing, SpanPrinter},
715};
716
717/// The default span/duration parser that we use.
718pub(crate) static DEFAULT_SPAN_PARSER: SpanParser = SpanParser::new();
719
720/// The default span/duration printer that we use.
721pub(crate) static DEFAULT_SPAN_PRINTER: SpanPrinter = SpanPrinter::new();
722
723mod parser;
724mod parser_label;
725mod printer;