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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Provides calendar/scheduling utilities
//! Parses and serializes string RRULEs with duration and provides api to query if time slot is available.

use chrono::{DateTime, Duration, NaiveDateTime, TimeZone, Utc};
use iso8601_duration::Duration as Iso8601Duration;
pub use rrule::{RRuleSet, Tz as RRuleTz};
use std::cmp::{max, min};
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Sub;
use std::str::FromStr;

/// The maximum number of events to return from an RRULE
const MAX_EVENT_COUNT: u16 = 100;

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Timeslot {
    pub time_start: DateTime<Utc>,
    pub time_end: DateTime<Utc>,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TimeslotError {
    NoOverlap,
}

impl Timeslot {
    pub fn duration(&self) -> Duration {
        self.time_end - self.time_start
    }

    pub fn split(&self, min_duration: &Duration, max_duration: &Duration) -> Vec<Timeslot> {
        let mut slots = vec![];
        let mut current_time = self.time_start;

        while current_time < self.time_end {
            let next_time = min(current_time + *max_duration, self.time_end);
            let timeslot = Timeslot {
                time_start: current_time,
                time_end: next_time,
            };

            if timeslot.duration() >= *min_duration {
                slots.push(timeslot);
            }

            current_time = next_time;
        }

        slots
    }

    pub fn overlap(&self, other: &Self) -> Result<Self, TimeslotError> {
        //
        //               |      self           |
        //         |        other         |
        //               |   overlap      |
        let slot = Self {
            time_start: max(self.time_start, other.time_start),
            time_end: min(self.time_end, other.time_end),
        };

        if slot.time_start >= slot.time_end {
            return Err(TimeslotError::NoOverlap);
        }

        Ok(slot)
    }
}

impl Sub for Timeslot {
    type Output = Vec<Timeslot>;

    fn sub(self, other: Self) -> Self::Output {
        // Occupied slot ends before available slot starts
        //  or occupied slot starts after available slot ends
        if self.time_end <= other.time_start || self.time_start >= other.time_end {
            return vec![self];
        }

        // Occupied slot starts before and ends after available slot
        // |           OCCUPIED           |
        //                +
        //     | Available | Available |
        //                =
        //       (no available slots)
        if other.time_start <= self.time_start && other.time_end >= self.time_end {
            // other timeslot obliterates this available timeslot
            return vec![];
        }

        // Occupied slot right in the middle of the available slot, so we need to split the available slot
        //       | Occupied |
        //            +
        // |     Available          |
        //            =
        // | Av. |           | Av.  |
        if self.time_start < other.time_start && self.time_end > other.time_end {
            return vec![
                Timeslot {
                    time_start: self.time_start,
                    time_end: other.time_start,
                },
                Timeslot {
                    time_start: other.time_end,
                    time_end: self.time_end,
                },
            ];
        }

        //        | Occupied |
        //       +
        // | Available |
        //       =
        //  | Av. |
        if self.time_start < other.time_start && self.time_end <= other.time_end {
            return vec![Timeslot {
                time_start: self.time_start,
                time_end: other.time_start,
            }];
        }

        //
        // |     Occupied     |
        //            +
        //      |     Available      |
        //            =
        //                     | Av. |
        if self.time_start >= other.time_start && self.time_end > other.time_end {
            return vec![Timeslot {
                time_start: other.time_end,
                time_end: self.time_end,
            }];
        }

        router_warn!("(sub) Unhandled case: {:?} {:?}", self, other);

        vec![]
    }
}

// /// formats chrono::DateTime to string in format: `YYYYMMDDThhmmssZ`, e.g. 20221026T133000Z
fn datetime_to_ical_format(dt: &DateTime<RRuleTz>) -> String {
    router_debug!("(datetime_to_ical_format) {:?}", dt);
    let mut tz_prefix = String::new();
    let mut tz_postfix = String::new();
    router_debug!("(datetime_to_ical_format) tz: {:?}", dt.timezone());
    let tz = dt.timezone();
    match tz {
        RRuleTz::Local(_) => {}
        RRuleTz::Tz(tz) => match tz {
            chrono_tz::Tz::UTC => {
                tz_postfix = "Z".to_string();
            }
            tz => {
                tz_prefix = format!(";TZID={}:", tz.name());
            }
        },
    }

    let dt = dt.format("%Y%m%dT%H%M%S");
    router_debug!("(datetime_to_ical_format) dt: {:?}", dt);
    format!("{}{}{}", tz_prefix, dt, tz_postfix)
}

/// Wraps rruleset and their duration
#[derive(Debug, Clone)]
pub struct RecurrentEvent {
    /// The rruleset with recurrence rules
    pub rrule_set: RRuleSet,
    /// The duration of the event
    pub duration: Duration,
}
///Calendar implementation for recurring events using the rrule crate and duration iso8601_duration crate
#[derive(Debug, Clone)]
pub struct Calendar {
    ///Vec of rrulesets and their duration
    pub events: Vec<RecurrentEvent>,
}

#[derive(Debug, Copy, Clone)]
pub enum CalendarError {
    Rrule,
    RruleSet,
    HeaderPartsLength,
    Duration,
    Internal,
}

impl Display for CalendarError {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self {
            CalendarError::Rrule => write!(f, "Invalid rrule"),
            CalendarError::RruleSet => write!(f, "Invalid rrule set"),
            CalendarError::HeaderPartsLength => write!(f, "Invalid header parts length"),
            CalendarError::Duration => write!(f, "Invalid duration"),
            CalendarError::Internal => write!(f, "Internal error"),
        }
    }
}

