periodical 0.3.0

Management of all kinds of time intervals, use it to manage schedules, find overlaps, and more!
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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Interval metadata
//!
//! Contains information about intervals such as [`Relativity`], [`Openness`],
//! [`OpeningDirection`], and more.

use std::error::Error;
use std::fmt::Display;
use std::ops::Bound;
use std::time::Duration as StdDuration;

#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Global interval trait
///
/// All intervals implement this trait.
///
/// This trait is used for restricting parameters to intervals when the
/// parameter itself is not important, but want to avoid implementing the method
/// on non-interval types.
///
/// For example, extending an
/// [`UnboundedInterval`](crate::intervals::special::UnboundedInterval) with any
/// other interval will produce an
/// [`UnboundedInterval`](crate::intervals::special::UnboundedInterval) anyways,
/// but we don't want to allow calls like `unbounded_interval.extend(3)`,
/// so this trait is used to restrict this parameter to interval types only.
pub trait Interval {}

/// Interval openness
///
/// Describes how open is the interval is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Openness {
    /// Defined start and end bounds
    Bounded,
    /// One of the bounds is known, but the interval continues to infinity in
    /// one direction
    HalfBounded,
    /// Covers the entire time
    Unbounded,
    /// Is technically bounded to time, but nowhere precise.
    ///
    /// Used for [`EmptyInterval`](crate::intervals::special::EmptyInterval)
    Empty,
}

impl Display for Openness {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bounded => write!(f, "Bounded"),
            Self::HalfBounded => write!(f, "Half-bounded"),
            Self::Unbounded => write!(f, "Unbounded"),
            Self::Empty => write!(f, "Empty"),
        }
    }
}

/// Possession of [`Openness`]
///
/// This trait should be implemented by all intervals supporting the concept of
/// [`Openness`].
pub trait HasOpenness {
    /// Returns the [`Openness`] of the interval
    #[must_use]
    fn openness(&self) -> Openness;
}

/// Interval relativity
///
/// An interval relativity defines in which kind of time it lives in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Relativity {
    /// Interval lives in absolute time
    ///
    /// This means that it uses an absolute [`Zoned`](jiff::Zoned).
    Absolute,
    /// Interval lives in relative time
    ///
    /// This means that it uses [`SignedDuration`](jiff::SignedDuration)s, also
    /// known as offsets.
    ///
    /// For example, if you compare and absolute interval to a point in time,
    /// e.g. this day compared to this year's 1st of January at midnight,
    /// you will end up with a relative interval.
    Relative,
    /// Interval isn't bound to relativity
    ///
    /// This means the interval uses a concept rather than representing itself
    /// through a time frame.
    ///
    /// It is used by intervals such as
    /// [`UnboundedInterval`](crate::intervals::special::UnboundedInterval)
    /// and [`EmptyInterval`](crate::intervals::special::EmptyInterval).
    ///
    /// The variant is called "Any" as those special intervals can be
    /// interpreted in both absolute and relative time frames.
    Any,
}

impl Display for Relativity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Absolute => write!(f, "Absolute"),
            Self::Relative => write!(f, "Relative"),
            Self::Any => write!(f, "Any relativity"),
        }
    }
}

/// Possession of [`Relativity`]
///
/// This trait should be implemented by all interval supporting the concept of
/// [`Relativity`].
pub trait HasRelativity {
    /// Returns the [`Relativity`] of the interval
    #[must_use]
    fn relativity(&self) -> Relativity;
}

/// Opening direction of half-bounded intervals
///
/// This indicates which _direction_ the half-bounded interval covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum OpeningDirection {
    /// Infinitely towards future
    ToFuture,
    /// Infinitely towards past
    ToPast,
}

impl OpeningDirection {
    /// Returns the opposite [`OpeningDirection`]
    #[must_use]
    pub fn opposite(&self) -> Self {
        match self {
            Self::ToFuture => OpeningDirection::ToPast,
            Self::ToPast => OpeningDirection::ToFuture,
        }
    }
}

impl Display for OpeningDirection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ToFuture => write!(f, "Opening direction towards future"),
            Self::ToPast => write!(f, "Opening direction towards past"),
        }
    }
}

/// Converts a [`bool`] into an [`OpeningDirection`]
///
/// The boolean is interpreted as _is it going to future?_
impl From<bool> for OpeningDirection {
    fn from(goes_to_future: bool) -> Self {
        if goes_to_future {
            OpeningDirection::ToFuture
        } else {
            OpeningDirection::ToPast
        }
    }
}

