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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! Bound containment positioning
//!
//! Bound containment positioning is the act of positioning _how_ a bound is
//! contained within an interval.
//!
//! The position of the bound is given by [`BoundContainmentPos`].
//! Since [bound overlap ambiguities](BoundOverlapAmbiguity) can be created, the
//! module provides ways to disambiguate that position, using either your own
//! closure to do that, or a [`BoundContainmentRuleSet`], describing the rule
//! set used for the disambiguation.
//!
//! Once disambiguated, you obtain a [`DisambiguatedBoundContainmentPos`]
//! that can then be converted to a clear boolean diagnostic of whether the
//! bound is consider _contained_ or not by the interval
//! using [`BoundContainmentRule`]s.

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

use crate::intervals::absolute::{
    AbsBoundPair,
    AbsEndBound,
    AbsStartBound,
    EmptiableAbsBoundPair,
    HasEmptiableAbsBoundPair,
};
use crate::intervals::ops::bound_overlap_ambiguity::{
    BoundOverlapAmbiguity,
    BoundOverlapDisambiguationRuleSet,
    DisambiguatedBoundOverlap,
};
use crate::intervals::ops::{BoundOrd, BoundOrdering};
use crate::intervals::relative::{
    EmptiableRelBoundPair,
    HasEmptiableRelBoundPair,
    RelBoundPair,
    RelEndBound,
    RelStartBound,
};

/// Bound position relative to an interval
///
/// Indicates where the bound is situated compared to a given interval
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum BoundContainmentPos {
    /// Bound was found before the interval's start
    OutsideBefore,
    /// Bound was found after the interval's end
    OutsideAfter,
    /// Bound was found outside the interval
    ///
    /// This result is only possible when dealing with empty intervals.
    Outside,
    /// Bound was found on the start of the interval
    ///
    /// The bound ambiguity is stored within this variant.
    ///
    /// The bound ambiguity is stored within an [`Option`] because infinite
    /// bounds can result in [`OnStart`](BoundContainmentPos::OnStart)
    /// / [`OnEnd`](BoundContainmentPos::OnEnd)
    /// positions unambiguously.
    ///
    /// Since [`BoundOverlapAmbiguity`] uses the terms "reference" and "compared",
    /// the reference in this case is the given bound, and the compared is the relevant
    /// bound from the interval.
    OnStart(Option<BoundOverlapAmbiguity>),
    /// The given bound was found exactly on the end of the interval
    ///
    /// The ambiguity is stored within this variant.
    ///
    /// The bound ambiguity is stored within an [`Option`] because infinite
    /// bounds can result in [`OnStart`](BoundContainmentPos::OnStart)
    /// / [`OnEnd`](BoundContainmentPos::OnEnd)
    /// positions unambiguously.
    ///
    /// Since [`BoundOverlapAmbiguity`] uses the terms "reference" and "compared",
    /// the reference in this case is the given bound, and the compared is the relevant
    /// bound from the interval.
    OnEnd(Option<BoundOverlapAmbiguity>),
    /// Bound was found exactly on the start and end of the interval
    ///
    /// This result is only possible when the given bound is inclusive and the
    /// interval is a single point in time with inclusive bounds.
    Equal,
    /// Bound was found inside the interval
    Inside,
}

impl BoundContainmentPos {
    /// Discards the information about bound inclusivity but conserves the
    /// variant
    ///
    /// **Careful!** This method discards data about bound inclusivity and
    /// cannot be recovered after conversion.
    #[must_use]
    pub fn strip(self) -> DisambiguatedBoundContainmentPos {
        match self {
            Self::OutsideBefore => DisambiguatedBoundContainmentPos::OutsideBefore,
            Self::OutsideAfter => DisambiguatedBoundContainmentPos::OutsideAfter,
            Self::Outside => DisambiguatedBoundContainmentPos::Outside,
            Self::OnStart(..) => DisambiguatedBoundContainmentPos::OnStart,
            Self::OnEnd(..) => DisambiguatedBoundContainmentPos::OnEnd,
            Self::Equal => DisambiguatedBoundContainmentPos::Equal,
            Self::Inside => DisambiguatedBoundContainmentPos::Inside,
        }
    }

