date_range_rs 0.2.0

A collection of date range types
Documentation
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use joda_rs::{Duration, LocalDate, LocalDateTime, LocalTime};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};

/// Represents an inclusive range of timestamps.
#[derive(Debug, Clone)]
pub struct DateTimeRange {
    start: LocalDateTime,
    end: LocalDateTime,
}

impl DateTimeRange {
    /// Creates a range from the given start and end timestamps.
    pub fn of(start: LocalDateTime, end: LocalDateTime) -> Self {
        Self { start, end }
    }

    /// Creates a range from a start/end time-of-day on the given date. If end_time is before
    /// start_time, the range is treated as crossing midnight into the next day.
    pub fn from_time_range_on_date(
        start_time: LocalTime,
        end_time: LocalTime,
        date: LocalDate,
    ) -> Self {
        if end_time < start_time {
            Self {
                start: date.at_time(start_time),
                end: date.plus_days(1).at_time(end_time),
            }
        } else {
            Self {
                start: date.at_time(start_time),
                end: date.at_time(end_time),
            }
        }
    }

    /// Creates a 24-hour range spanning all of date, from midnight to the following midnight.
    pub fn all_day(date: LocalDate) -> Self {
        Self {
            start: date.at_start_of_day(),
            end: date.plus_days(1).at_start_of_day(),
        }
    }

    /// Get the starting timestamp of the range.
    pub fn start(&self) -> LocalDateTime {
        self.start
    }

    /// Get the ending timestamp of the range.
    pub fn end(&self) -> LocalDateTime {
        self.end
    }

    /// Get the duration between the start and end timestamps.
    pub fn duration(&self) -> Duration {
        self.end - self.start
    }

    /// Check if this range overlaps another, inclusive of touching endpoints.
    pub fn overlaps(&self, other: &DateTimeRange) -> bool {
        self.start <= other.end && self.end >= other.start
    }

    /// Check if this range overlaps another, excluding touching endpoints.
    pub fn overlaps_exclusive(&self, other: &DateTimeRange) -> bool {
        self.start < other.end && self.end > other.start
    }

    /// Check if other is fully contained within this range.
    pub fn overlaps_completely(&self, other: &DateTimeRange) -> bool {
        other.start >= self.start && other.end <= self.end
    }

    /// Get the duration of the overlap with another range, or zero if they don't overlap.
    pub fn overlap_duration(&self, other: &DateTimeRange) -> Duration {
        self.overlap_range(other)
            .map(|r| r.duration())
            .unwrap_or_else(|| Duration::of_seconds(0))
    }

    /// Get the range representing the overlap with another range, or None if they don't overlap.
    pub fn overlap_range(&self, other: &DateTimeRange) -> Option<DateTimeRange> {
        if !self.overlaps(other) {
            return None;
        }

        let start = self.start.max(other.start);
        let end = self.end.min(other.end);

        Some(Self::of(start, end))
    }

    /// Check if a timestamp falls within the range, inclusive of both bounds.
    pub fn contains(&self, dt: LocalDateTime) -> bool {
        dt >= self.start && dt <= self.end
    }

    /// Check if a timestamp falls within the range, excluding both bounds.
    pub fn contains_exclusive(&self, dt: LocalDateTime) -> bool {
        dt > self.start && dt < self.end
    }
}

impl PartialEq for DateTimeRange {
    fn eq(&self, other: &Self) -> bool {
        self.start == other.start && self.end == other.end
    }
}

impl Eq for DateTimeRange {}

impl Hash for DateTimeRange {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.start.hash(state);
        self.end.hash(state);
    }
}

impl PartialOrd for DateTimeRange {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DateTimeRange {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.start.cmp(&other.start) {
            Ordering::Equal => self.end.cmp(&other.end),
            ord => ord,
        }
    }
}