pub trait HasOpeningDirection {
    #[must_use]
    fn opening_direction(&self) -> OpeningDirection;
}

/// Infinitesimal duration variation of an interval
///
/// Represents the infinitesimal duration variation(s) created by [exclusive bounds](BoundInclusivity::Exclusive).
///
/// An infinitesimal duration is represented by an epsilon sign, hence the name.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Epsilon {
    /// No epsilon
    #[default]
    None,
    /// Epsilon variation on start bound
    Start,
    /// Epsilon variation on end bound
    End,
    /// Epsilon variation on both bounds
    Both,
}

impl Epsilon {
    /// Returns whether an epsilon is present
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::Epsilon;
    /// assert!(Epsilon::Start.has_epsilon());
    /// assert!(Epsilon::End.has_epsilon());
    /// assert!(Epsilon::Both.has_epsilon());
    /// assert!(!Epsilon::None.has_epsilon());
    /// ```
    #[must_use]
    pub fn has_epsilon(&self) -> bool {
        !matches!(self, Self::None)
    }

    /// Returns whether the start bound has an epsilon
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::Epsilon;
    /// assert!(Epsilon::Start.has_epsilon_on_start());
    /// assert!(Epsilon::Both.has_epsilon_on_start());
    /// assert!(!Epsilon::None.has_epsilon_on_start());
    /// assert!(!Epsilon::End.has_epsilon_on_start());
    /// ```
    #[must_use]
    pub fn has_epsilon_on_start(&self) -> bool {
        matches!(self, Self::Start | Self::Both)
    }

    /// Returns whether the end bound has an epsilon
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::Epsilon;
    /// assert!(Epsilon::End.has_epsilon_on_end());
    /// assert!(Epsilon::Both.has_epsilon_on_end());
    /// assert!(!Epsilon::None.has_epsilon_on_end());
    /// assert!(!Epsilon::Start.has_epsilon_on_end());
    /// ```
    #[must_use]
    pub fn has_epsilon_on_end(&self) -> bool {
        matches!(self, Self::End | Self::Both)
    }

    /// Interprets the epsilon as a specific duration using different duration
    /// interpretations per bound
    ///
    /// # Errors
    ///
    /// If `start_epsilon_duration` + `end_epsilon_duration` overflows,
    /// the method returns [`EpsilonInterpretationDurationOverflowError`].
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::Epsilon;
    /// let start_epsilon_duration = std::time::Duration::from_secs(1);
    /// let end_epsilon_duration = std::time::Duration::from_secs(2);
    ///
    /// assert_eq!(
    ///     Epsilon::None
    ///         .interpret_as_duration_bound_specific(start_epsilon_duration, end_epsilon_duration),
    ///     Ok(std::time::Duration::ZERO),
    /// );
    /// assert_eq!(
    ///     Epsilon::Start
    ///         .interpret_as_duration_bound_specific(start_epsilon_duration, end_epsilon_duration),
    ///     Ok(start_epsilon_duration),
    /// );
    /// assert_eq!(
    ///     Epsilon::End
    ///         .interpret_as_duration_bound_specific(start_epsilon_duration, end_epsilon_duration),
    ///     Ok(end_epsilon_duration),
    /// );
    /// assert_eq!(
    ///     Epsilon::Both
    ///         .interpret_as_duration_bound_specific(start_epsilon_duration, end_epsilon_duration),
    ///     Ok(start_epsilon_duration + end_epsilon_duration)
    /// );
    /// ```
    pub fn interpret_as_duration_bound_specific(
        &self,
        start_epsilon_duration: StdDuration,
        end_epsilon_duration: StdDuration,
    ) -> Result<StdDuration, EpsilonInterpretationDurationOverflowError> {
        match self {
            Self::None => Ok(StdDuration::ZERO),
            Self::Start => Ok(start_epsilon_duration),
            Self::End => Ok(end_epsilon_duration),
            Self::Both => start_epsilon_duration
                .checked_add(end_epsilon_duration)
                .ok_or(EpsilonInterpretationDurationOverflowError),
        }
    }

