summaryrefslogtreecommitdiffstats
path: root/src/time.rs
blob: 7084b08182aee8732de026be6572bbc7cd7a1bc4 (plain)
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use super::IcalDuration;
use super::IcalTimeZone;
use super::TZ_MUTEX;
use crate::ical;
use crate::utils::dateutil;
use chrono::{Date, DateTime, Local, TimeZone, Utc};
use std::ffi::{CStr, CString};
use std::fmt::{Display, Error, Formatter};
use std::ops::{Add, Deref};
use std::str::FromStr;

/// Time type
///
/// A type representing "time"
#[derive(Clone, Debug)]
pub struct IcalTime {
    time: ical::icaltimetype,
}

impl IcalTime {

    /// Get an IcalTime object that represents UTC now
    pub fn utc() -> Self {
        dateutil::now().into()
    }

    /// Get an IcalTime object that represents the current time in the local timezone.
    pub fn local() -> Self {
        dateutil::now().with_timezone(&Local).into()
    }

    /// Get an IcalTime object that represents a specific day.
    pub fn floating_ymd(year: i32, month: i32, day: i32) -> Self {
        let time = ical::icaltimetype {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
            is_date: 1,
            is_daylight: 0,
            zone: ::std::ptr::null(),
        };
        let time = unsafe { ical::icaltime_normalize(time) };
        IcalTime { time }
    }

    /// Get an IcalTime object that is the same as the object this function is called on, but with
    /// hour, minute and second set
    pub fn and_hms(&self, hour: i32, minute: i32, second: i32) -> Self {
        let mut time = self.time;
        time.hour = hour;
        time.minute = minute;
        time.second = second;
        time.is_date = 0;

        let time = unsafe { ical::icaltime_normalize(time) };

        IcalTime { time }
    }

    /// Get an IcalTime object based on a timestamp
    pub fn from_timestamp(timestamp: i64) -> Self {
        let _lock = TZ_MUTEX.lock();
        let utc = IcalTimeZone::utc();
        let is_date = 0;
        let time = unsafe { ical::icaltime_from_timet_with_zone(timestamp, is_date, *utc) };
        IcalTime { time }
    }

    /// Get the timestamp representation of the IcalTime object
    pub fn timestamp(&self) -> i64 {
        let _lock = TZ_MUTEX.lock();
        unsafe { ical::icaltime_as_timet_with_zone(self.time, self.time.zone) }
    }

    /// Get whether the IcalTime object is a date object
    pub fn is_date(&self) -> bool {
        self.time.is_date != 0
    }

    /// Get the IcalTime object as a date object
    pub fn as_date(&self) -> IcalTime {
        let mut time = self.time;
        time.is_date = 1;
        IcalTime { time }
    }

    /// Get the timezone for the IcalTime object
    pub fn get_timezone(&self) -> Option<IcalTimeZone> {
        if self.time.zone.is_null() {
            return None;
        }
        let tz_ptr = unsafe { ical::icaltime_get_timezone(self.time) };
        Some(IcalTimeZone::from_ptr_copy(tz_ptr))
    }

    /// Get a new IcalTime object with a different timezone
    pub fn with_timezone(&self, timezone: &IcalTimeZone) -> IcalTime {
        let _lock = TZ_MUTEX.lock();
        let mut time = unsafe { ical::icaltime_convert_to_zone(self.time, **timezone) };
        //icaltime_convert_to_zone does nothing if is_date == 1
        time.zone = **timezone;
        IcalTime { time }
    }

    /// Get a new IcalTime object with the day before the day of the current object
    pub fn pred(&self) -> IcalTime {
        let mut time = self.time;
        time.day -= 1;
        let time = unsafe { ical::icaltime_normalize(time) };
        IcalTime { time }
    }

    /// Get a new IcalTime object with the day after the day of the current object
    pub fn succ(&self) -> IcalTime {
        let mut time = self.time;
        time.day += 1;
        let time = unsafe { ical::icaltime_normalize(time) };
        IcalTime { time }
    }
}

impl Deref for IcalTime {
    type Target = ical::icaltimetype;

    fn deref(&self) -> &ical::icaltimetype {
        &self.time
    }
}

impl Display for IcalTime {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let cstr = unsafe { CStr::from_ptr(ical::icaltime_as_ical_string(self.time)) };
        let string = cstr.to_string_lossy();
        write!(f, "{}", string)
    }
}

impl FromStr for IcalTime {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        unsafe {
            let c_str = CString::new(s).unwrap();
            let time = ical::icaltime_from_string(c_str.as_ptr());
            if ical::icaltime_is_null_time(time) == 0 {
                Ok(IcalTime { time })
            } else {
                Err(format!("Could not parse time {}", s))
            }
        }
    }
}

impl PartialEq<IcalTime> for IcalTime {
    fn eq(&self, rhs: &IcalTime) -> bool {
        let _lock = TZ_MUTEX.lock();
        let cmp = unsafe { ical::icaltime_compare(self.time, rhs.time) };
        cmp == 0
    }
}

impl Eq for IcalTime {}

impl From<ical::icaltimetype> for IcalTime {
    fn from(time: ical::icaltimetype) -> IcalTime {
        IcalTime { time }
    }
}

impl Add<IcalDuration> for IcalTime {
    type Output = IcalTime;

    fn add(self, other: IcalDuration) -> IcalTime {
        let time = unsafe { ical::icaltime_add(self.time, *other) };
        IcalTime { time }
    }
}

impl From<DateTime<Local>> for IcalTime {
    fn from(time: DateTime<Local>) -> IcalTime {
        let timestamp = time.timestamp();
        let local = IcalTimeZone::local();
        IcalTime::from_timestamp(timestamp).with_timezone(&local)
    }
}

impl From<DateTime<Utc>> for IcalTime {
    fn from(time: DateTime<Utc>) -> IcalTime {
        let timestamp = time.timestamp();
        IcalTime::from_timestamp(timestamp)
    }
}

impl From<Date<Local>> for IcalTime {
    fn from(date: Date<Local>) -> IcalTime {
        let timestamp = date.with_timezone(&Utc).and_hms(0, 0, 0).timestamp();
        let timezone = IcalTimeZone::local();
        IcalTime::from_timestamp(timestamp)
            .with_timezone(&timezone)
            .as_date()
    }
}

impl From<Date<Utc>> for IcalTime {
    fn from(date: Date<Utc>) -> IcalTime {
        let timestamp = date.and_hms(0, 0, 0).timestamp();
        IcalTime::from_timestamp(timestamp).as_date()
    }
}

impl From<IcalTime> for Date<Local> {
    fn from(time: IcalTime) -> Date<Local> {
        Local.timestamp(time.timestamp(), 0).date()
    }
}

impl From<IcalTime> for DateTime<Local> {
    fn from(time: IcalTime) -> DateTime<Local> {
        Local.timestamp(time.timestamp(), 0)
    }
}

impl From<IcalTime> for Date<Utc> {
    fn from(time: IcalTime) -> Date<Utc> {
        Utc.timestamp(time.timestamp(), 0).date()
    }
}

impl From<IcalTime> for DateTime<Utc> {
    fn from