Why doesn't Jiff support 3.years() + 1.month() + 5.days() + 10.hours()
?
#41
-
One of the most popular remarks about Jiff (other than the pronunciation of its name) is a question about why spans can't be added together using the So why doesn't Jiff support that syntax? And if we really wanted to add it, how would we go about it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I think the simplest way to look at the essential problem here is to ask this: what is the answer to use jiff::ToSpan;
fn main() -> anyhow::Result<()> {
let sp1 = 2.months().days(25);
let sp2 = 10.days();
let sum = sp1.checked_add(sp2)?;
println!("{sum}");
Ok(())
} Has this output:
Oops. So that fails. Indeed, whenever adding spans with non-uniform units (like months), you need to provide a reference date. Otherwise, you can't know how long that month actually is. And crucially, Jiff specifically avoids returning "unbalanced" spans like use jiff::{civil::date, ToSpan};
fn main() -> anyhow::Result<()> {
let sp1 = 2.months().days(25);
let sp2 = 10.days();
let sum = sp1.checked_add((sp2, date(2024, 7, 24)))?;
println!("{sum}");
Ok(())
} And its output is:
What we get out is a nice span that isn't bottom heavy. The smaller units "overflowed" and this caused the bigger units to go up. This behavior isn't going to change. It's a key selling point of Jiff's You can probably already start to see the shape of the problem here. An alternative would be to declare that The main problem with the alternative, and one that I think is significant, is that its behavior doesn't match that of |
Beta Was this translation helpful? Give feedback.
-
Ohhh, alright! So, i missed a couple of important things when asking #37... First, that And i also missed all this re-balancing logic that When building spans, i guess what we want to say is "i want a span with these many days, and with these many hours, and so on".
IDK if you're interested in brainstorming ideas given that this question is already answered. But if that's the case, here are some not-very-deeply-thought ideas 😅
Of all these, my personal preference would be for the operator overloading approach (i don't have a strong preference for either In fact, going the operator route, one could even imagine building the individual spans like let span = 5 * DAY & 8 * HOUR & 1 * MINUTE; IDK if i would prefer this TBH, but i wanted to mention it for brainstorming's sake. |
Beta Was this translation helpful? Give feedback.
I think the simplest way to look at the essential problem here is to ask this: what is the answer to
2.months().days(25) + 10.days()
? Well, Jiff providesSpan::checked_add
. And surely,span1 + span2
would just useSpan::checked_add
and panic on failure, right? Right? Right? And surely, there is absolutely nothing wrong with adding together these two spans!Has this output: