1use core::time::Durationas UnsignedDuration;
23use crate::{
4Error, SignedDuration, Span,
5 error::{ErrorContext, duration::Erroras E},
6};
78/// An internal type for abstracting over different duration types.
9#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Duration {
}
#[automatically_derived]impl ::core::clone::Clone for Duration {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<SignedDuration>;
let _: ::core::clone::AssertParamIsClone<UnsignedDuration>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Duration { }Copy, #[automatically_derived]impl ::core::fmt::Debug for Duration {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Span(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Span",
&__self_0),
Self::Signed(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Signed", &__self_0),
Self::Unsigned(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Unsigned", &__self_0),
}
}
}Debug)]
10pub(crate) enum Duration {
11 Span(Span),
12 Signed(SignedDuration),
13 Unsigned(UnsignedDuration),
14}
1516impl Duration {
17/// Convert this to a signed duration.
18 ///
19 /// This returns an error only in the case where this is an unsigned
20 /// duration with a number of whole seconds that exceeds `|i64::MIN|`.
21#[cfg_attr(feature = "perf-inline", inline(always))]
22pub(crate) fn to_signed(&self) -> Result<SDuration<'_>, Error> {
23match *self {
24 Duration::Span(ref span) => Ok(SDuration::Span(span)),
25 Duration::Signed(sdur) => Ok(SDuration::Absolute(sdur)),
26 Duration::Unsigned(udur) => {
27let sdur = SignedDuration::try_from(udur)
28 .context(E::RangeUnsignedDuration)?;
29Ok(SDuration::Absolute(sdur))
30 }
31 }
32 }
3334/// Negates this duration.
35 ///
36 /// When the duration is a span, this can never fail because a span defines
37 /// its min and max values such that negation is always possible.
38 ///
39 /// When the duration is signed, then this attempts to return a signed
40 /// duration and only falling back to an unsigned duration when the number
41 /// of seconds corresponds to `i64::MIN`.
42 ///
43 /// When the duration is unsigned, then this fails when the whole seconds
44 /// exceed the absolute value of `i64::MIN`. Otherwise, a signed duration
45 /// is returned.
46 ///
47 /// The failures for large unsigned durations here are okay because the
48 /// point at which absolute durations overflow on negation, they would also
49 /// cause overflow when adding or subtracting to *any* valid datetime value
50 /// for *any* datetime type in this crate. So while the error message may
51 /// be different, the actual end result is the same (failure).
52 ///
53 /// TODO: Write unit tests for this.
54#[cfg_attr(feature = "perf-inline", inline(always))]
55pub(crate) fn checked_neg(self) -> Result<Duration, Error> {
56match self {
57 Duration::Span(span) => Ok(Duration::Span(span.negate())),
58 Duration::Signed(sdur) => {
59// We try to stick with signed durations, but in the case
60 // where negation fails, we can represent its negation using
61 // an unsigned duration.
62if let Some(sdur) = sdur.checked_neg() {
63Ok(Duration::Signed(sdur))
64 } else {
65let udur = UnsignedDuration::new(
66i64::MIN.unsigned_abs(),
67sdur.subsec_nanos().unsigned_abs(),
68 );
69Ok(Duration::Unsigned(udur))
70 }
71 }
72 Duration::Unsigned(udur) => {
73// We can permit negating i64::MIN.unsigned_abs() to
74 // i64::MIN, but we need to handle it specially since
75 // i64::MIN.unsigned_abs() exceeds i64::MAX.
76let sdur = if udur.as_secs() == i64::MIN.unsigned_abs() {
77SignedDuration::new_unchecked(
78i64::MIN,
79// OK because `udur.subsec_nanos()` < 999_999_999.
80-i32::try_from(udur.subsec_nanos()).unwrap(),
81 )
82 } else {
83// The negation here is always correct because it can only
84 // panic with `sdur.as_secs() == i64::MIN`, which is
85 // impossible because it must be positive.
86 //
87 // Otherwise, this is the only failure point in this entire
88 // routine. And specifically, we fail here in precisely
89 // the cases where `udur.as_secs() > |i64::MIN|`.
90-SignedDuration::try_from(udur)
91 .context(E::FailedNegateUnsignedDuration)?
92};
93Ok(Duration::Signed(sdur))
94 }
95 }
96 }
9798/// Returns true if and only if this duration is negative.
99#[cfg_attr(feature = "perf-inline", inline(always))]
100pub(crate) fn is_negative(&self) -> bool {
101match *self {
102 Duration::Span(ref span) => span.is_negative(),
103 Duration::Signed(ref sdur) => sdur.is_negative(),
104 Duration::Unsigned(_) => false,
105 }
106 }
107}
108109impl From<Span> for Duration {
110#[inline]
111fn from(span: Span) -> Duration {
112 Duration::Span(span)
113 }
114}
115116impl From<SignedDuration> for Duration {
117#[inline]
118fn from(sdur: SignedDuration) -> Duration {
119 Duration::Signed(sdur)
120 }
121}
122123impl From<UnsignedDuration> for Duration {
124#[inline]
125fn from(udur: UnsignedDuration) -> Duration {
126 Duration::Unsigned(udur)
127 }
128}
129130/// An internal type for abstracting over signed durations.
131///
132/// This is typically converted to from a `Duration`. It enables callers
133/// downstream to implement datetime arithmetic on only two duration types
134/// instead of doing it for three duration types (including
135/// `std::time::Duration`).
136///
137/// The main thing making this idea work is that if an unsigned duration cannot
138/// fit into a signed duration, then it would overflow any calculation on any
139/// datetime type in Jiff anyway. If this weren't true, then we'd need to
140/// support doing actual arithmetic with unsigned durations separately from
141/// signed durations.
142#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'a>
::core::clone::TrivialClone for SDuration<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for SDuration<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'a Span>;
let _: ::core::clone::AssertParamIsClone<SignedDuration>;
*self
}
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for SDuration<'a> { }Copy, #[automatically_derived]impl<'a> ::core::fmt::Debug for SDuration<'a> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Span(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Span",
&__self_0),
Self::Absolute(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Absolute", &__self_0),
}
}
}Debug)]
143pub(crate) enum SDuration<'a> {
144 Span(&'a Span),
145 Absolute(SignedDuration),
146}