1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! A parser implementation for  durations as defined in RFC5545.
//!
//! These are mostly used for alarms, to indicate their time relative to the time of an event or
//! todo.
//!
//! For convenience, [`Rfc5545Duration`](crate::Rfc5545Duration) implements [`Add`](core::ops::Add)
//! for [`icalendar::DatePerhapsTime`], [`chrono::DateTime`] and
//! [`chrono::naive::NaiveDateTime`].
//!
//! ## Example
//!
//! ```
//! use chrono::TimeZone;
//! use chrono::Utc;
//!
//! let duration = icalendar_duration::parse("PT24H")?;
//! let dt = Utc.ymd(2022, 9, 1).and_hms(22, 9, 14);
//!
//! assert_eq!(dt + duration, Utc.ymd(2022, 9, 2).and_hms(22, 9, 14));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt::Display;
use std::ops::{Add, MulAssign, Neg, Sub};

use chrono::{DateTime, Duration, NaiveDateTime, TimeZone};
use icalendar::{CalendarDateTime, DatePerhapsTime};

mod parser;

pub use parser::parse;

/// The sign for a duration (which can be negative or positive).
///
/// The default is positive, as the absence of an explicit sign implies positive.
#[derive(Default, PartialEq, Eq, Debug)]
pub enum Sign {
    #[default]
    Positive,
    Negative,
}

/// Converts a "+" or "-" into a `Sign`.
///
/// # Quirks
///
/// Will return `Sign:Positive` for invalid input.
impl From<Option<char>> for Sign {
    fn from(value: Option<char>) -> Self {
        if Some('-') == value {
            Sign::Negative
        } else {
            Sign::Positive
        }
    }
}

impl Display for Sign {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sign = match self {
            Sign::Positive => "+",
            Sign::Negative => "-",
        };
        write!(f, "{}", sign)
    }
}

impl Neg for Sign {
    type Output = Sign;

    fn neg(self) -> Self::Output {
        match self {
            Sign::Positive => Sign::Negative,
            Sign::Negative => Sign::Positive,
        }
    }
}

/// The Duration specified in RFC554.
///
/// This has a few quirks that ultimately, make it incompatible with the Duration classes from both
/// Chrono and the stdlib. The main difference is how DST transition and leap seconds are handled.
///
/// From Section 3.3.6:
///
/// > The duration of a week or a day depends on its position in the calendar.  In the case of
/// > discontinuities in the time scale, such as the change from standard time to daylight time and
/// > back, the computation of the exact duration requires the subtraction or addition of the
/// > change of duration of the discontinuity.  Leap seconds MUST NOT be considered when computing
/// > an exact duration. When computing an exact duration, the greatest order time components MUST
/// > be added first, that is, the number of days MUST be added first, followed by the number of
/// > hours, number of minutes, and number of seconds.
///
/// This will usually behave rather intuitively for users. For an event that occurs at 16:00hs on
/// the Monday after daylight saving, an alarm set 1 day before will trigger at 16hs, even though
/// this is technically 25 (or 23) hours before the event.
///
/// # Caveats
///
/// The specification indicates that numerical values are "one or more digits". Technically,
/// setting an alarm one million years before an event is perfectly valid. However, modelling this
/// would require arbitrary precision numbers or using absurdly large sized integers. These
/// scenarios are valid but unrealistic, and are deliberately not supported in the interest of
/// better performance. Any `1*DIGIT` is restricted to an [u16].
///
/// Parsing and re-encoding a duration will sometimes yield different results. In particular the
/// `+` sign is always dropped (it is the implicit default) and units with value `0` are dropped.
/// E.g.: `-P0DT1H` will become `-PT1H`, and `+PT1H` will become `PT1H`. These are equivalent.
///
/// # See also
///
/// [`icalendar_duration::parse`](crate::parse).
#[derive(Default, PartialEq, Eq, Debug)]
pub struct Rfc5545Duration {
    sign: Sign,
    weeks: i64,
    days: i64,
    hours: i64,
    minutes: i64,
    seconds: i64,
}

impl Display for Rfc5545Duration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // XXX: Modeling an absent sign is required to avoid altering explicit "PLUS".
        if self.sign == Sign::Negative {
            write!(f, "-")?;
        }
        write!(f, "P")?;
        if self.weeks > 0 {
            write!(f, "{}W", self.weeks)?;
        }
        if self.days > 0 {
            write!(f, "{}D", self.days)?;
        }
        if self.hours > 0 || self.minutes > 0 || self.seconds > 0 {
            write!(f, "T")?;
            if self.hours > 0 {
                write!(f, "{}H", self.hours)?;
            }
            if self.minutes > 0 {
                write!(f, "{}M", self.minutes)?;
            }
            if self.seconds > 0 {
                write!(f, "{}S", self.seconds)?;
            }
        }

        Ok(())
    }
}