    /// Interprets the epsilon as a specific duration using the given duration
    ///
    /// # Errors
    ///
    /// If `epsilon_duration * 2` overflows,
    /// the method returns [`EpsilonInterpretationDurationOverflowError`].
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::Epsilon;
    /// let epsilon_duration = std::time::Duration::from_secs(1);
    ///
    /// assert_eq!(
    ///     Epsilon::None.interpret_as_duration(epsilon_duration),
    ///     Ok(std::time::Duration::ZERO),
    /// );
    /// assert_eq!(
    ///     Epsilon::Start.interpret_as_duration(epsilon_duration),
    ///     Ok(epsilon_duration),
    /// );
    /// assert_eq!(
    ///     Epsilon::End.interpret_as_duration(epsilon_duration),
    ///     Ok(epsilon_duration),
    /// );
    /// assert_eq!(
    ///     Epsilon::Both.interpret_as_duration(epsilon_duration),
    ///     Ok(epsilon_duration * 2),
    /// );
    /// ```
    pub fn interpret_as_duration(
        &self,
        epsilon_duration: StdDuration,
    ) -> Result<StdDuration, EpsilonInterpretationDurationOverflowError> {
        self.interpret_as_duration_bound_specific(epsilon_duration, epsilon_duration)
    }
}

impl Display for Epsilon {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => write!(f, "No epsilons"),
            Self::Start => write!(f, "Epsilon on start bound"),
            Self::End => write!(f, "Epsilon on end bound"),
            Self::Both => write!(f, "Epsilon on both bounds"),
        }
    }
}

/// Converts `(BoundInclusivity, BoundInclusivity)` into [`Epsilon`]
///
/// The tuple elements represent the start bound inclusivity and end bound
/// inclusivity, respectively. Exclusive bounds,
/// [`BoundInclusivity::Exclusive`], create an epsilon.
impl From<(BoundInclusivity, BoundInclusivity)> for Epsilon {
    fn from((start_inclusivity, end_inclusivity): (BoundInclusivity, BoundInclusivity)) -> Self {
        match (start_inclusivity, end_inclusivity) {
            (BoundInclusivity::Inclusive, BoundInclusivity::Inclusive) => Epsilon::None,
            (BoundInclusivity::Exclusive, BoundInclusivity::Inclusive) => Epsilon::Start,
            (BoundInclusivity::Inclusive, BoundInclusivity::Exclusive) => Epsilon::End,
            (BoundInclusivity::Exclusive, BoundInclusivity::Exclusive) => Epsilon::Both,
        }
    }
}

/// Duration interpretation overflowed when [`Epsilon`] tried to be interpreted as a duration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EpsilonInterpretationDurationOverflowError;

impl Display for EpsilonInterpretationDurationOverflowError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Epsilon interpretation made the duration overflow")
    }
}

impl Error for EpsilonInterpretationDurationOverflowError {}

/// Interval duration
///
/// Represents the duration of a single interval. It can either be
/// [`Infinite`](Duration::Infinite), or [`Finite`](Duration::Finite), in which
/// case the duration is stored as a standard [`Duration`](StdDuration)
/// and an [`Epsilon`], which serves to represent infinitesimal duration
/// variations created by the use of [exclusive bounds](BoundInclusivity::Exclusive).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Duration {
    /// Finite duration
    Finite(StdDuration, Epsilon),
    /// Infinite duration
    Infinite,
}

impl Duration {
    /// Returns whether the interval duration is finite
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::{Duration, Epsilon};
    /// assert!(Duration::Finite(std::time::Duration::from_hours(1), Epsilon::None).is_finite());
    /// ```
    #[must_use]
    pub fn is_finite(&self) -> bool {
        matches!(self, Duration::Finite(..))
    }

    /// Returns the content of the [`Finite`](Duration::Finite) variant
    ///
    /// Consumes `self` and puts the content of the [`Finite`](Duration::Finite)
    /// variant in an [`Option`]. If instead `self` is another variant, the
    /// method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::{Duration, Epsilon};
    /// assert_eq!(
    ///     Duration::Finite(std::time::Duration::from_hours(2), Epsilon::End).finite(),
    ///     Some((std::time::Duration::from_hours(2), Epsilon::End)),
    /// );
    /// assert_eq!(Duration::Infinite.finite(), None);
    /// ```
    #[must_use]
    pub fn finite(self) -> Option<(StdDuration, Epsilon)> {
        match self {
            Self::Finite(duration, epsilon) => Some((duration, epsilon)),
            Self::Infinite => None,
        }
    }