impl FromStr for Calendar {
    type Err = CalendarError;

    /// Parses multiline string into a vector of `RecurrentEvents`
    /// Using `rrule` library is not sufficient to capture duration of the event so we need to parse it
    /// manually ane remove it from the string before letting rrule parse the rest
    /// Duration has to be the last part of the RRULE_SET header after DTSTART e.g.
    ///   "DTSTART:20221020T180000Z;DURATION:PT1H" not "DURATION:PT1H;DTSTART:20221020T180000Z"
    /// Duration is in ISO8601 format (`iso8601_duration` crate)
    fn from_str(calendar_str: &str) -> Result<Self, Self::Err> {
        router_debug!("(from_str) Parsing calendar: {}", calendar_str);
        let rrule_sets: Vec<&str> = calendar_str
            .split("DTSTART:")
            .filter(|s| !s.is_empty())
            .collect();
        router_debug!("(from_str) rrule_sets: {:?}", rrule_sets);
        let mut recurrent_events: Vec<RecurrentEvent> = Vec::new();
        for rrule_set_str in rrule_sets {
            router_debug!("(from_str) rrule_set_str: {}", rrule_set_str);
            let rrules_with_header: Vec<&str> = rrule_set_str
                .split('\n')
                .filter(|s| !s.is_empty())
                .collect();
            if rrules_with_header.len() < 2 {
                router_error!(
                    "(from_str) Invalid rrule {} with header length: {}",
                    calendar_str,
                    rrules_with_header.len()
                );
                return Err(CalendarError::Rrule);
            }
            let header = rrules_with_header[0];
            let rrules = &rrules_with_header[1..];
            let header_parts: Vec<&str> = header
                .split(";DURATION:")
                .filter(|s| !s.is_empty())
                .collect();
            if header_parts.len() != 2 {
                router_error!(
                    "(from_str) Invalid header parts length: {}",
                    header_parts.len()
                );
                return Err(CalendarError::HeaderPartsLength);
            }

            let dtstart = header_parts[0];
            let duration: &str = header_parts[1];
            let Ok(duration) = duration.parse::<Iso8601Duration>() else {
                router_error!("(from_str) Invalid duration: {:?}", duration);
                return Err(CalendarError::Duration);
            };

            let Some(duration) = duration.to_chrono() else {
                router_error!(
                    "(from_str) Could not convert duration to chrono::DateTime: {:?}",
                    duration
                );
                return Err(CalendarError::Duration);
            };

            let str = "DTSTART:".to_owned() + dtstart + "\n" + rrules.join("\n").as_str();
            let rrset_res = RRuleSet::from_str(&str);

            let Ok(rrule_set) = rrset_res else {
                router_error!("(from_str) Invalid rrule set: {:?}", rrset_res.unwrap_err());
                return Err(CalendarError::RruleSet);
            };

            recurrent_events.push(RecurrentEvent {
                rrule_set,
                duration,
            });
        }
        router_debug!("(from_str) Parsed calendar: {:?}", recurrent_events);
        Ok(Calendar {
            events: recurrent_events,
        })
    }
}

impl Display for Calendar {
    /// Formats `Calendar` into multiline string which can be stored in the database
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        for event in &self.events {
            if let Err(e) = writeln!(
                f,
                "DTSTART:{};DURATION:{}",
                datetime_to_ical_format(event.rrule_set.get_dt_start()),
                &event.duration
            ) {
                router_error!("(Calendar fmt) {}", e);
                return Err(std::fmt::Error);
            }

            for rrule in event.rrule_set.get_rrule() {
                if let Err(e) = writeln!(f, "RRULE:{}", rrule) {
                    router_error!("(Calendar fmt) {}", e);
                    return Err(std::fmt::Error);
                }
            }

            for rdate in event.rrule_set.get_rdate() {
                if let Err(e) = writeln!(f, "RDATE:{}", datetime_to_ical_format(rdate)) {
                    router_error!("(Calendar fmt) {}", e);
                    return Err(std::fmt::Error);
                }
            }
        }