    /// Uses a rule set to transform the bound position into a disambiguated one
    ///
    /// **Careful!** This method discards data about bound inclusivity and
    /// cannot be recovered after conversion.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsBoundPair, AbsFiniteBoundPos};
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::{
    /// #     CanPositionBoundContainment,
    /// #     BoundContainmentRuleSet,
    /// #     DisambiguatedBoundContainmentPos,
    /// # };
    /// let bound_pair = AbsBoundPair::new(
    ///     AbsFiniteBoundPos::new("2025-01-01 08:00:00Z".parse::<Timestamp>()?).to_start_bound(),
    ///     AbsFiniteBoundPos::new_with_incl(
    ///         "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    ///         BoundInclusivity::Exclusive,
    ///     )
    ///     .to_end_bound(),
    /// );
    ///
    /// let end_bound =
    ///     AbsFiniteBoundPos::new("2025-01-01 16:00:00Z".parse::<Timestamp>()?).to_end_bound();
    ///
    /// let bound_position = bound_pair.bound_position(&end_bound);
    ///
    /// assert_eq!(
    ///     bound_position.disambiguate_using_rule_set(BoundContainmentRuleSet::Strict),
    ///     DisambiguatedBoundContainmentPos::OutsideAfter,
    /// );
    /// assert_eq!(
    ///     bound_position.disambiguate_using_rule_set(BoundContainmentRuleSet::Lenient),
    ///     DisambiguatedBoundContainmentPos::OnEnd,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    pub fn disambiguate_using_rule_set(self, rule_set: BoundContainmentRuleSet) -> DisambiguatedBoundContainmentPos {
        rule_set.disambiguate(self)
    }
}

/// Disambiguated [`BoundContainmentPos`]
///
/// Indicates where the bound is situated compared to a given interval without
/// any ambiguity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum DisambiguatedBoundContainmentPos {
    /// See [`OutsideBefore`](BoundContainmentPos::OutsideBefore)
    OutsideBefore,
    /// See [`OutsideAfter`](BoundContainmentPos::OutsideAfter)
    OutsideAfter,
    /// See [`Outside`](BoundContainmentPos::Outside)
    Outside,
    /// See [`OnStart`](BoundContainmentPos::OnStart)
    OnStart,
    /// See [`OnEnd`](BoundContainmentPos::OnEnd)
    OnEnd,
    /// See [`Equal`](BoundContainmentPos::Equal)
    Equal,
    /// See [`Inside`](BoundContainmentPos::Inside)
    Inside,
}

/// Rule sets for disambiguating a [`BoundContainmentPos`]
///
/// See [`contains_bound`](CanPositionBoundContainment::contains_bound) for more.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum BoundContainmentRuleSet {
    /// Strict rule set
    ///
    /// Mathematical interpretation of bounds.
    ///
    /// Two bounds possessing the same point in time need to be inclusive in
    /// order to be counted as equal.
    ///
    /// See [`BoundOverlapDisambiguationRuleSet::Strict`].
    #[default]
    Strict,
    /// Lenient rule set
    ///
    /// Two bounds possessing the same point in time need to be either inclusive
    /// or at least one of them needs to be exclusive (not both!) in order
    /// to be counted as equal.
    ///
    /// See [`BoundOverlapDisambiguationRuleSet::Lenient`].
    Lenient,
    /// Very lenient rule set
    ///
    /// Two bounds possessing the same point in time are counted as equal,
    /// regardless of the inclusivity.
    ///
    /// See [`BoundOverlapDisambiguationRuleSet::VeryLenient`].
    VeryLenient,
    /// Continuous to future rule set
    ///
    /// Follows the same principles as [`BoundContainmentRuleSet::Strict`], but
    /// adds an exception: if an exclusive end bound is adjacent to an
    /// inclusive start bound, it also counts as equal.
    ///
    /// See [`BoundOverlapDisambiguationRuleSet::ContinuousToFuture`].
    ContinuousToFuture,
    /// Continuous to past rule set
    ///
    /// Follows the same principles as [`BoundContainmentRuleSet::Strict`], but
    /// adds an exception: if an exclusive start bound is adjacent to an
    /// inclusive end bound, it also counts as equal.
    ///
    /// See [`BoundOverlapDisambiguationRuleSet::ContinuousToFuture`].
    ContinuousToPast,
}