    /// Returns the content of the [`Finite`](Duration::Finite) variant and
    /// subtracts interpreted epsilon duration from it
    ///
    /// Consumes `self`, then uses the content of the
    /// [`Finite`](Duration::Finite) variant to compute the final
    /// interpreted duration, using [`Epsilon::interpret_as_duration`] under the
    /// hood, and puts the result in an [`Option`]. If instead `self` is
    /// another variant, the method returns [`None`].
    ///
    /// If [`Epsilon::interpret_as_duration`] returns an [`Err`], then the
    /// method returns [`None`].
    ///
    /// If the duration is small or if the interpreted [`Epsilon`]\(s) are
    /// larger than the duration, resulting in a negative duration, the
    /// duration defaults to [an empty duration](StdDuration::ZERO).
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::{Duration, Epsilon};
    /// let epsilon_duration = std::time::Duration::from_secs(1);
    /// let large_epsilon_duration = std::time::Duration::from_hours(2);
    ///
    /// assert_eq!(
    ///     Duration::Finite(std::time::Duration::from_hours(1), Epsilon::End)
    ///         .finite_interpret_epsilon(epsilon_duration),
    ///     Some(std::time::Duration::from_mins(59) + std::time::Duration::from_secs(59)),
    /// );
    /// assert_eq!(
    ///     Duration::Infinite.finite_interpret_epsilon(epsilon_duration),
    ///     None,
    /// );
    /// assert_eq!(
    ///     Duration::Finite(std::time::Duration::from_hours(1), Epsilon::Start)
    ///         .finite_interpret_epsilon(large_epsilon_duration),
    ///     Some(std::time::Duration::ZERO),
    /// );
    /// ```
    #[must_use]
    pub fn finite_interpret_epsilon(self, epsilon_duration: StdDuration) -> Option<StdDuration> {
        let (duration, epsilon) = self.finite()?;
        let interpreted_epsilon = epsilon.interpret_as_duration(epsilon_duration).ok()?;

        Some(duration.checked_sub(interpreted_epsilon).unwrap_or(StdDuration::ZERO))
    }

    /// Returns the [`std::time::Duration`] of the [`Finite`](Duration::Finite)
    /// variant and strips the epsilon duration
    ///
    /// Consumes `self`, then simply returns the [`std::time::Duration`] stored
    /// in the [`Finite`](Duration::Finite) variant, without using the
    /// stored [`Epsilon`]. Puts the result in an [`Option`]. If instead
    /// `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::{Duration, Epsilon};
    /// assert_eq!(
    ///     Duration::Finite(std::time::Duration::from_hours(2), Epsilon::Both).finite_strip_epsilon(),
    ///     Some(std::time::Duration::from_hours(2)),
    /// );
    /// assert_eq!(Duration::Infinite.finite_strip_epsilon(), None);
    /// ```
    #[must_use]
    pub fn finite_strip_epsilon(self) -> Option<StdDuration> {
        Some(self.finite()?.0)
    }
}

impl From<StdDuration> for Duration {
    fn from(duration: StdDuration) -> Self {
        Duration::Finite(duration, Epsilon::default())
    }
}

impl From<(StdDuration, Epsilon)> for Duration {
    fn from((duration, epsilon): (StdDuration, Epsilon)) -> Self {
        Duration::Finite(duration, epsilon)
    }
}

/// Possession of [`Duration`]
///
/// This trait should be implements by all intervals supporting the concept of
/// [`Duration`].
pub trait HasDuration {
    /// Returns the [`Duration`] of the interval
    fn duration(&self) -> Duration;
}

/// Inclusivity of an interval's bound
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum BoundInclusivity {
    /// Includes the point described by the bound
    #[default]
    Inclusive,
    /// Excludes the point described by the bound
    ///
    /// An exclusive bound inclusivity means that virtually anything except the
    /// described point given by the bound is included.
    /// Of course, in the context of an interval it also possesses a dimension
    /// of _direction_.
    ///
    /// Learn more about the directionality of bound inclusivity
    /// in the [documentation of the `intervals` module](crate::intervals).
    Exclusive,
}

impl BoundInclusivity {
    /// Returns the opposite bound inclusivity
    #[must_use]
    pub fn opposite(&self) -> BoundInclusivity {
        match self {
            BoundInclusivity::Inclusive => BoundInclusivity::Exclusive,
            BoundInclusivity::Exclusive => BoundInclusivity::Inclusive,
        }
    }

    /// Creates a [`Bound`] from [`BoundInclusivity`] and a given value
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::ops::Bound;
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// assert_eq!(
    ///     BoundInclusivity::Exclusive.to_range_bound_with(5),
    ///     Bound::Excluded(5),
    /// );
    /// ```
    #[must_use]
    pub fn to_range_bound_with<T>(self, value: T) -> Bound<T> {
        match self {
            Self::Inclusive => Bound::Included(value),
            Self::Exclusive => Bound::Excluded(value),
        }
    }
}