        Ok(())
    }
}

impl Calendar {
    /// Converts a date into a sorted list of timeslots for a given date
    pub fn to_timeslots(
        &self,
        time_start: &DateTime<Utc>,
        time_end: &DateTime<Utc>,
    ) -> Result<Vec<Timeslot>, CalendarError> {
        // Want to grab the full day's schedule, so we need to expand the start and end times
        let delta = Duration::try_days(1).ok_or_else(|| {
            router_error!("(Calendar to_timeslots) error creating time delta.");
            CalendarError::Internal
        })?;

        let start: NaiveDateTime = (*time_start).naive_utc() - delta;
        let end: NaiveDateTime = (*time_end).naive_utc() + delta;

        // convert to a Tz type understood by the rrule library
        let start: DateTime<rrule::Tz> = rrule::Tz::UTC.from_utc_datetime(&start);
        let end: DateTime<rrule::Tz> = rrule::Tz::UTC.from_utc_datetime(&end);

        let mut timeslots = vec![];
        for event in &self.events {
            let rrule = event.rrule_set.clone().after(start).before(end);
            for dt in rrule.all(MAX_EVENT_COUNT).dates {
                router_debug!(
                    "(Calendar to_timeslots) Found timeslot for event {:?}: {:?}",
                    event,
                    dt
                );

                let slot_start = dt.with_timezone(&Utc);
                let slot_end = slot_start + event.duration;
                if slot_start >= *time_end || slot_end <= *time_start {
                    continue;
                }

                let timeslot = Timeslot {
                    time_start: max(slot_start, *time_start),
                    time_end: min(slot_end, *time_end),
                };

                router_debug!("(Calendar to_timeslots) timeslot: {:?}", &timeslot);
                timeslots.push(timeslot);
            }
        }

        Ok(timeslots)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, TimeZone, Utc};
    use std::str::FromStr;

    const CAL_WORKDAYS_8AM_6PM: &str = "DTSTART:20221020T180000Z;DURATION:PT14H\n\
    RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n\
    DTSTART:20221022T000000Z;DURATION:PT24H\n\
    RRULE:FREQ=DAILY;BYDAY=SA,SU";

    const _WITH_1HR_DAILY_BREAK: &str = "\n\
    DTSTART:20221020T120000Z;DURATION:PT1H\n\
    RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR";

    const _WITH_ONE_OFF_BLOCK: &str = "\n\
    DTSTART:20221026T133000Z;DURATION:PT3H\n\
    RDATE:20221026T133000Z";

    const INVALID_CALENDAR: &str = "DURATION:PT3H;DTSTART:20221026T133000Z;\n\
    RRULE:FREQ=DAILY;BYDAY=SA,SU";

    #[test]
    fn test_parse_calendar() {
        let calendar = Calendar::from_str(CAL_WORKDAYS_8AM_6PM).unwrap();
        assert_eq!(calendar.events.len(), 2);
        assert_eq!(
            calendar.events[0].duration,
            Duration::try_hours(14).unwrap()
        );
        assert_eq!(
            calendar.events[1].duration,
            Duration::try_hours(24).unwrap()
        );
    }

    #[test]
    fn test_save_and_load_calendar() {
        let orig_cal_str =
            &(CAL_WORKDAYS_8AM_6PM.to_owned() + _WITH_1HR_DAILY_BREAK + _WITH_ONE_OFF_BLOCK);
        let calendar = Calendar::from_str(orig_cal_str).unwrap();
        let cal_str = calendar.to_string();
        let calendar = Calendar::from_str(&cal_str).unwrap();
        assert_eq!(calendar.events.len(), 4);
        assert_eq!(
            calendar.events[0].duration,
            Duration::try_hours(14).unwrap()
        );
    }

    #[test]
    #[should_panic]
    fn test_invalid_input() {
        let _calendar = Calendar::from_str(INVALID_CALENDAR).unwrap();
    }

    #[test]
    fn test_calendar_to_timeslots() {
        // 8AM to 12PM, 2PM to 6PM
        let calendar = "DTSTART:20221020T080000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n\
        DTSTART:20221020T140000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n";

        let calendar = Calendar::from_str(calendar).unwrap();
        assert_eq!(calendar.events.len(), 2);

        let cal_start = Utc.with_ymd_and_hms(2022, 10, 20, 8, 0, 0).unwrap();
        let expected_timeslots = vec![
            Timeslot {
                time_start: cal_start,                                 // 8AM
                time_end: cal_start + Duration::try_hours(4).unwrap(), // 12PM
            },
            Timeslot {
                time_start: cal_start + Duration::try_hours(6).unwrap(), // 2PM
                time_end: cal_start + Duration::try_hours(10).unwrap(),  // 6PM
            },
        ];

        // Get full day schedule
        let timeslots = calendar
            .to_timeslots(
                &(cal_start - Duration::try_hours(1).unwrap()),
                &(cal_start + Duration::try_hours(12).unwrap()),
            )
            .unwrap();
        assert_eq!(timeslots.len(), 2);
        assert_eq!(timeslots, expected_timeslots);
    }

    #[test]
    fn test_calendar_to_timeslots_cropped() {
        // 8AM to 12PM, 2PM to 6PM
        let calendar = "DTSTART:20221020T080000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n\
        DTSTART:20221020T140000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n";

        let calendar = Calendar::from_str(calendar).unwrap();
        assert_eq!(calendar.events.len(), 2);

        let cal_start = Utc.with_ymd_and_hms(2022, 10, 20, 8, 0, 0).unwrap();

        // Crop to 10AM to 6PM
        let start: DateTime<Utc> = cal_start + Duration::try_hours(2).unwrap();
        let end: DateTime<Utc> = cal_start + Duration::try_hours(8).unwrap();

        let expected_timeslots = vec![
            Timeslot {
                time_start: start,                                     // 10 AM
                time_end: cal_start + Duration::try_hours(4).unwrap(), // 12PM
            },
            Timeslot {
                time_start: cal_start + Duration::try_hours(6).unwrap(), // 2PM
                time_end: end,                                           // 4PM
            },
        ];

        // Get full day schedule
        let timeslots = calendar.to_timeslots(&start, &end).unwrap();
        assert_eq!(timeslots.len(), 2);
        assert_eq!(timeslots, expected_timeslots);
    }

    #[test]
    fn test_calendar_to_timeslots_cropped_to_single() {
        // 8AM to 12PM, 2PM to 6PM
        let calendar = "DTSTART:20221020T080000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n\
        DTSTART:20221020T140000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR\n";

        let calendar = Calendar::from_str(calendar).unwrap();
        assert_eq!(calendar.events.len(), 2);

        let cal_start = Utc.with_ymd_and_hms(2022, 10, 20, 8, 0, 0).unwrap();

        // Crop to 10AM to 6PM
        let start: DateTime<Utc> = cal_start + Duration::try_hours(2).unwrap();
        let end: DateTime<Utc> = cal_start + Duration::try_hours(3).unwrap();

        let expected_timeslots = vec![Timeslot {
            time_start: start, // 10 AM
            time_end: end,     // 11AM
        }];

        // Get full day schedule
        let timeslots = calendar.to_timeslots(&start, &end).unwrap();
        assert_eq!(timeslots.len(), 1);
        assert_eq!(timeslots, expected_timeslots);
    }

    #[test]
    fn test_calendar_to_timeslots_future() {
        // 8AM to 12PM, 2PM to 6PM
        let calendar = "DTSTART:20221020T080000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR,SA,SU\n\
        DTSTART:20221020T140000Z;DURATION:PT4H\n\
        RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR,SA,SU"
            .to_string();

        let calendar = Calendar::from_str(&calendar).unwrap();
        assert_eq!(calendar.events.len(), 2);

        let cal_start = Utc.with_ymd_and_hms(2023, 10, 20, 8, 0, 0).unwrap();

        // Crop to 10AM to 6PM
        let start: DateTime<Utc> = cal_start - Duration::try_hours(2).unwrap();
        let end: DateTime<Utc> = cal_start + Duration::try_hours(16).unwrap();

        let expected_timeslots = vec![
            Timeslot {
                time_start: cal_start,                                 // 8
                time_end: cal_start + Duration::try_hours(4).unwrap(), // 12
            },
            Timeslot {
                time_start: cal_start + Duration::try_hours(6).unwrap(), // 14
                time_end: cal_start + Duration::try_hours(10).unwrap(),  // 18
            },
        ];

        // Get full day schedule
        let timeslots = calendar.to_timeslots(&start, &end).unwrap();
        assert_eq!(timeslots.len(), 2);
        assert_eq!(timeslots, expected_timeslots);
    }