// --- Period traits and helpers moved here ---
pub trait PeriodIndexing {
    fn start_index(&self) -> i32;
    fn end_index(&self) -> i32;
    fn index_range(&self) -> (i32, i32);
    fn number_of_periods(&self) -> i32;
    fn period_length_in_minutes(&self) -> i32;
}

pub trait PeriodIteration {
    type Item;
    type Iter: Iterator<Item = Self::Item>;
    fn iter(&self) -> Self::Iter;
}

const MINUTES_PER_HOUR: i32 = 60;
const MINUTES_PER_DAY: i32 = 1440;

#[derive(Debug, Copy, Clone)]
pub struct WithPeriod<'a> {
    range: &'a DateTimeRange,
    period_length_minutes: i32,
}

impl DateTimeRange {
    /// Views this range as a sequence of fixed-length periods, for indexing and iteration.
    pub fn with_period_len(&self, period_length_minutes: i32) -> WithPeriod<'_> {
        WithPeriod {
            range: self,
            period_length_minutes,
        }
    }
}

pub struct DateTimeRangeIterator {
    current: LocalDateTime,
    end: LocalDateTime,
    step_minutes: i32,
}

impl DateTimeRangeIterator {
    fn new(range: &DateTimeRange, period_minutes: i32) -> Self {
        Self {
            current: range.start(),
            end: range.end(),
            step_minutes: period_minutes,
        }
    }
}

impl Iterator for DateTimeRangeIterator {
    type Item = LocalDateTime;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current > self.end {
            None
        } else {
            let result = self.current;
            self.current = self.current.plus_minutes(self.step_minutes as i64);
            Some(result)
        }
    }
}

impl<'a> WithPeriod<'a> {
    /// Get the underlying DateTimeRange.
    pub fn date_time_range(&self) -> &DateTimeRange {
        self.range
    }

    /// Get the index of the period containing the start of the range.
    pub fn start_index(&self) -> i32 {
        let st = self.range.start();
        let st_time = st.to_local_time();
        let minutes_from_midnight =
            st_time.hour() as i32 * MINUTES_PER_HOUR + st_time.minute() as i32;
        minutes_from_midnight / self.period_length_minutes
    }

    /// Get the index of the period containing the end of the range.
    pub fn end_index(&self) -> i32 {
        let sd = self.range.start();
        let ed = self.range.end();
        let sd_date = sd.to_local_date();
        let ed_date = ed.to_local_date();
        let ed_time = ed.to_local_time();
        let mut end_index = ed_time.hour() as i32 * MINUTES_PER_HOUR + ed_time.minute() as i32;
        if ed_date > sd_date {
            end_index += MINUTES_PER_DAY;
        }
        end_index / self.period_length_minutes
    }

    /// Get the inclusive (start_index, end_index) pair covering the range.
    pub fn index_range(&self) -> (i32, i32) {
        (self.start_index(), self.end_index() - 1)
    }

    /// Get the number of full periods that fit between the start and end of the range.
    pub fn number_of_periods(&self) -> i32 {
        let mut count = 0;
        let mut t = self.range.start();
        let step = self.period_length_minutes as i64;
        while t.plus_minutes(step) <= self.range.end() {
            count += 1;
            t = t.plus_minutes(step);
        }
        count
    }

    /// Get the configured period length, in minutes.
    pub fn period_length_in_minutes(&self) -> i32 {
        self.period_length_minutes
    }
}

impl<'a> PeriodIndexing for WithPeriod<'a> {
    fn start_index(&self) -> i32 {
        Self::start_index(self)
    }
    fn end_index(&self) -> i32 {
        Self::end_index(self)
    }
    fn index_range(&self) -> (i32, i32) {
        Self::index_range(self)
    }
    fn number_of_periods(&self) -> i32 {
        Self::number_of_periods(self)
    }
    fn period_length_in_minutes(&self) -> i32 {
        Self::period_length_in_minutes(self)
    }
}

impl<'a> PeriodIteration for WithPeriod<'a> {
    type Item = LocalDateTime;
    type Iter = DateTimeRangeIterator;
    fn iter(&self) -> Self::Iter {
        DateTimeRangeIterator::new(self.range, self.period_length_minutes)
    }
}

#[cfg(test)]
mod tests {
    use super::DateTimeRange;
    use joda_rs::{Duration, LocalDate, LocalDateTime, LocalTime};
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    fn d(y: i32, m: i32, day: i32) -> LocalDate {
        LocalDate::of(y, m, day)
    }
    fn t(h: i32, m: i32, s: i32) -> LocalTime {
        LocalTime::of(h, m, s)
    }
    fn dt(y: i32, m: i32, day: i32, h: i32, mi: i32, s: i32) -> LocalDateTime {
        LocalDateTime::of(y, m, day, h, mi, s)
    }

    #[test]
    fn of_constructs_and_duration_is_end_minus_start() {
        let start = dt(2023, 3, 10, 8, 30, 0);
        let end = dt(2023, 3, 10, 17, 0, 0);
        let r = DateTimeRange::of(start, end);
        assert_eq!(r.start(), start);
        assert_eq!(r.end(), end);
        assert_eq!(r.duration(), Duration::of_seconds(8 * 3600 + 30 * 60));
    }

    #[test]
    fn from_time_range_on_date_same_day_and_cross_midnight() {
        // Same day: 09:00-17:00 on 2023-03-01
        let r1 = DateTimeRange::from_time_range_on_date(t(9, 0, 0), t(17, 0, 0), d(2023, 3, 1));
        assert_eq!(r1.start(), dt(2023, 3, 1, 9, 0, 0));
        assert_eq!(r1.end(), dt(2023, 3, 1, 17, 0, 0));
        assert_eq!(r1.duration(), Duration::of_seconds(8 * 3600));

        // Cross midnight: 22:00-06:00 should end on next day 06:00
        let r2 = DateTimeRange::from_time_range_on_date(t(22, 0, 0), t(6, 0, 0), d(2023, 3, 1));
        assert_eq!(r2.start(), dt(2023, 3, 1, 22, 0, 0));
        assert_eq!(r2.end(), dt(2023, 3, 2, 6, 0, 0));
        assert_eq!(r2.duration(), Duration::of_seconds(8 * 3600));
    }

    #[test]
    fn all_day_builds_midnight_to_next_midnight_24h() {
        let r = DateTimeRange::all_day(d(2024, 2, 29)); // leap day
        assert_eq!(r.start(), dt(2024, 2, 29, 0, 0, 0));
        assert_eq!(r.end(), dt(2024, 3, 1, 0, 0, 0));
        assert_eq!(r.duration(), Duration::of_seconds(24 * 3600));
    }

    #[test]
    fn contains_and_contains_exclusive_respect_boundaries() {
        let r = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 17, 0, 0));
        assert!(r.contains(dt(2023, 1, 1, 9, 0, 0))); // inclusive start
        assert!(r.contains(dt(2023, 1, 1, 17, 0, 0))); // inclusive end
        assert!(r.contains_exclusive(dt(2023, 1, 1, 12, 0, 0)));
        assert!(!r.contains_exclusive(dt(2023, 1, 1, 9, 0, 0)));
        assert!(!r.contains_exclusive(dt(2023, 1, 1, 17, 0, 0)));
    }

    #[test]
    fn overlaps_variants_and_overlap_range_duration() {
        let a = DateTimeRange::of(dt(2023, 5, 10, 9, 0, 0), dt(2023, 5, 10, 12, 0, 0));
        let b = DateTimeRange::of(dt(2023, 5, 10, 11, 0, 0), dt(2023, 5, 10, 13, 0, 0));
        let c_touch_right = DateTimeRange::of(dt(2023, 5, 10, 12, 0, 0), dt(2023, 5, 10, 14, 0, 0));
        let d_disjoint = DateTimeRange::of(dt(2023, 5, 10, 14, 0, 1), dt(2023, 5, 10, 15, 0, 0));

        // overlaps is inclusive
        assert!(a.overlaps(&b));
        assert!(a.overlaps(&c_touch_right)); // touch at 12:00
        assert!(!a.overlaps(&d_disjoint));

        // overlaps_exclusive requires strict
        assert!(a.overlaps_exclusive(&b));
        assert!(!a.overlaps_exclusive(&c_touch_right));

        // overlaps_completely
        let inner = DateTimeRange::of(dt(2023, 5, 10, 9, 30, 0), dt(2023, 5, 10, 11, 0, 0));
        assert!(a.overlaps_completely(&inner));
        assert!(!inner.overlaps_completely(&a));

        // overlap_range and overlap_duration
        let r = a.overlap_range(&b).unwrap();
        assert_eq!(r.start(), dt(2023, 5, 10, 11, 0, 0));
        assert_eq!(r.end(), dt(2023, 5, 10, 12, 0, 0));
        assert_eq!(a.overlap_duration(&b), Duration::of_seconds(3600));

        // touching -> zero duration but Some(range)
        let r2 = a.overlap_range(&c_touch_right).unwrap();
        assert_eq!(r2.start(), dt(2023, 5, 10, 12, 0, 0));
        assert_eq!(r2.end(), dt(2023, 5, 10, 12, 0, 0));
        assert_eq!(a.overlap_duration(&c_touch_right), Duration::of_seconds(0));

        // disjoint -> None and zero duration
        assert!(a.overlap_range(&d_disjoint).is_none());
        assert_eq!(a.overlap_duration(&d_disjoint), Duration::of_seconds(0));
    }

    #[test]
    fn ordering_and_equality_and_hash() {
        let a = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 0, 0));
        let b = DateTimeRange::of(dt(2023, 1, 1, 8, 0, 0), dt(2023, 1, 1, 9, 30, 0));
        let c = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 0, 0));
        let d_shorter_end = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 9, 30, 0));
        let e_longer_end = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 30, 0));

        // Eq compares bounds
        assert_eq!(a, c);
        assert_ne!(a, b);

        // Ord sorts by start then end
        let mut v = vec![a.clone(), b.clone()];
        v.sort();
        assert_eq!(v, vec![b, a.clone()]);

        // When starts are equal, ordering falls back to end
        assert!(d_shorter_end < a); // same start, earlier end
        assert!(e_longer_end > a); // same start, later end

        // Hash consistent with Eq (basic smoke test: equal values hash the same)
        let mut ha = DefaultHasher::new();
        let mut hc = DefaultHasher::new();
        a.hash(&mut ha);
        c.hash(&mut hc);
        assert_eq!(ha.finish(), hc.finish());
    }

    #[test]
    fn with_period_indexing_and_iteration_behave_like_previous_type() {
        use super::PeriodIteration;
        let r = DateTimeRange::of(dt(2023, 5, 1, 9, 15, 0), dt(2023, 5, 1, 16, 45, 0));
        let w = r.with_period_len(60);
        assert_eq!(w.start_index(), 9); // floor(555/60)=9
        assert_eq!(w.end_index(), 16); // floor(1005/60)=16
        assert_eq!(w.index_range(), (9, 15));
        assert_eq!(w.number_of_periods(), 7); // 7h30m -> 450/60=7
        assert_eq!(w.period_length_in_minutes(), 60);

        // Iterate hourly points from 09:15, 10:15, ... up to <= end (16:15)
        let via_iter: Vec<_> = w.iter().collect();
        assert_eq!(via_iter.first().copied().unwrap(), dt(2023, 5, 1, 9, 15, 0));
        assert_eq!(via_iter.last().copied().unwrap(), dt(2023, 5, 1, 16, 15, 0));
    }
}