impl Display for BoundInclusivity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Inclusive => write!(f, "Inclusive bound"),
            Self::Exclusive => write!(f, "Exclusive bound"),
        }
    }
}

/// Converts a [`bool`] into a [`BoundInclusivity`]
///
/// The boolean is interpreted as _is it inclusive?_
impl From<bool> for BoundInclusivity {
    fn from(is_inclusive: bool) -> Self {
        if is_inclusive {
            BoundInclusivity::Inclusive
        } else {
            BoundInclusivity::Exclusive
        }
    }
}

/// Possession of [`BoundInclusivity`]
///
/// This trait should be implemented by all interval bounds supporting the
/// concept of [`BoundInclusivity`].
pub trait HasBoundInclusivity {
    /// Returns the [`BoundInclusivity`] of the bound
    #[must_use]
    fn inclusivity(&self) -> BoundInclusivity;
}

/// Capacity of an interval to be empty
pub trait IsEmpty {
    /// Returns whether the interval is empty
    fn is_empty(&self) -> bool;
}

/// Bound extremality — start or end
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BoundExtremality {
    Start,
    End,
}

impl BoundExtremality {
    /// Returns the opposite bound extremality
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::BoundExtremality;
    /// assert_eq!(BoundExtremality::Start.opposite(), BoundExtremality::End);
    /// assert_eq!(BoundExtremality::End.opposite(), BoundExtremality::Start);
    /// ```
    #[must_use]
    pub fn opposite(self) -> Self {
        match self {
            Self::Start => Self::End,
            Self::End => Self::Start,
        }
    }
}

/// Capacity of a bound to have an associated extreme (start/end)
pub trait HasBoundExtremality {
    /// Returns the associated [`BoundExtremality`]
    #[must_use]
    fn bound_extremality(&self) -> BoundExtremality;
}

/// Type of interval
///
/// Represents the different kinds of intervals that exist, not only
/// the openness of a given interval.
///
/// This type is particularly useful as an identifier.
///
/// If you need to associate a [`Relativity`] to it, see [`IntervalTypeWithRel`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalType {
    /// An [empty interval](crate::intervals::special::EmptyInterval)
    Empty,
    /// A bounded interval
    Bounded,
    /// A half-bounded interval with its [opening direction](OpeningDirection)
    HalfBounded(OpeningDirection),
    /// An [unbounded interval](crate::intervals::special::UnboundedInterval)
    Unbounded,
}

impl IntervalType {
    /// Attempts to associate the interval type with the given [`Relativity`]
    ///
    /// # Errors
    ///
    /// Returns [`IntervalTypeWithRelTryFromIntervalTypeAndRel`] if the given [`Relativity`]
    /// is not associable with the [`IntervalType`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use periodical::intervals::meta::{IntervalType, IntervalTypeWithRel, Relativity};
    /// assert_eq!(
    ///     IntervalType::Bounded.try_with_rel(Relativity::Absolute)?,
    ///     IntervalTypeWithRel::AbsBounded,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn try_with_rel(
        self,
        relativity: Relativity,
    ) -> Result<IntervalTypeWithRel, IntervalTypeWithRelTryFromIntervalTypeAndRel> {
        IntervalTypeWithRel::try_from((self, relativity))
    }
}

impl IsEmpty for IntervalType {
    fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }
}

impl HasOpenness for IntervalType {
    fn openness(&self) -> Openness {
        match self {
            Self::Empty => Openness::Empty,
            Self::Bounded => Openness::Bounded,
            Self::HalfBounded(_) => Openness::HalfBounded,
            Self::Unbounded => Openness::Unbounded,
        }
    }
}

impl From<IntervalTypeWithRel> for IntervalType {
    fn from(value: IntervalTypeWithRel) -> Self {
        match value {
            IntervalTypeWithRel::Empty => Self::Empty,
            IntervalTypeWithRel::AbsBounded | IntervalTypeWithRel::RelBounded => Self::Bounded,
            IntervalTypeWithRel::AbsHalfBounded(opening_direction)
            | IntervalTypeWithRel::RelHalfBounded(opening_direction) => Self::HalfBounded(opening_direction),
            IntervalTypeWithRel::Unbounded => Self::Unbounded,
        }
    }
}