    /// |         a         |
    ///           -
    ///      |    b    |
    ///           =
    /// |    |         |    |
    #[test]
    fn test_timeslot_sub_cleave() {
        let chrono::LocalResult::Single(dt_start) = Utc.with_ymd_and_hms(2023, 10, 24, 0, 0, 0)
        else {
            panic!();
        };

        let timeslot_a = Timeslot {
            time_start: dt_start,
            time_end: dt_start + Duration::try_hours(3).unwrap(),
        };

        let timeslot_b = Timeslot {
            time_start: dt_start + Duration::try_hours(1).unwrap(),
            time_end: dt_start + Duration::try_hours(2).unwrap(),
        };

        let timeslots = timeslot_a - timeslot_b;
        assert_eq!(timeslots.len(), 2);
        assert_eq!(
            timeslots,
            vec![
                Timeslot {
                    time_start: dt_start,
                    time_end: dt_start + Duration::try_hours(1).unwrap(),
                },
                Timeslot {
                    time_start: dt_start + Duration::try_hours(2).unwrap(),
                    time_end: dt_start + Duration::try_hours(3).unwrap(),
                },
            ]
        );
    }

    /// |         a         |
    ///           -
    ///                |    b    |
    ///           =
    /// |              |
    #[test]
    fn test_timeslot_sub_crop_end() {
        let chrono::LocalResult::Single(dt_start) = Utc.with_ymd_and_hms(2023, 10, 24, 0, 0, 0)
        else {
            panic!();
        };

        let timeslot_a = Timeslot {
            time_start: dt_start,
            time_end: dt_start + Duration::try_hours(3).unwrap(),
        };

        let timeslot_b = Timeslot {
            time_start: dt_start + Duration::try_hours(2).unwrap(),
            time_end: dt_start + Duration::try_hours(4).unwrap(),
        };

        let timeslots = timeslot_a - timeslot_b;
        assert_eq!(timeslots.len(), 1);
        assert_eq!(
            timeslots,
            vec![Timeslot {
                time_start: dt_start,
                time_end: dt_start + Duration::try_hours(2).unwrap(),
            },]
        );
    }

    ///       |         a         |
    ///           -
    /// |    b    |
    ///           =
    ///           |               |
    #[test]
    fn test_timeslot_sub_crop_start() {
        let chrono::LocalResult::Single(dt_start) = Utc.with_ymd_and_hms(2023, 10, 24, 0, 0, 0)
        else {
            panic!();
        };

        let timeslot_a = Timeslot {
            time_start: dt_start + Duration::try_hours(1).unwrap(),
            time_end: dt_start + Duration::try_hours(3).unwrap(),
        };

        let timeslot_b = Timeslot {
            time_start: dt_start,
            time_end: dt_start + Duration::try_hours(2).unwrap(),
        };

        let timeslots = timeslot_a - timeslot_b;
        assert_eq!(timeslots.len(), 1);
        assert_eq!(
            timeslots,
            vec![Timeslot {
                time_start: dt_start + Duration::try_hours(2).unwrap(),
                time_end: dt_start + Duration::try_hours(3).unwrap(),
            },]
        );
    }

    #[test]
    fn test_timeslot_sub_no_overlap() {
        let chrono::LocalResult::Single(dt_start) = Utc.with_ymd_and_hms(2023, 10, 24, 0, 0, 0)
        else {
            panic!();
        };

        //           |         a         |
        //           -
        // |    b    |
        //           =
        //           |               |
        let timeslot_a = Timeslot {
            time_start: dt_start + Duration::try_hours(2).unwrap(),
            time_end: dt_start + Duration::try_hours(3).unwrap(),
        };

        let timeslot_b = Timeslot {
            time_start: dt_start,
            time_end: dt_start + Duration::try_hours(2).unwrap(),
        };

        let timeslots = timeslot_a - timeslot_b;
        assert_eq!(timeslots.len(), 1);
        assert_eq!(timeslots, vec![timeslot_a]);

        // |         a         |
        //           -
        //                     |    b    |
        //           =
        //           |               |
        let timeslot_a = Timeslot {
            time_start: dt_start,
            time_end: dt_start + Duration::try_hours(1).unwrap(),
        };

        let timeslot_b = Timeslot {
            time_start: dt_start + Duration::try_hours(1).unwrap(),
            time_end: dt_start + Duration::try_hours(2).unwrap(),
        };

        let timeslots = timeslot_a - timeslot_b;
        assert_eq!(timeslots.len(), 1);
        assert_eq!(timeslots, vec![timeslot_a]);
    }
}