impl MulAssign<Sign> for Rfc5545Duration {
    #[inline]
    fn mul_assign(&mut self, rhs: Sign) {
        self.sign = rhs;
    }
}

impl Rfc5545Duration {
    /// Return this duration in seconds.
    ///
    /// Care should be taken not to use this on timezone-aware datetimes, since the results would
    /// not be correct.
    fn absolute_seconds(&self) -> i64 {
        self.days
            .saturating_mul(24)
            .saturating_add(self.hours)
            .saturating_mul(60)
            .saturating_add(self.minutes)
            .saturating_mul(60)
            .saturating_add(self.seconds)
    }
}

/// Changes the sign from positive to negative and vice versa.
///
/// Usage of this function is discouraged, since it creates a copy of the entire struct.
impl Neg for Rfc5545Duration {
    type Output = Rfc5545Duration;

    fn neg(self) -> Self::Output {
        Self::Output {
            sign: -self.sign,
            ..self
        }
    }
}

/// Adds a duration to [`DatePerhapsTime`].
///
/// A [`DatePerhapsTime::Date`] is equivalent to one with time `00:00:00`. From rfc5545,
/// section-3.8.6.3:
///
/// > Alarms specified in an event or to-do that is defined in terms of a DATE value
/// > type will be triggered relative to 00:00:00 of the user's configured time zone
/// > on the specified date, or relative to 00:00:00 UTC on the specified date if no
/// > configured time zone can be found for the user.
impl Add<Rfc5545Duration> for DatePerhapsTime {
    type Output = CalendarDateTime;

    fn add(self, rhs: Rfc5545Duration) -> Self::Output {
        match self {
            DatePerhapsTime::DateTime(CalendarDateTime::Floating(naive)) => {
                CalendarDateTime::Floating(naive + rhs)
            }
            DatePerhapsTime::DateTime(CalendarDateTime::Utc(aware)) => {
                CalendarDateTime::Utc(aware + rhs)
            }
            DatePerhapsTime::DateTime(CalendarDateTime::WithTimezone {
                date_time: naive,
                tzid,
            }) => CalendarDateTime::WithTimezone {
                date_time: naive + rhs,
                tzid,
            },
            DatePerhapsTime::Date(date) => CalendarDateTime::Floating(date.and_hms(0, 0, 0) + rhs),
        }
    }
}

impl<Tz: TimeZone> Add<Rfc5545Duration> for DateTime<Tz> {
    type Output = DateTime<Tz>;

    /// # Panics
    ///
    /// Panics if the resulting time does not exist in the datetime's timezone.
    fn add(self, rhs: Rfc5545Duration) -> Self::Output {
        // Converting to naive AND THEN operating on that makes sure we ignore any DST transition,
        // leap seconds and other discontinuities.
        let result = self.naive_local() + rhs;

        self.timezone()
            .from_local_datetime(&result)
            .earliest()
            .unwrap()
    }
}

impl Add<Rfc5545Duration> for NaiveDateTime {
    type Output = NaiveDateTime;

    fn add(self, rhs: Rfc5545Duration) -> Self::Output {
        // Converting to naive AND THEN operating on that makes sure we ignore any DST transition,
        // leap seconds and other discontinuities.
        match rhs.sign {
            Sign::Positive => self + Duration::seconds(rhs.absolute_seconds()),
            Sign::Negative => self - Duration::seconds(rhs.absolute_seconds()),
        }
    }
}

impl<Tz: TimeZone> Sub<Rfc5545Duration> for DateTime<Tz> {
    type Output = DateTime<Tz>;

    fn sub(self, rhs: Rfc5545Duration) -> Self::Output {
        let result = self.naive_local() - rhs;

        self.timezone()
            .from_local_datetime(&result)
            .earliest()
            .unwrap()
    }
}

impl Sub<Rfc5545Duration> for NaiveDateTime {
    type Output = NaiveDateTime;

    fn sub(self, rhs: Rfc5545Duration) -> Self::Output {
        // Converting to naive AND THEN operating on that makes sure we ignore any DST transition,
        // leap seconds and other discontinuities.
        //
        // See [`Rfc5545Duration`]
        //
        // # Panics
        //
        // Panics if the resulting time does not exist in the given timezone.
        match rhs.sign {
            Sign::Positive => self - Duration::seconds(rhs.absolute_seconds()),
            Sign::Negative => self + Duration::seconds(rhs.absolute_seconds()),
        }
    }
}