/// Capacity of an interval to have an associated [`IntervalType`]
pub trait HasIntervalType {
    /// Returns the corresponding [`IntervalType`] of the interval type
    #[must_use]
    fn interval_type(&self) -> IntervalType;
}

/// Type of interval with relativity included
///
/// Represents the different kinds of intervals that exist, similarly to [`IntervalType`],
/// but with their respective [`Relativity`] included.
///
/// This type is particularly useful as an identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalTypeWithRel {
    /// An [empty interval](crate::intervals::special::EmptyInterval)
    Empty,
    /// A [bounded absolute interval](crate::intervals::absolute::BoundedAbsInterval)
    AbsBounded,
    /// A [bounded relative interval](crate::intervals::relative::BoundedRelInterval)
    RelBounded,
    /// A [half-bounded absolute interval](crate::intervals::absolute::HalfBoundedAbsInterval)
    /// with its [opening direction](OpeningDirection)
    AbsHalfBounded(OpeningDirection),
    /// A [half-bounded relative interval](crate::intervals::relative::HalfBoundedRelInterval)
    /// with its [opening direction](OpeningDirection)
    RelHalfBounded(OpeningDirection),
    /// An [unbounded interval](crate::intervals::special::UnboundedInterval)
    Unbounded,
}

impl IsEmpty for IntervalTypeWithRel {
    fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }
}

impl HasRelativity for IntervalTypeWithRel {
    fn relativity(&self) -> Relativity {
        match self {
            Self::Empty | Self::Unbounded => Relativity::Any,
            Self::AbsBounded | Self::AbsHalfBounded(_) => Relativity::Absolute,
            Self::RelBounded | Self::RelHalfBounded(_) => Relativity::Relative,
        }
    }
}

impl HasOpenness for IntervalTypeWithRel {
    fn openness(&self) -> Openness {
        match self {
            Self::Empty => Openness::Empty,
            Self::AbsBounded | Self::RelBounded => Openness::Bounded,
            Self::AbsHalfBounded(_) | Self::RelHalfBounded(_) => Openness::HalfBounded,
            Self::Unbounded => Openness::Unbounded,
        }
    }
}

impl HasIntervalType for IntervalTypeWithRel {
    fn interval_type(&self) -> IntervalType {
        match self {
            Self::Empty => IntervalType::Empty,
            Self::AbsBounded | Self::RelBounded => IntervalType::Bounded,
            Self::AbsHalfBounded(opening_direction) | Self::RelHalfBounded(opening_direction) => {
                IntervalType::HalfBounded(*opening_direction)
            },
            Self::Unbounded => IntervalType::Unbounded,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IntervalTypeWithRelTryFromIntervalTypeAndRel;

impl Display for IntervalTypeWithRelTryFromIntervalTypeAndRel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "An error occurred when trying to convert `(IntervalType, Relativity)` into `IntervalTypeWithRel`"
        )
    }
}

impl Error for IntervalTypeWithRelTryFromIntervalTypeAndRel {}

impl TryFrom<(IntervalType, Relativity)> for IntervalTypeWithRel {
    type Error = IntervalTypeWithRelTryFromIntervalTypeAndRel;

    fn try_from(interval_type_and_rel: (IntervalType, Relativity)) -> Result<Self, Self::Error> {
        match interval_type_and_rel {
            (IntervalType::Empty, Relativity::Any) => Ok(Self::Empty),
            (IntervalType::Bounded, Relativity::Absolute) => Ok(Self::AbsBounded),
            (IntervalType::Bounded, Relativity::Relative) => Ok(Self::RelBounded),
            (IntervalType::HalfBounded(opening_direction), Relativity::Absolute) => {
                Ok(Self::AbsHalfBounded(opening_direction))
            },
            (IntervalType::HalfBounded(opening_direction), Relativity::Relative) => {
                Ok(Self::RelHalfBounded(opening_direction))
            },
            (IntervalType::Unbounded, Relativity::Any) => Ok(Self::Unbounded),
            _ => Err(IntervalTypeWithRelTryFromIntervalTypeAndRel),
        }
    }
}

/// Capacity of an interval to have an associated [`IntervalTypeWithRel`]
pub trait HasIntervalTypeWithRel: HasIntervalType {
    /// Returns the corresponding [`IntervalTypeWithRel`] of the interval type
    #[must_use]
    fn interval_type_with_rel(&self) -> IntervalTypeWithRel;
}

impl<T: HasIntervalTypeWithRel> HasIntervalType for T {
    fn interval_type(&self) -> IntervalType {
        self.interval_type_with_rel().interval_type()
    }
}