impl BoundContainmentRuleSet {
    /// Disambiguates a [`BoundContainmentPos`] according to the given rule
    /// set
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::{
    /// #     BoundContainmentPos,
    /// #     BoundContainmentRuleSet,
    /// #     DisambiguatedBoundContainmentPos,
    /// #     BoundOverlapAmbiguity,
    /// # };
    /// let bound_position = BoundContainmentPos::OnStart(Some(BoundOverlapAmbiguity::EndStart(
    ///     BoundInclusivity::Exclusive,
    ///     BoundInclusivity::Inclusive,
    /// )));
    ///
    /// assert_eq!(
    ///     BoundContainmentRuleSet::Strict.disambiguate(bound_position),
    ///     DisambiguatedBoundContainmentPos::OutsideBefore,
    /// );
    /// ```
    #[must_use]
    pub fn disambiguate(&self, bound_position: BoundContainmentPos) -> DisambiguatedBoundContainmentPos {
        let disambiguation_rule_set = match self {
            Self::Strict => BoundOverlapDisambiguationRuleSet::Strict,
            Self::Lenient => BoundOverlapDisambiguationRuleSet::Lenient,
            Self::VeryLenient => BoundOverlapDisambiguationRuleSet::VeryLenient,
            Self::ContinuousToFuture => BoundOverlapDisambiguationRuleSet::ContinuousToFuture,
            Self::ContinuousToPast => BoundOverlapDisambiguationRuleSet::ContinuousToPast,
        };

        bound_position_rule_set_disambiguation(bound_position, disambiguation_rule_set)
    }
}

/// Disambiguates a [`BoundContainmentPos`] using the given [`BoundOverlapDisambiguationRuleSet`]
///
/// Converts the unambiguous [`BoundContainmentPos`]s into [`DisambiguatedBoundContainmentPos`].
/// For ambiguous [`BoundContainmentPos`]s, uses the given
/// [`BoundOverlapDisambiguationRuleSet`] to disambiguate the inner ambiguity
/// before converting the result in a [`DisambiguatedBoundContainmentPos`].
#[must_use]
pub fn bound_position_rule_set_disambiguation(
    bound_position: BoundContainmentPos,
    bound_overlap_disambiguation_rule_set: BoundOverlapDisambiguationRuleSet,
) -> DisambiguatedBoundContainmentPos {
    match bound_position {
        BoundContainmentPos::Outside => DisambiguatedBoundContainmentPos::Outside,
        BoundContainmentPos::OutsideBefore => DisambiguatedBoundContainmentPos::OutsideBefore,
        BoundContainmentPos::OutsideAfter => DisambiguatedBoundContainmentPos::OutsideAfter,
        BoundContainmentPos::OnStart(None) => DisambiguatedBoundContainmentPos::OnStart,
        BoundContainmentPos::OnStart(Some(ambiguity)) => {
            match ambiguity.disambiguate(bound_overlap_disambiguation_rule_set) {
                DisambiguatedBoundOverlap::Before => DisambiguatedBoundContainmentPos::OutsideBefore,
                DisambiguatedBoundOverlap::Equal => DisambiguatedBoundContainmentPos::OnStart,
                DisambiguatedBoundOverlap::After => DisambiguatedBoundContainmentPos::Inside,
            }
        },
        BoundContainmentPos::OnEnd(None) => DisambiguatedBoundContainmentPos::OnEnd,
        BoundContainmentPos::OnEnd(Some(ambiguity)) => {
            match ambiguity.disambiguate(bound_overlap_disambiguation_rule_set) {
                DisambiguatedBoundOverlap::Before => DisambiguatedBoundContainmentPos::Inside,
                DisambiguatedBoundOverlap::Equal => DisambiguatedBoundContainmentPos::OnEnd,
                DisambiguatedBoundOverlap::After => DisambiguatedBoundContainmentPos::OutsideAfter,
            }
        },
        BoundContainmentPos::Equal => DisambiguatedBoundContainmentPos::Equal,
        BoundContainmentPos::Inside => DisambiguatedBoundContainmentPos::Inside,
    }
}

/// Bound containment rules used as the reference for predefined decisions
pub const DEFAULT_BOUND_CONTAINMENT_RULES: [BoundContainmentRule; 1] = [BoundContainmentRule::AllowOnBounds];

/// Rules for determining what counts as containment
///
/// Those rules are used to convert a [`DisambiguatedBoundContainmentPos`]
/// into a boolean indicating whether the bound is contained within the interval
/// or not, according to the given rules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum BoundContainmentRule {
    /// Counts as contained when the bound is on the start of the interval
    AllowOnStart,
    /// Counts as contained when the bound is on the end of the interval
    AllowOnEnd,
    /// Counts as contained when the bound is either on the start or the end of
    /// the interval
    AllowOnBounds,
    /// Doesn't count as contained when the bound is on the start of the
    /// interval
    DenyOnStart,
    /// Doesn't count as contained when the bound is on the end of the interval
    DenyOnEnd,
    /// Doesn't count as contained when the bound is either on the start or the
    /// end of the interval
    DenyOnBounds,
}

