| 1 |
# The API design rationale for Jiff |
| 2 |
|
| 3 |
This document discusses some of the design decisions that led to Jiff's API. |
| 4 |
The purpose of writing this document is to help folks understand _why_ Jiff's |
| 5 |
API is the way it is, above and beyond "Jiff did it this way to match |
| 6 |
[Temporal]." |
| 7 |
|
| 8 |
This document is written as an FAQ, although it is restricted in scope to the |
| 9 |
API design of Jiff. This isn't a FAQ for questions like, "How do I add 1 day |
| 10 |
to a zoned datetime?" |
| 11 |
|
| 12 |
Unlike "[Comparison with other Rust datetime crates][comparison]," this |
| 13 |
document is _opinionated_. That is, some value judgments are expressed that are |
| 14 |
opinion based, and on which reasonable people may disagree. |
| 15 |
|
| 16 |
|
| 17 |
## Why name the library "jiff"? |
| 18 |
|
| 19 |
I wanted something short and related to time for the library name. Most of the |
| 20 |
"obvious" names are taken. |
| 21 |
|
| 22 |
I thought a lot about phrases or words that had some connection to time. There |
| 23 |
are more than you think. One phrase I heard a lot as a kid who grew up in New |
| 24 |
England was, "I'll be back in a jiff" or "I'll be back in a jiffy." The meaning |
| 25 |
of that phrase was, roughly, "I'll be back very soon." So "jiff" refers to some |
| 26 |
"short span of time." Since "jiff" was shorter than "jiffy," that's what I went |
| 27 |
with. |
| 28 |
|
| 29 |
Jiff is pronounced like "gif" with a soft "g," as in "gem." |
| 30 |
|
| 31 |
|
| 32 |
## Why build another datetime library? |
| 33 |
|
| 34 |
At the time of writing, there are four existing prominent datetime libraries |
| 35 |
for Rust: [`chrono`], [`time`], [`hifitime`] and [`icu`]. "[Comparison with |
| 36 |
other Rust datetime crates][comparison]" goes over the "facts of comparison" |
| 37 |
between the crates (mostly for just `chrono` and `time`), but it intentionally |
| 38 |
leaves out value judgments. To answer this question, I have to introduce value |
| 39 |
judgments and my opinions on existing libraries. **These are opinions on which |
| 40 |
reasonable people can disagree.** Moreover, since these are opinions meant to |
| 41 |
justify an alternative, these opinions tend to be oriented on the faults (as |
| 42 |
this author sees them) in existing crates as opposed to their benefits. |
| 43 |
|
| 44 |
Broadly speaking, my view on Rust datetime libraries was that they had reached |
| 45 |
a local maximum, and there didn't seem to be much movement toward breaking out |
| 46 |
of that local maximum and getting to something that was categorically better. |
| 47 |
Much of my thoughts revolve around not just the functionality provided, but |
| 48 |
also the API design of these crates. Thus, I perceived a gap in the ecosystem |
| 49 |
that I felt like I could fill. |
| 50 |
|
| 51 |
I'll share my brief thoughts on each crate. I'll cover "why not contribute to |
| 52 |
an existing library and make it better" in the next question. |
| 53 |
|
| 54 |
### `chrono` |
| 55 |
|
| 56 |
In my view, Chrono is the closest to Jiff in terms of the functionality it |
| 57 |
provides. It has some support for DST safe arithmetic for example, and even |
| 58 |
some support for doing calendar math. But its support is incomplete. While one |
| 59 |
can add units of days to Chrono datetimes, Chrono lacks the ability to do math |
| 60 |
on multiple calendar units at the same time. Moreover, Chrono cannot _produce_ |
| 61 |
calendar durations between two time zone aware datetimes. |
| 62 |
|
| 63 |
Moreover, Chrono's integration with the [IANA Time Zone Database] is somewhat |
| 64 |
spotty. Support for it isn't included in the `chrono` crate itself, but |
| 65 |
is instead something you need to opt into with additional crates, such |
| 66 |
as [`chrono-tz`] or [`tzfile`]. And each crate comes with its own set of |
| 67 |
trade-offs. `chrono-tz` embeds the entire database into your binary and makes |
| 68 |
the time zones available at compile time, while `tzfile` reads the database |
| 69 |
from your system's copy of the database (i.e., `/usr/share/zoneinfo` on Unix). |
| 70 |
In my view, this creates a difficult situation for non-expert users of Chrono |
| 71 |
where the "right" choice isn't obvious. In my opinion, the _default_ should be |
| 72 |
to read time zone transition data from the system's copy of the database on |
| 73 |
disk, and only bundle the data into the binary as a last resort when a copy of |
| 74 |
the database isn't reliably available (like on Windows). The main reason for |
| 75 |
this is that the database is frequently updated (a few times each year) since |
| 76 |
the rules for time zone transitions can change. If that time zone data is |
| 77 |
embedded into your binary, then you need to 1) wait for `chrono-tz` to update |
| 78 |
their data and 2) re-compile your application and ship it out to users. |
| 79 |
|
| 80 |
In contrast, Jiff _abstracts_ the method of time zone data discovery. That |
| 81 |
is, there are no API differences between "read time zone data from the system |
| 82 |
database" and "read embedded time zone data." Of course, Jiff provides options |
| 83 |
to choose which method to use (like forcing bundling on Unix), but all of this |
| 84 |
is transparent to users of Jiff itself. That is, _Jiff tries to do the right |
| 85 |
thing by default_. There's no need to go off and find a different crate to |
| 86 |
handle time zone data for you. |
| 87 |
|
| 88 |
While on the topic of time zones, Chrono also has no support for serializing |
| 89 |
IANA time zone identifiers. This implies that if you have a time zone aware |
| 90 |
datetime in Chrono (whether by `chrono-tz` or `tzfile`), then you can't |
| 91 |
losslessly serialize and deserialize it. Namely, serialization will lose |
| 92 |
the time zone the datetime is associated with, and instead only include |
| 93 |
the offset. Then when it's deserialized, you're left with an offset-only |
| 94 |
datetime that won't, for example, provide DST safe arithmetic based on the |
| 95 |
original time zone. In contrast, Jiff follows [RFC 9557] to support embedding |
| 96 |
IANA time zone identifiers in the serialized representation. For example, |
| 97 |
`2024-07-21T17:11-04[America/New_York]`. |
| 98 |
|
| 99 |
There are a variety of other things that Jiff supports which Chrono does |
| 100 |
not, but that's covered in [the comparison section between Jiff and |
| 101 |
Chrono][comparison-chrono]. |
| 102 |
|
| 103 |
As for API design, I found Chrono's API to be overengineered and difficult to |
| 104 |
deal with. This is a frustratingly vague complaint, but here are some things |
| 105 |
that I believe contribute to that opinion: |
| 106 |
|
| 107 |
* I've used Chrono for various things, and I found it very difficult to figure |
| 108 |
out from its API what the right operations to use were. |
| 109 |
* Chrono has been steadily deprecating huge portions of its API in favor of |
| 110 |
fallible routines. I find the resulting documentation difficult to read and the |
| 111 |
naming to be very clunky. |
| 112 |
* The fallible routines return a mixture of `Option<T>` and `Result<T, E>`. |
| 113 |
This is frustrating in my experience because the `Option<T>` _usually_ needs to |
| 114 |
be converted to a human readable error message, and I think the library should |
| 115 |
make use of its contextual information to do this for you. Indeed, Jiff rarely |
| 116 |
returns `Option<T>` and instead returns `Result<T, E>` with a contextualized |
| 117 |
human readable error message. (Although I'm sure the error messages could use a |
| 118 |
lot of improvement.) |
| 119 |
* I find the use of generics in Chrono to be overengineered. It has some |
| 120 |
key benefits, for example, making the notion of "time zone" an open concept |
| 121 |
that can be defined by users of the crate. But in my opinion, this is rarely |
| 122 |
needed. The Chrono crate ecosystem makes use of this via the `chrono-tz` and |
| 123 |
`tzfile` crates, but Jiff covers both of those use cases (broadly speaking) |
| 124 |
automatically. |
| 125 |
* Chrono overall puts a large emphasis on "fixed offset" datetimes, but these |
| 126 |
are rarely the right abstraction to use. It's possible this is due to the fact |
| 127 |
that IANA time zone support is external to Chrono itself. Instead, Jiff just |
| 128 |
tries to do the right thing by default, and gives users IANA time zone support |
| 129 |
out of the box. Jiff does support fixed offset datetimes as well, but they are |
| 130 |
de-emphasized. |
| 131 |
* I find generic traits like `Datelike` to also be very confusing because they |
| 132 |
split the APIs of types like `NaiveDate` into concrete methods and generic |
| 133 |
methods, and there's no obvious rhyme or reason as to how those methods are |
| 134 |
split up. |
| 135 |
* Chrono's API doesn't offer clean on-ramps from civil ("naive") datetimes to |
| 136 |
time zone aware datetimes. For example, Chrono provides `NaiveDate::succ_opt` |
| 137 |
to get the next day, but this method isn't available on `NaiveDateTime` or |
| 138 |
`DateTime`. Instead, to implement it correctly on `DateTime`, you have to get |
| 139 |
the naive date, get the date for tomorrow via `succ_opt`, and then convert |
| 140 |
it back to the same `NaiveDateTime` and finally make it time zone aware by |
| 141 |
applying the original time zone to it. In contrast, in Jiff, it's just a matter |
| 142 |
of calling `Zoned::tomorrow`. Indeed, (almost) any method you can call on |
| 143 |
`civil::Date` in Jiff is also available on `civil::DateTime` and likewise for |
| 144 |
`Zoned`. This makes transitioning between datetime types very easy. Chrono |
| 145 |
almost appears to provide this same experience via traits like `Datelike`, |
| 146 |
but doesn't fully commit and, in my opinion, the end result has a feeling of |
| 147 |
arbitrariness to it. |
| 148 |
* Chrono lacks a standard timestamp type. You can approximate this with a |
| 149 |
`DateTime<Utc>`, but it's a more complicated type that includes a full datetime |
| 150 |
representation. In contrast, Jiff provides a `Timestamp` type for when you just |
| 151 |
want the number of seconds from the Unix epoch. And then integrates it with the |
| 152 |
rest of the datetime types in a consistent way. |
| 153 |
|
| 154 |
### `time` |
| 155 |
|
| 156 |
My main gripe with the `time` crate is that it has very limited |
| 157 |
[IANA Time Zone Database] support. This means it is difficult to do DST safe |
| 158 |
arithmetic. Consequently, it emphasizes the use of "fixed offset" datetimes |
| 159 |
in a similar fashion as Chrono, except `time` does not provide any extension |
| 160 |
mechanism like a `TimeZone` trait. In my view, fixed offset datetimes are |
| 161 |
rarely the right thing to use. In my opinion, this makes writing correct |
| 162 |
datetime code with the `time` crate rather difficult. In contrast, Jiff |
| 163 |
provides full [IANA Time Zone Database] support, and it should be very |
| 164 |
rare to need fixed offset datetimes (although Jiff does support them via |
| 165 |
`TimeZone::fixed`). |
| 166 |
|
| 167 |
(Note that at time of writing, there does exist an unofficial [`time-tz`] |
| 168 |
crate that provides very limited support for time zones in concert with the |
| 169 |
`time` crate. However, there is no time zone aware datetime type and no way to |
| 170 |
distinguish between calendar arithmetic and time arithmetic across daylight |
| 171 |
saving time boundaries. The `time-tz` crate borrows the design of `chrono-tz`, |
| 172 |
and thus has all of its downsides as well.) |
| 173 |
|
| 174 |
I overall find the API of `time` to be easier to understand than Chrono, likely |
| 175 |
because there are fewer generics. But `time` is also supporting a lot less than |
| 176 |
Chrono and Jiff (because of the missing time zone support in `time` itself). |
| 177 |
|
| 178 |
As with Chrono, I've done a |
| 179 |
[more detailed comparison between Jiff and `time`][comparison-time]. |
| 180 |
|
| 181 |
### `hifitime` |
| 182 |
|
| 183 |
`hifitime` is more of a specialized datetime library suited to scientific |
| 184 |
applications, and so while Jiff and `hifitime` have overlapping use cases, |
| 185 |
`hifitime` fundamentally has a different target demographic than Jiff. As noted |
| 186 |
in a [comparison between Jiff and `hifitime`][comparison-hifitime], `hifitime` |
| 187 |
doesn't have any time zone support, but it does support conversions between |
| 188 |
many different time scales and leap second support. Leap second support, in |
| 189 |
this context, means that the durations between two points in time take leap |
| 190 |
seconds into account in `hifitime`, but Jiff pretends as if they don't exist. |
| 191 |
|
| 192 |
In terms of building a new datetime library, I felt like `hifitime` wasn't |
| 193 |
really targeting the "general purpose datetime library" use case that I felt |
| 194 |
`chrono` and `time` were. And so, whether it existed or not didn't really |
| 195 |
impact whether another _general purpose_ datetime library should be built. |
| 196 |
|
| 197 |
### `icu` |
| 198 |
|
| 199 |
`icu` is, as I understand it, still under construction with respect to datetime |
| 200 |
support. For example, it doesn't have [IANA Time Zone Database] support. |
| 201 |
But, it does support locale aware formatting of datetimes and non-Gregorian |
| 202 |
calendars. |
| 203 |
|
| 204 |
When I started working on Jiff, I didn't have a good understanding of what the |
| 205 |
`icu` crate offers. I still don't really. In part because the API is difficult |
| 206 |
for me to understand and in part because I haven't dedicated a ton of time to |
| 207 |
studying its API. But either way, I don't think it is currently in a position |
| 208 |
to be a general purpose datetime library and I wasn't clear on what its goals |
| 209 |
were. |
| 210 |
|
| 211 |
Since I haven't spent a lot of time with `icu`, I didn't have much to say about |
| 212 |
it in my [comparison with it and Jiff][comparison-icu]. |
| 213 |
|
| 214 |
|
| 215 |
## Why not contribute to an existing library instead of building a new one? |
| 216 |
|
| 217 |
Given that Rust already has at least two prominent datetime libraries, doesn't |
| 218 |
adding another one just make things worse? And why not contribute to an |
| 219 |
existing library to make it better instead of starting over from scratch? |
| 220 |
|
| 221 |
I first want to say that I acknowledge that throwing a new crate into the |
| 222 |
ecosystem, and adding yet another choice, does actually come with downsides. |
| 223 |
There is a cost to having too many choices, and when possible, I do believe it |
| 224 |
is better to improve an existing project rather than start a new one. |
| 225 |
|
| 226 |
Improving existing projects can be difficult. Jiff has a different design than |
| 227 |
both `chrono` and `time`. Evolving either one of those crates into what Jiff is |
| 228 |
would, in my view, require a huge amount of resources. Not just in time, but in |
| 229 |
social capital as well. Because it wouldn't be greenfield development done by |
| 230 |
one person making all of the design choices, but instead someone from outside |
| 231 |
the project trying to convince the maintainers of established projects to move |
| 232 |
in a radically different direction. I know what it's like to be on the side of |
| 233 |
maintaining an established API for a library with a lot of users. There is a |
| 234 |
huge inertial cost to making sweeping API changes. |
| 235 |
|
| 236 |
Moreover, when I started Jiff, I was not a domain expert in datetime libraries |
| 237 |
or datetime handling in general. Therefore, my opinion that `chrono` and `time` |
| 238 |
_could_ be better would arguably not carry a lot of weight. It was only through |
| 239 |
the process of actually building a datetime library did I learn enough to form |
| 240 |
nuanced opinions about the status quo. When I started, my opinions were much |
| 241 |
more vague (but still strong enough to start this project). |
| 242 |
|
| 243 |
On top of all of this, I was _intrinsically_ motivated to work on this problem. |
| 244 |
I found it very interesting, and especially because I perceived there to be a |
| 245 |
gap in the ecosystem that I thought I could fill in. I had a vision for what |
| 246 |
a datetime library _should_ look like. And it took a lot of iteration to get |
| 247 |
from my initial vision to something that works in practice. Doing this on an |
| 248 |
existing datetime library with real users would be extremely difficult. |
| 249 |
|
| 250 |
And speaking as someone who has had folks publish _better_ versions of some of |
| 251 |
my own crates, I know what it's like to be on the other end of this. Sometimes |
| 252 |
you just have to start fresh. |
| 253 |
|
| 254 |
|
| 255 |
## Are there any published alternative perspectives on Rust datetime libraries? |
| 256 |
|
| 257 |
Here's a list. More may be added in the future: |
| 258 |
|
| 259 |
* [Commentary from the original author of the `chrono` crate.][alt1] |
| 260 |
|
| 261 |
[alt1]: https://github.com/BurntSushi/jiff/issues/63 |
| 262 |
|
| 263 |
|
| 264 |
## Why are there two duration types? |
| 265 |
|
| 266 |
The two duration types provided by Jiff are `Span` and `SignedDuration`. A |
| 267 |
`SignedDuration` is effectively identical to a `std::time::Duration`, but it's |
| 268 |
signed instead of unsigned. A `Span` is also a duration type, but is likely |
| 269 |
different than most other duration types you've used before. |
| 270 |
|
| 271 |
While a `SignedDuration` can be thought of as a single integer corresponding |
| 272 |
to the number of nanoseconds between two points in time, a `Span` is a |
| 273 |
collection of individual unit values that combine to represent the difference |
| 274 |
between two point in time. Stated more concretely, while the spans `2 |
| 275 |
hours` and `120 minutes` both correspond to the same duration of time, when |
| 276 |
represented as a Jiff `Span`, they correspond to two distinct values in |
| 277 |
memory. This is something that is fundamentally not expressible by a type |
| 278 |
like `SignedDuration`, where `2 hours` and `120 minutes` are completely |
| 279 |
indistinguishable. |
| 280 |
|
| 281 |
One of the key advantages of a `Span` is that it can represent units of |
| 282 |
non-uniform length. For example, not every month has the same number of days, |
| 283 |
but a `Span` can still represent units of months because it tracks the values |
| 284 |
of each unit independently. For example, Jiff is smart enough to know that the |
| 285 |
difference between `2024-03-01` and `2024-04-01` is the same number of months |
| 286 |
as `2024-04-01` and `2024-05-01`, even though the number of days is different: |
| 287 |
|
| 288 |
```rust |
| 289 |
use jiff::{civil::date, ToSpan, Unit}; |
| 290 |
|
| 291 |
fn main() -> anyhow::Result<()> { |
| 292 |
let date1 = date(2024, 3, 1); |
| 293 |
let date2 = date(2024, 4, 1); |
| 294 |
let date3 = date(2024, 5, 1); |
| 295 |
|
| 296 |
// When computing durations between `Date` values, |
| 297 |
// the spans default to days. |
| 298 |
assert_eq!(date1.until(date2)?, 31.days().fieldwise()); |
| 299 |
assert_eq!(date2.until(date3)?, 30.days().fieldwise()); |
| 300 |
|
| 301 |
// But we can request bigger units! |
| 302 |
assert_eq!(date1.until((Unit::Month, date2))?, 1.month().fieldwise()); |
| 303 |
assert_eq!(date2.until((Unit::Month, date3))?, 1.month().fieldwise()); |
| 304 |
|
| 305 |
Ok(()) |
| 306 |
} |
| 307 |
``` |
| 308 |
|
| 309 |
While most folks are very in tune with the fact that years and months have |
| 310 |
non-uniform length, a less obvious truth is that days themselves also have |
| 311 |
non-uniform length in the presence of time zones. For example, `2024-03-10` in |
| 312 |
`America/New_York` was only 23 hours long (the region entered daylight saving |
| 313 |
time, creating a gap in time), while `2024-11-03` was 25 hours long (the region |
| 314 |
left daylight saving time, creating a fold in time). Being unaware of this |
| 315 |
corner case leads to folks assuming that "1 day" and "24 hours" are _always_ |
| 316 |
exactly equivalent. But they aren't. The design of Jiff leans into this and |
| 317 |
ensures that so long as you're using `Span` to encode a concept of days and are |
| 318 |
doing arithmetic with it on `Zoned` values, then you can never get it wrong. |
| 319 |
Jiff will always take time zones into account when dealing with units of days |
| 320 |
or bigger. |
| 321 |
|
| 322 |
The design of `Span` comes from [Temporal], which [uses only one duration |
| 323 |
type][temporal-one-duration]. From that issue, there are some significant |
| 324 |
advantages to using a `Span`. In my own words: |
| 325 |
|
| 326 |
* It more closely lines up with ISO 8601 durations, which themselves combine |
| 327 |
calendar and clock units. |
| 328 |
* With a `Span`, it is very easy to move between `5 years 2 months` and |
| 329 |
the number of hours in that same span. |
| 330 |
* Jiff's `Span` type specifically represents each unit as distinct from the |
| 331 |
others. In contrast, most absolute duration types (like `std::time::Duration` |
| 332 |
and Jiff's own `SignedDuration`), are "just" a 96-bit integer number of |
| 333 |
nanoseconds. This means that, for example, `1 hour 30 minutes` is impossible to |
| 334 |
differentiate from `90 minutes`. But depending on the use case, you might want |
| 335 |
one or the other. Jiff's `Span` design (copied from Temporal) enables users |
| 336 |
to express durations in whatever units they want. And this expression can be |
| 337 |
manipulated via APIs like `Span::round` in intuitive ways. |
| 338 |
|
| 339 |
A `SignedDuration` is still useful in some respects. For example, when you |
| 340 |
need tighter integration with the standard library's `std::time::Duration` |
| 341 |
(since a `SignedDuration` is the same, but just signed), or when you need |
| 342 |
better performance than what `Span` gives you. In particular, since a `Span` |
| 343 |
keeps track of the values for each individual unit, it is a much heavier type |
| 344 |
than a `SignedDuration`. It uses up more stack space and also required more |
| 345 |
computation to do arithmetic with it. |
| 346 |
|
| 347 |
|
| 348 |
## Why isn't there a `TimeZone` trait? |
| 349 |
|
| 350 |
First, let's start by explaining what a `TimeZone` is. In Jiff, a `TimeZone` |
| 351 |
is a concrete type that cannot be extended by users of Jiff. Instead, users of |
| 352 |
Jiff are forced to use one of three different kinds of time zones: |
| 353 |
|
| 354 |
* A "fixed offset" time zone where the civil time for any particular instant |
| 355 |
is computed by simply adding or subtracting a fixed number of seconds from UTC. |
| 356 |
The `TimeZone::fixed` constructor enables callers to build time zones with any |
| 357 |
offset within the limits imposed by Jiff. |
| 358 |
* A [POSIX time zone][POSIX TZ], typically set via the `TZ` environment |
| 359 |
variable. These are rarely used by end users, but do provide a way to specify |
| 360 |
a rule for when daylight saving time transitions occur thoughtout the year. |
| 361 |
(But it does not support historical transitions that might not conform to the |
| 362 |
current rule.) The `TimeZone::posix` constructor enables callers to build a |
| 363 |
`TimeZone` with a POSIX time zone string. |
| 364 |
* [TZif formatted data][RFC 8536], usually from the |
| 365 |
[IANA Time Zone Database]. This data contains historical time zone transitions |
| 366 |
in addition to rules governing the future in the form of POSIX TZ strings.The |
| 367 |
`TimeZone::tzif` constructor enables callers to build a `TimeZone` with any |
| 368 |
TZif formatted data. |
| 369 |
|
| 370 |
The `jiff::tz::TimeZoneDatabase` automatically looks for TZif formatted |
| 371 |
files in your system's copy of the IANA Time Zone Database, usually at |
| 372 |
`/usr/share/zoneinfo`. (On Windows, Jiff embeds a copy of the IANA Time Zone |
| 373 |
Database into the compiled artifact itself.) |
| 374 |
|
| 375 |
So why isn't `TimeZone` a trait? Well, the above formulation should cover the |
| 376 |
_vast majority_ of use cases. And even if that doesn't cover everything, it |
| 377 |
is possible for callers to use `TimeZone::tzif` to construct arbitrary time |
| 378 |
zones by building their own TZif data. This is a somewhat large hurdle though, |
| 379 |
so if this is something that is commonly needed, I'm open to exploring other |
| 380 |
options for building custom time zones. For example, perhaps we introduce a way |
| 381 |
to describe time zone transitions in Rust code that can then be used to build a |
| 382 |
`TimeZone` directly. But, the benefit of TZif is that it is inter-operable and |
| 383 |
a standard. There are tools that can build them. |
| 384 |
|
| 385 |
An important thing to note here is that I actually approach questions like |
| 386 |
"Why isn't `TimeZone` a trait?" as instead "Why _should_ `TimeZone` be a trait?" |
| 387 |
In particular, I personally perceive costs to introducing generics, especially |
| 388 |
on a fundamental type in the crate. For example, if `TimeZone` were a trait, |
| 389 |
then `Zoned` would not be a concrete type. It would be generic over a type |
| 390 |
parameter that implements the `TimeZone` trait. This in turn implies that |
| 391 |
anyone _using_ a `Zoned` in their own types or APIs needs to think about the |
| 392 |
`TimeZone` trait and likely incorporate it into their own type signatures. This |
| 393 |
is because a `TimeZone` trait implies an open system that infects everything |
| 394 |
it touches. The complexity isn't contained. But a concrete `TimeZone` type, |
| 395 |
like what Jiff has, encapsulates everything there is about time zones. |
| 396 |
|
| 397 |
(Making `Zoned` generic over a type parameter with a _default_ type does |
| 398 |
contain the complexity in some cases, but not all. I explored using default |
| 399 |
type parameters in Jiff for supporting [leap seconds][github-issue-leap], and |
| 400 |
it was overall quite awkward in my opinion.) |
| 401 |
|
| 402 |
The trade off is that we do give up some flexibility. For example, Chrono uses |
| 403 |
a `TimeZone` trait design. This enables external crates to provide their own |
| 404 |
implementations of the `TimeZone` trait. But the two principle instances of |
| 405 |
this occurring, `chrono-tz` and `tzfile`, are both supported by Jiff itself. |
| 406 |
With that said, one key advantage of Chrono's design is that it permits its |
| 407 |
zone aware datetime type (`DateTime<T>`) to be `Copy` if `T` is `Copy`. It is |
| 408 |
somewhat difficult (although not literally impossible) to make a TZif-backed |
| 409 |
time zone implement `Copy`, but a _reference_ to it is `Copy` and a reference |
| 410 |
to it can still implement Chrono's `TimeZone` trait. (And indeed, this is what |
| 411 |
the `tzfile` crate does.) This ultimately leads to more flexibility compared |
| 412 |
to Jiff, where its `Zoned` type embeds a `TimeZone` and a `TimeZone` cannot |
| 413 |
easily be made `Copy` without giving up something else. |
| 414 |
|
| 415 |
My opinions on the costs of generics tend to overestimate them compared to many |
| 416 |
others in my experience, so your mileage may vary on where you land on this |
| 417 |
issue. Buy in my opinion, being able to just write `Zoned` as a concrete type |
| 418 |
without any generics is a huge win for comprehensibility. |
| 419 |
|
| 420 |
|
| 421 |
## Why doesn't `TimeZone` implement `Copy`? |
| 422 |
|
| 423 |
When initially setting out to build Jiff, I _really_ wanted the `TimeZone` type |
| 424 |
to implement `Copy`. The reason why I wanted it to implement `Copy` is because |
| 425 |
I wanted all datetime types to have "plain old data" semantics. That is, I want |
| 426 |
callers to think of them as small immutable bits of data that can be freely |
| 427 |
copied without worry. This makes APIs a little nicer because you can ask for a |
| 428 |
`Zoned` instead of a `&Zoned`, assuming the `Zoned` type is small enough. |
| 429 |
|
| 430 |
But, in order for `Zoned` to be `Copy`, it must be the case that `TimeZone` is |
| 431 |
`Copy`. This is because `Zoned` embeds a `TimeZone`. Indeed, this is the reason |
| 432 |
for its existence: it couples an instant in time with a particular geographic |
| 433 |
region. This makes it possible to expose very ergonomic high level APIs that |
| 434 |
don't require the caller to keep passing in a `TimeZone` value repeatedly. |
| 435 |
|
| 436 |
So, how can a `TimeZone` be `Copy`? Well, both fixed offset and POSIX time |
| 437 |
zones could be `Copy`. There's no huge challenge in that. (Internally, a POSIX |
| 438 |
time zone is not currently `Copy` because there's no reason for it given what |
| 439 |
we're about to discuss.) The main challenge is the TZif-backed time zone. TZif |
| 440 |
formatted data can contain an arbitrary number of time zone transitions. There |
| 441 |
is just no way to avoid some kind of dynamic memory allocation. |
| 442 |
|
| 443 |
Since we need dynamic memory allocation, there is really only one way to |
| 444 |
make it `Copy` at this point: introduce some kind of caching mechanism with |
| 445 |
a small `Copy` identifier that lets us "look up" the time zone in some kind |
| 446 |
of global or thread-local cache. I thought a lot about how I might wire this |
| 447 |
together, and I could not come up with a satisfactory design. I believe |
| 448 |
garbage collection is the main challenge, but also synchronization overhead |
| 449 |
for accessing a time zone is likely also a problem. The nice benefit of the |
| 450 |
`TimeZone` type as it exists now is that it's just data. While _getting_ a |
| 451 |
`TimeZone` from a `TimeZoneDatabase` might require synchronization and possibly |
| 452 |
even I/O if the cache for it was invalidated, a `TimeZone` itself requires no |
| 453 |
synchronization whatsoever to use it. It is just an `Arc` internally to make it |
| 454 |
pointer-sized. |
| 455 |
|
| 456 |
|
| 457 |
## Why isn't there a `SystemZoned` type? Or a `OffsetZoned` type? |
| 458 |
|
| 459 |
Some datetime libraries have multiple different zone aware datetime types. Jiff |
| 460 |
opts to have just one, and embeds support for the different types of time zones |
| 461 |
that most people will ever need into that one type. Jiff does this via the |
| 462 |
`TimeZone` type, which can be a fixed offset, a POSIX time zone or TZif-backed |
| 463 |
(usually from the [IANA Time Zone Database]). |
| 464 |
|
| 465 |
|
| 466 |
## Why doesn't Jiff support leap seconds? |
| 467 |
|
| 468 |
The short summary is that the use cases for leap second support are rather |
| 469 |
limited, and the effect they have on overall API complexity is quite large. |
| 470 |
That is, I believe they would make the API of Jiff more complicated than the |
| 471 |
value they bring to the domain. |
| 472 |
|
| 473 |
A standard work-around for _part_ of the leap second problem---and usually the |
| 474 |
one people care about---is to use custom TZif data that describes when each of |
| 475 |
the leap seconds occurs. In effect, you can treat [TAI] as its own time zone. |
| 476 |
This enables callers to compute accurate durations of time that span a leap |
| 477 |
second (positive or negative). And indeed, so long as you build that TZif |
| 478 |
data, Jiff supports this via `TimeZone::tzif`. |
| 479 |
|
| 480 |
I wrote a lot more [about leap seconds on the issue |
| 481 |
tracker][github-issue-leap]. |
| 482 |
|
| 483 |
|
| 484 |
## Why isn't there any integration with `std::time::Duration`? |
| 485 |
|
| 486 |
The initial release of `jiff 0.1` originally left out any integration |
| 487 |
points with `std::time::Duration`. Since then, `SignedDuration` has |
| 488 |
been added to Jiff. And `TryFrom` trait implementations have been added |
| 489 |
to both `SignedDuration` and `Span` to make conversions between it and |
| 490 |
`std::time::Duration` easier. |
| 491 |
|
| 492 |
|
| 493 |
## What are the `ZoneDifference` and `ZonedRound` types for? |
| 494 |
|
| 495 |
The `ZonedDifference` and `ZonedRound` are builders for expressing the |
| 496 |
parameters to the functions `Zoned::{since, until}` and `Zoned::round`, |
| 497 |
respectively. For example, this: |
| 498 |
|
| 499 |
```rust |
| 500 |
use jiff::{civil::date, ToSpan}; |
| 501 |
|
| 502 |
let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 503 |
let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 504 |
assert_eq!(zdt1.until(&zdt2)?, 744.hours().seconds(36).fieldwise()); |
| 505 |
|
| 506 |
# Ok::<(), Box<dyn std::error::Error>>(()) |
| 507 |
``` |
| 508 |
|
| 509 |
Is equivalent to: |
| 510 |
|
| 511 |
```rust |
| 512 |
use jiff::{civil::date, ToSpan, ZonedDifference}; |
| 513 |
|
| 514 |
let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 515 |
let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 516 |
assert_eq!( |
| 517 |
zdt1.until(ZonedDifference::new(&zdt2))?, |
| 518 |
744.hours().seconds(36).fieldwise(), |
| 519 |
); |
| 520 |
|
| 521 |
# Ok::<(), Box<dyn std::error::Error>>(()) |
| 522 |
``` |
| 523 |
|
| 524 |
The point of this is that `ZonedDifference` permits specifying additional |
| 525 |
configuration. For example, rounding the span returned: |
| 526 |
|
| 527 |
```rust |
| 528 |
use jiff::{civil::date, ToSpan, Unit, ZonedDifference}; |
| 529 |
|
| 530 |
let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 531 |
let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 532 |
assert_eq!( |
| 533 |
zdt1.until(ZonedDifference::new(&zdt2).smallest(Unit::Minute))?, |
| 534 |
744.hours().fieldwise(), |
| 535 |
); |
| 536 |
|
| 537 |
# Ok::<(), Box<dyn std::error::Error>>(()) |
| 538 |
``` |
| 539 |
|
| 540 |
By using a dedicated type to represent the parameters, we can enable ergonomic |
| 541 |
uses of the API for common cases (by using `From<&Zoned> for ZonedDifference` |
| 542 |
trait implementations) while still permitting callers to provide additional |
| 543 |
configuration. |
| 544 |
|
| 545 |
An alternative API would be to remove the additional parameters to |
| 546 |
`Zoned::until`, and instead require callers to do span rounding themselves |
| 547 |
explicitly. But this is more verbose and requires repeating the correct |
| 548 |
zoned datetime to indicate how to interpret non-uniform units. For example, |
| 549 |
instead of this: |
| 550 |
|
| 551 |
```rust |
| 552 |
use jiff::{civil::date, ToSpan, Unit, ZonedDifference}; |
| 553 |
|
| 554 |
let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 555 |
let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 556 |
let diff = ZonedDifference::new(&zdt2) |
| 557 |
.largest(Unit::Month) |
| 558 |
.smallest(Unit::Minute); |
| 559 |
assert_eq!(zdt1.until(diff)?, 1.month().fieldwise()); |
| 560 |
|
| 561 |
# Ok::<(), Box<dyn std::error::Error>>(()) |
| 562 |
``` |
| 563 |
|
| 564 |
One would need to do this: |
| 565 |
|
| 566 |
```rust |
| 567 |
use jiff::{civil::date, RoundMode, SpanRound, ToSpan, Unit}; |
| 568 |
|
| 569 |
let zdt1 = date(2024, 7, 16).at(22, 3, 23, 0).in_tz("America/New_York")?; |
| 570 |
let zdt2 = date(2024, 8, 16).at(22, 3, 59, 0).in_tz("America/New_York")?; |
| 571 |
let span = zdt1.until(&zdt2)?; |
| 572 |
let rounded = span.round( |
| 573 |
SpanRound::new() |
| 574 |
.largest(Unit::Month) |
| 575 |
.smallest(Unit::Minute) |
| 576 |
.relative(&zdt1) |
| 577 |
.mode(RoundMode::Trunc), |
| 578 |
)?; |
| 579 |
assert_eq!(rounded, 1.month().fieldwise()); |
| 580 |
|
| 581 |
# Ok::<(), Box<dyn std::error::Error>>(()) |
| 582 |
``` |
| 583 |
|
| 584 |
This is somewhat fiddly and easy to get wrong. Moreover, the `Zoned::until` |
| 585 |
API, when rounding is enabled, will automatically use `RoundMode::Trunc`, since |
| 586 |
this is what usually expects when computing the span between two datetimes. But |
| 587 |
span rounding uses `RoundMode::HalfExpand` by default, corresponding to how you |
| 588 |
were likely taught to round in school. (Rounds to the nearest unit, with ties |
| 589 |
breaking away from zero.) |
| 590 |
|
| 591 |
Similar reasoning applies to other "parameter builder" types like |
| 592 |
`civil::DateTimeDifference` as well. |
| 593 |
|
| 594 |
|
| 595 |
## Why isn't `Timestamp` called `Instant`? |
| 596 |
|
| 597 |
The main reason why is because of the existence of `std::time::Instant`. While |
| 598 |
that doesn't in and of itself prevent Jiff from using the name `Instant`, it |
| 599 |
creates a naming clash with something that is _similar_ but different. Namely, |
| 600 |
a Jiff `Timestamp` corresponds to a time from your system clock, where as an |
| 601 |
`Instant` represents _monotonic_ time. The system clock might change or even |
| 602 |
go backwards, where as a monotonic instant will always produce time that is |
| 603 |
greater than or equal to a previous time. |
| 604 |
|
| 605 |
An `Instant` is, for example, something you might use to measure the time |
| 606 |
something takes in a program. Like in capturing a measurement for a benchmark. |
| 607 |
Conversely, a `Timestamp` is something you use to represent time as represented |
| 608 |
by the system. In particular, a `Timestamp` is like a `std::time::SystemTime` |
| 609 |
and _not_ a `std::time::Instant`. |
| 610 |
|
| 611 |
While [Temporal] uses the name `Instant` for their equivalent of Jiff's |
| 612 |
`Timestamp` type, using the name `Instant` in Jiff would likely result in |
| 613 |
serious confusion and conflicts in names when someone wants to use both an |
| 614 |
`Instant` and a `Timestamp` in the same namespace. |
| 615 |
|
| 616 |
[Temporal]: https://tc39.es/proposal-temporal/docs/ |
| 617 |
[temporal-one-duration]: https://github.com/tc39/proposal-temporal/issues/2915 |
| 618 |
[comparison]: http://docs.rs/jiff/*/jiff/_documentation/comparison/index.html |
| 619 |
[comparison-chrono]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#chrono-v0438 |
| 620 |
[comparison-time]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#time-v0336 |
| 621 |
[comparison-hifitime]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#hifitime-v0390 |
| 622 |
[comparison-icu]: https://docs.rs/jiff/*/jiff/_documentation/comparison/index.html#icu-v150 |
| 623 |
[RFC 8536]: https://datatracker.ietf.org/doc/draft-murchison-rfc8536bis/ |
| 624 |
[RFC 9557]: https://datatracker.ietf.org/doc/rfc9557/ |
| 625 |
[POSIX TZ]: https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html |
| 626 |
[IANA Time Zone Database]: https://en.wikipedia.org/wiki/Tz_database |
| 627 |
[TAI]: https://en.wikipedia.org/wiki/International_Atomic_Time |
| 628 |
[github-issue-leap]: https://github.com/BurntSushi/jiff/issues/7 |
| 629 |
[`java.time`]: https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html |
| 630 |
[NodaTime]: https://nodatime.org/ |
| 631 |
[`chrono-tz`]: https://docs.rs/chrono-tz |
| 632 |
[`tzfile`]: https://docs.rs/tzfile |
| 633 |
[`chrono`]: https://docs.rs/chrono |
| 634 |
[`time`]: https://docs.rs/time |
| 635 |
[`time-tz`]: https://docs.rs/time-tz |
| 636 |
[`hifitime`]: https://docs.rs/hifitime |
| 637 |
[`icu`]: https://docs.rs/icu |