impl BoundContainmentRule {
    /// Returns the next state of the running containment decision
    ///
    /// This method takes the running containment decision and the
    /// [`DisambiguatedBoundContainmentPos`] and returns the next state
    /// of the running containment decision.
    #[must_use]
    pub fn counts_as_contained(&self, running: bool, disambiguated_pos: DisambiguatedBoundContainmentPos) -> bool {
        match self {
            Self::AllowOnStart => allow_on_start_containment_rule_counts_as_contained(running, disambiguated_pos),
            Self::AllowOnEnd => allow_on_end_containment_rule_counts_as_contained(running, disambiguated_pos),
            Self::AllowOnBounds => allow_on_bounds_containment_rule_counts_as_contained(running, disambiguated_pos),
            Self::DenyOnStart => deny_on_start_containment_rule_counts_as_contained(running, disambiguated_pos),
            Self::DenyOnEnd => deny_on_end_containment_rule_counts_as_contained(running, disambiguated_pos),
            Self::DenyOnBounds => deny_on_bounds_containment_rule_counts_as_contained(running, disambiguated_pos),
        }
    }
}

/// Checks all given rules and returns the final boolean regarding bound
/// containment
///
/// Iterates over the given rules and [fold](Iterator::fold) them with
/// [`BoundContainmentRule::counts_as_contained`] in order to get the final
/// boolean regarding whether the bound should be considered contained.
///
/// This method also contains the common logic of considering
/// an [`Equal`](DisambiguatedBoundContainmentPos::Equal)
/// or [`Inside`](DisambiguatedBoundContainmentPos::Inside)
/// [`DisambiguatedBoundContainmentPos`] as being contained.
///
/// If conflicting rules are provided, for example
/// [`AllowOnStart`](BoundContainmentRule::AllowOnStart)
/// and [`DenyOnStart`](BoundContainmentRule::DenyOnStart), the one appearing
/// last is the one taking priority.
///
/// Don't use this method directly, use [`CanPositionBoundContainment::contains_bound`] instead.
///
/// # Examples
///
/// ```
/// # use periodical::intervals::ops::{
/// #     BoundContainmentRule,
/// #     DisambiguatedBoundContainmentPos,
/// # };
/// # use periodical::intervals::ops::bound_containment::check_bound_containment_rules;
/// let disambiguated_pos = DisambiguatedBoundContainmentPos::OnStart;
///
/// let deny_on_bounds_diagnostic =
///     check_bound_containment_rules(disambiguated_pos, &[BoundContainmentRule::DenyOnBounds]);
/// let allow_on_bounds_diagnostic =
///     check_bound_containment_rules(disambiguated_pos, &[BoundContainmentRule::AllowOnBounds]);
///
/// assert!(!deny_on_bounds_diagnostic);
/// assert!(allow_on_bounds_diagnostic);
/// ```
#[must_use]
pub fn check_bound_containment_rules<'a, RI>(disambiguated_pos: DisambiguatedBoundContainmentPos, rules: RI) -> bool
where
    RI: IntoIterator<Item = &'a BoundContainmentRule>,
{
    let common = matches!(
        disambiguated_pos,
        DisambiguatedBoundContainmentPos::Equal | DisambiguatedBoundContainmentPos::Inside,
    );

    rules.into_iter().fold(common, |is_contained, rule| {
        rule.counts_as_contained(is_contained, disambiguated_pos)
    })
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`AllowOnStart`](BoundContainmentRule::AllowOnStart) rule
#[must_use]
pub fn allow_on_start_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running || matches!(disambiguated_pos, DisambiguatedBoundContainmentPos::OnStart)
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`AllowOnEnd`](BoundContainmentRule::AllowOnEnd) rule
#[must_use]
pub fn allow_on_end_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running || matches!(disambiguated_pos, DisambiguatedBoundContainmentPos::OnEnd)
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`AllowOnBounds`](BoundContainmentRule::AllowOnBounds) rule
#[must_use]
pub fn allow_on_bounds_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running
        || matches!(
            disambiguated_pos,
            DisambiguatedBoundContainmentPos::OnStart | DisambiguatedBoundContainmentPos::OnEnd,
        )
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`DenyOnStart`](BoundContainmentRule::DenyOnStart) rule
#[must_use]
pub fn deny_on_start_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running && !matches!(disambiguated_pos, DisambiguatedBoundContainmentPos::OnStart)
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`DenyOnEnd`](BoundContainmentRule::DenyOnEnd) rule
#[must_use]
pub fn deny_on_end_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running && !matches!(disambiguated_pos, DisambiguatedBoundContainmentPos::OnEnd)
}

/// Checks whether the given [`DisambiguatedBoundContainmentPos`] respects
/// the [`DenyOnBounds`](BoundContainmentRule::DenyOnBounds) rule
#[must_use]
pub fn deny_on_bounds_containment_rule_counts_as_contained(
    running: bool,
    disambiguated_pos: DisambiguatedBoundContainmentPos,
) -> bool {
    running
        && !matches!(
            disambiguated_pos,
            DisambiguatedBoundContainmentPos::OnStart | DisambiguatedBoundContainmentPos::OnEnd,
        )
}

/// Capacity to position a bound in an interval
///
/// # Examples
///
/// ## Fetching the disambiguated position of a bound
///
/// ```
/// # use std::error::Error;
/// # use jiff::Timestamp;
/// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
/// # use periodical::intervals::meta::BoundInclusivity;
/// # use periodical::intervals::ops::{
/// #     BoundContainmentRuleSet,
/// #     CanPositionBoundContainment,
/// #     DisambiguatedBoundContainmentPos,
/// # };
/// let interval = BoundedAbsInterval::from_times(
///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
/// );
///
/// let bound = AbsFiniteBoundPos::new_with_incl(
///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
///     BoundInclusivity::Exclusive,
/// )
/// .to_start_bound();
///
/// let pos = interval.disambiguated_bound_position(&bound, BoundContainmentRuleSet::Lenient);
///
/// assert_eq!(pos, DisambiguatedBoundContainmentPos::OnStart);
/// # Ok::<(), Box<dyn Error>>(())
/// ```
///
/// ## Checking if a bound is contained in an interval
///
/// ```
/// # use std::error::Error;
/// # use jiff::Timestamp;
/// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
/// # use periodical::intervals::ops::{
/// #     CanPositionBoundContainment,
/// #     DisambiguatedBoundContainmentPos,
/// # };
/// let interval = BoundedAbsInterval::from_times(
///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
/// );
///
/// let bound =
///     AbsFiniteBoundPos::new("2025-01-01 10:00:00Z".parse::<Timestamp>()?).to_start_bound();
///
/// assert!(interval.simple_contains_bound(&bound));
/// # Ok::<(), Box<dyn Error>>(())
/// ```
pub trait CanPositionBoundContainment<B> {
    /// Returns the bound position relative to the interval
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::{
    /// #     BoundContainmentPos,
    /// #     CanPositionBoundContainment,
    /// #     BoundOverlapAmbiguity,
    /// # };
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound = AbsFiniteBoundPos::new_with_incl(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     BoundInclusivity::Exclusive,
    /// )
    /// .to_start_bound();
    ///
    /// let pos = interval.bound_position(&bound);
    ///
    /// assert_eq!(
    ///     pos,
    ///     BoundContainmentPos::OnStart(Some(BoundOverlapAmbiguity::BothStarts(
    ///         BoundInclusivity::Exclusive,
    ///         BoundInclusivity::Inclusive,
    ///     ))),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn bound_position(&self, bound: &B) -> BoundContainmentPos;

    /// Returns the disambiguated bound position of the given bound using the
    /// given rule set
    ///
    /// Uses [`BoundContainmentPos::disambiguate_using_rule_set`] under the
    /// hood.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::{
    /// #     BoundContainmentRuleSet,
    /// #     CanPositionBoundContainment,
    /// #     DisambiguatedBoundContainmentPos,
    /// # };
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound = AbsFiniteBoundPos::new_with_incl(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     BoundInclusivity::Exclusive,
    /// )
    /// .to_start_bound();
    ///
    /// let pos = interval.disambiguated_bound_position(&bound, BoundContainmentRuleSet::Lenient);
    ///
    /// assert_eq!(pos, DisambiguatedBoundContainmentPos::OnStart);
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn disambiguated_bound_position(
        &self,
        bound: &B,
        rule_set: BoundContainmentRuleSet,
    ) -> DisambiguatedBoundContainmentPos {
        self.bound_position(bound).disambiguate_using_rule_set(rule_set)
    }

    /// Returns whether the given bound is contained in the interval using
    /// predetermined rules
    ///
    /// Uses the [default rule set](BoundContainmentRuleSet::default)
    /// with [default rules](DEFAULT_BOUND_CONTAINMENT_RULES)
    /// in [`contains_bound`](CanPositionBoundContainment::contains_bound).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::CanPositionBoundContainment;
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound =
    ///     AbsFiniteBoundPos::new("2025-01-01 08:00:00Z".parse::<Timestamp>()?).to_start_bound();
    ///
    /// assert!(interval.simple_contains_bound(&bound));
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn simple_contains_bound(&self, bound: &B) -> bool {
        self.contains_bound(
            bound,
            BoundContainmentRuleSet::default(),
            &DEFAULT_BOUND_CONTAINMENT_RULES,
        )
    }

    /// Returns whether the given bound is contained in the interval
    /// using the given [containment rules](BoundContainmentRule)
    ///
    /// Uses [`check_bound_containment_rules`] under the hood.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::meta::BoundInclusivity;
    /// # use periodical::intervals::ops::{
    /// #     BoundContainmentRule,
    /// #     BoundContainmentRuleSet,
    /// #     CanPositionBoundContainment,
    /// # };
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound = AbsFiniteBoundPos::new_with_incl(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     BoundInclusivity::Exclusive,
    /// )
    /// .to_start_bound();
    ///
    /// let is_contained = interval.contains_bound(
    ///     &bound,
    ///     BoundContainmentRuleSet::Lenient,
    ///     &[BoundContainmentRule::AllowOnStart],
    /// );
    ///
    /// assert!(is_contained);
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn contains_bound<'a, RI>(&self, bound: &B, rule_set: BoundContainmentRuleSet, rules: RI) -> bool
    where
        RI: IntoIterator<Item = &'a BoundContainmentRule>,
    {
        check_bound_containment_rules(self.disambiguated_bound_position(bound, rule_set), rules)
    }

    /// Returns whether the given bound is contained in the interval using the
    /// given closure
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::ops::bound_containment::CanPositionBoundContainment;
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound =
    ///     AbsFiniteBoundPos::new("2025-01-01 10:00:00Z".parse::<Timestamp>()?).to_start_bound();
    ///
    /// let is_contained = interval.contains_bound_using(&bound, |_bound| false);
    ///
    /// assert!(!is_contained);
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn contains_bound_using<F>(&self, bound: &B, f: F) -> bool
    where
        F: FnOnce(BoundContainmentPos) -> bool,
    {
        (f)(self.bound_position(bound))
    }

    /// Returns whether the given bound is contained in the interval using the
    /// given closure with a disambiguated position
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use jiff::Timestamp;
    /// # use periodical::intervals::absolute::{AbsFiniteBoundPos, BoundedAbsInterval};
    /// # use periodical::intervals::ops::bound_containment::{
    /// #     BoundContainmentRuleSet, CanPositionBoundContainment,
    /// # };
    /// let interval = BoundedAbsInterval::from_times(
    ///     "2025-01-01 08:00:00Z".parse::<Timestamp>()?,
    ///     "2025-01-01 16:00:00Z".parse::<Timestamp>()?,
    /// );
    ///
    /// let bound =
    ///     AbsFiniteBoundPos::new("2025-01-01 10:00:00Z".parse::<Timestamp>()?).to_start_bound();
    ///
    /// let is_contained = interval.contains_bound_using_simple(
    ///     &bound,
    ///     BoundContainmentRuleSet::Lenient,
    ///     |_disambiguated_bound| false,
    /// );
    ///
    /// assert!(!is_contained);
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    #[must_use]
    fn contains_bound_using_simple<F>(&self, bound: &B, rule_set: BoundContainmentRuleSet, f: F) -> bool
    where
        F: FnOnce(DisambiguatedBoundContainmentPos) -> bool,
    {
        (f)(self.disambiguated_bound_position(bound, rule_set))
    }
}

impl<T> CanPositionBoundContainment<AbsStartBound> for T
where
    T: HasEmptiableAbsBoundPair,
{
    fn bound_position(&self, bound: &AbsStartBound) -> BoundContainmentPos {
        bound_position_abs_start_bound_on_emptiable_abs_bound_pair(&self.emptiable_abs_bound_pair(), bound)
    }
}

/// Returns the [`BoundContainmentPos`] of an [`AbsStartBound`]
/// relative to an [`EmptiableAbsBoundPair`]
#[must_use]
pub fn bound_position_abs_start_bound_on_emptiable_abs_bound_pair(
    emptiable_abs_bound_pair: &EmptiableAbsBoundPair,
    abs_start_bound: &AbsStartBound,
) -> BoundContainmentPos {
    let EmptiableAbsBoundPair::Bound(abs_bound_pair) = emptiable_abs_bound_pair else {
        return BoundContainmentPos::Outside;
    };

    bound_position_abs_start_bound_on_abs_bound_pair(abs_bound_pair, abs_start_bound)
}

/// Returns the [`BoundContainmentPos`] of an [`AbsStartBound`]
/// relative to an [`AbsBoundPair`]
#[must_use]
pub fn bound_position_abs_start_bound_on_abs_bound_pair(
    abs_bound_pair: &AbsBoundPair,
    abs_start_bound: &AbsStartBound,
) -> BoundContainmentPos {
    match abs_start_bound.bound_cmp(&abs_bound_pair.start()) {
        BoundOrdering::Less => BoundContainmentPos::OutsideBefore,
        BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnStart(ambiguity),
        BoundOrdering::Greater => match abs_start_bound.bound_cmp(&abs_bound_pair.end()) {
            BoundOrdering::Less => BoundContainmentPos::Inside,
            BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnEnd(ambiguity),
            BoundOrdering::Greater => BoundContainmentPos::OutsideAfter,
        },
    }
}

impl<T> CanPositionBoundContainment<AbsEndBound> for T
where
    T: HasEmptiableAbsBoundPair,
{
    fn bound_position(&self, bound: &AbsEndBound) -> BoundContainmentPos {
        bound_position_abs_end_bound_on_emptiable_abs_bound_pair(&self.emptiable_abs_bound_pair(), bound)
    }
}

/// Returns the [`BoundContainmentPos`] of an [`AbsEndBound`] relative
/// to an [`EmptiableAbsBoundPair`]
#[must_use]
pub fn bound_position_abs_end_bound_on_emptiable_abs_bound_pair(
    emptiable_abs_bound_pair: &EmptiableAbsBoundPair,
    abs_end_bound: &AbsEndBound,
) -> BoundContainmentPos {
    let EmptiableAbsBoundPair::Bound(abs_bound_pair) = emptiable_abs_bound_pair else {
        return BoundContainmentPos::Outside;
    };

    bound_position_abs_end_bound_on_abs_bound_pair(abs_bound_pair, abs_end_bound)
}

/// Returns the [`BoundContainmentPos`] of an [`AbsEndBound`] relative
/// to an [`AbsBoundPair`]
#[must_use]
pub fn bound_position_abs_end_bound_on_abs_bound_pair(
    abs_bound_pair: &AbsBoundPair,
    abs_end_bound: &AbsEndBound,
) -> BoundContainmentPos {
    match abs_end_bound.bound_cmp(&abs_bound_pair.start()) {
        BoundOrdering::Less => BoundContainmentPos::OutsideBefore,
        BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnStart(ambiguity),
        BoundOrdering::Greater => match abs_end_bound.bound_cmp(&abs_bound_pair.end()) {
            BoundOrdering::Less => BoundContainmentPos::Inside,
            BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnEnd(ambiguity),
            BoundOrdering::Greater => BoundContainmentPos::OutsideAfter,
        },
    }
}

impl<T> CanPositionBoundContainment<RelStartBound> for T
where
    T: HasEmptiableRelBoundPair,
{
    fn bound_position(&self, bound: &RelStartBound) -> BoundContainmentPos {
        bound_position_rel_start_bound_on_emptiable_rel_bound_pair(&self.emptiable_rel_bound_pair(), bound)
    }
}

/// Returns the [`BoundContainmentPos`] of a [`RelStartBound`]
/// relative to an [`EmptiableRelBoundPair`]
#[must_use]
pub fn bound_position_rel_start_bound_on_emptiable_rel_bound_pair(
    emptiable_rel_bound_pair: &EmptiableRelBoundPair,
    rel_start_bound: &RelStartBound,
) -> BoundContainmentPos {
    let EmptiableRelBoundPair::Bound(rel_bound_pair) = emptiable_rel_bound_pair else {
        return BoundContainmentPos::Outside;
    };

    bound_position_rel_start_bound_on_rel_bound_pair(rel_bound_pair, rel_start_bound)
}

/// Returns the [`BoundContainmentPos`] of a [`RelStartBound`]
/// relative to a [`RelBoundPair`]
#[must_use]
pub fn bound_position_rel_start_bound_on_rel_bound_pair(
    rel_bound_pair: &RelBoundPair,
    rel_start_bound: &RelStartBound,
) -> BoundContainmentPos {
    match rel_start_bound.bound_cmp(&rel_bound_pair.start()) {
        BoundOrdering::Less => BoundContainmentPos::OutsideBefore,
        BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnStart(ambiguity),
        BoundOrdering::Greater => match rel_start_bound.bound_cmp(&rel_bound_pair.end()) {
            BoundOrdering::Less => BoundContainmentPos::Inside,
            BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnEnd(ambiguity),
            BoundOrdering::Greater => BoundContainmentPos::OutsideAfter,
        },
    }
}

impl<T> CanPositionBoundContainment<RelEndBound> for T
where
    T: HasEmptiableRelBoundPair,
{
    fn bound_position(&self, bound: &RelEndBound) -> BoundContainmentPos {
        bound_position_rel_end_bound_on_emptiable_rel_bound_pair(&self.emptiable_rel_bound_pair(), bound)
    }
}

/// Returns the [`BoundContainmentPos`] of a [`RelEndBound`] relative
/// to an [`EmptiableRelBoundPair`]
#[must_use]
pub fn bound_position_rel_end_bound_on_emptiable_rel_bound_pair(
    emptiable_rel_bound_pair: &EmptiableRelBoundPair,
    rel_end_bound: &RelEndBound,
) -> BoundContainmentPos {
    let EmptiableRelBoundPair::Bound(rel_bound_pair) = emptiable_rel_bound_pair else {
        return BoundContainmentPos::Outside;
    };

    bound_position_rel_end_bound_on_rel_bound_pair(rel_bound_pair, rel_end_bound)
}

/// Returns the [`BoundContainmentPos`] of a [`RelEndBound`] relative
/// to a [`RelBoundPair`]
#[must_use]
pub fn bound_position_rel_end_bound_on_rel_bound_pair(
    rel_bound_pair: &RelBoundPair,
    rel_end_bound: &RelEndBound,
) -> BoundContainmentPos {
    match rel_end_bound.bound_cmp(&rel_bound_pair.start()) {
        BoundOrdering::Less => BoundContainmentPos::OutsideBefore,
        BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnStart(ambiguity),
        BoundOrdering::Greater => match rel_end_bound.bound_cmp(&rel_bound_pair.end()) {
            BoundOrdering::Less => BoundContainmentPos::Inside,
            BoundOrdering::Equal(ambiguity) => BoundContainmentPos::OnEnd(ambiguity),
            BoundOrdering::Greater => BoundContainmentPos::OutsideAfter,
        },
    }
}