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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! Generic operation-related structures
//!
//! This module contains [`Precision`], [`RunningResult`] and set operations result structures.
//!
//! Those structures are not part of [`intervals::ops`](crate::intervals::ops)
//! as they are not related to intervals and can be used in other contexts.

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

use jiff::tz::{AmbiguousZoned, TimeZone};
use jiff::{SignedDuration, Timestamp, Zoned};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Mode for applying a [`Precision`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum PrecisionMode {
    /// Rounds the given time(s) to the nearest multiple of the duration
    ///
    /// In case of a tie, round up (to future).
    ToNearest,
    /// Ceils/Rounds up the given time(s) to the duration
    ToFuture,
    /// Floors/Rounds down the compared times to the duration
    ToPast,
}

impl PrecisionMode {
    /// Creates a [`Precision`] with the given precision without checking invariants
    ///
    /// Equivalent to calling [`Precision::unchecked_new`] with `self` and the desired duration.
    #[must_use]
    pub fn unchecked_with_precision(self, precision: StdDuration) -> Precision {
        Precision::unchecked_new(precision, self)
    }

    /// Creates a [`Precision`] with the given precision
    ///
    /// Equivalent to calling [`Precision::new`] with `self` and the desired duration.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionCreationPrecisionIsZeroError`] if the given precision is zero.
    pub fn with_precision(self, precision: StdDuration) -> Result<Precision, PrecisionCreationPrecisionIsZeroError> {
        Precision::new(precision, self)
    }
}

/// Precision to round times and intervals
///
/// Stores a [`PrecisionMode`] and a duration to apply a precision.
///
/// Rounding a time is useful in many cases, such as when a output time is
/// expected to be a multiple of a certain duration. In some companies, this is
/// used to be able to convert work time into pay without having to handle fractions.
///
/// Common rounding values such as 5 minutes, 15 minutes, 45 minutes, 1 hour,
/// are all divisors of 24 hours, which means that they all are modular with
/// respect to 24 hours. In other words: the instants to which all times within
/// a day are rounded to, given the precision, remain the same across days.
///
/// If you want to use other durations that may not exactly divide a day, you
/// should keep in mind that the rounding is always based on [the Unix epoch](https://en.wikipedia.org/w/index.php?title=Unix_time&oldid=1308795653).
///
/// To solve that problem, you can use another frame of reference for the rounding using the
/// [`precise_time_with_base_time`](Precision::precise_time_with_base_time) method.
///
/// Also, a time will never change if it is already a multiple of the precision
/// duration. For example, if we round up to every 5 minutes, `08:05:00` won't
/// be rounded up. But the instant you have even just a single microsecond more
/// than that, it will be rounded up.
///
/// Rounding a time can also be ambiguous when the given day includes
/// timezone-related offsets, like daylight savings. How those issues are
/// handled are explained in more details in the relevant methods.
///
/// # Invariants
///
/// The stored precision must be positive.
///
/// # Examples
///
/// ## Rounding to the nearest 5 minutes
///
/// ```
/// # use std::error::Error;
/// # use std::time::Duration;
/// # use jiff::Zoned;
/// # use periodical::ops::{Precision, PrecisionMode};
/// let round_to_nearest_five_mins =
///     Precision::new(Duration::from_mins(5), PrecisionMode::ToNearest)?;
///
/// let two_minutes_after_eight = "2025-01-01 08:02:11[Europe/Oslo]".parse::<Zoned>()?;
/// let fourteen_minutes_after_ten = "2025-01-01 10:14:21[Europe/Oslo]".parse::<Zoned>()?;
///
/// assert_eq!(
///     round_to_nearest_five_mins
///         .precise_time(&two_minutes_after_eight)?
///         .unambiguous()?,
///     "2025-01-01 08:00:00[Europe/Oslo]".parse::<Zoned>()?,
/// );
///
/// assert_eq!(
///     round_to_nearest_five_mins
///         .precise_time(&fourteen_minutes_after_ten)?
///         .unambiguous()?,
///     "2025-01-01 10:15:00[Europe/Oslo]".parse::<Zoned>()?,
/// );
/// # Ok::<(), Box<dyn Error>>(())
/// ```
///
/// ## Rounding up every 35 minutes with a given base time
///
/// ```
/// # use std::error::Error;
/// # use std::time::Duration;
/// # use jiff::Zoned;
/// # use periodical::ops::{Precision, PrecisionMode};
/// let round_up_every_35_mins = Precision::new(Duration::from_mins(35), PrecisionMode::ToFuture)?;
///
/// let first_january_2025 = "2025-01-01 00:00:00[Europe/Oslo]"
///     .parse::<Zoned>()?
///     .timestamp();
/// let two_minutes_after_eight = "2025-01-01 08:02:11[Europe/Oslo]".parse::<Zoned>()?;
/// let fourteen_minutes_after_ten = "2025-01-01 10:14:21[Europe/Oslo]".parse::<Zoned>()?;
///
/// // 13 * 35m = 07:35
/// // 14 * 35m = 08:10
/// assert_eq!(
///     round_up_every_35_mins
///         .precise_time_with_base_time(&two_minutes_after_eight, first_january_2025)?,
///     "2025-01-01 08:10:00[Europe/Oslo]".parse::<Zoned>()?,
/// );
///
/// // 17 * 35m = 09:55
/// // 18 * 35m = 10:30
/// assert_eq!(
///     round_up_every_35_mins
///         .precise_time_with_base_time(&fourteen_minutes_after_ten, first_january_2025)?,
///     "2025-01-01 10:30:00[Europe/Oslo]".parse::<Zoned>()?,
/// );
/// # Ok::<(), Box<dyn Error>>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Precision {
    precision: StdDuration,
    mode: PrecisionMode,
}

impl Precision {
    /// Creates a new [`Precision`] without checking invariants
    #[must_use]
    pub fn unchecked_new(precision: StdDuration, mode: PrecisionMode) -> Self {
        Precision {
            precision,
            mode,
        }
    }

    /// Creates a new [`Precision`]
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionCreationPrecisionIsZeroError`] if the given precision is zero.
    pub fn new(precision: StdDuration, mode: PrecisionMode) -> Result<Self, PrecisionCreationPrecisionIsZeroError> {
        if precision.is_zero() {
            return Err(PrecisionCreationPrecisionIsZeroError);
        }

        Ok(Self::unchecked_new(precision, mode))
    }

    /// Returns the precision duration
    #[must_use]
    pub fn precision(&self) -> StdDuration {
        self.precision
    }

    /// Returns the [`PrecisionMode`]
    #[must_use]
    pub fn mode(&self) -> PrecisionMode {
        self.mode
    }

    /// Applies the precision to a given [`u128`] representing a duration
    ///
    /// This operation is mostly designed for use by [`precise_duration`](Precision::precise_duration).
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    #[must_use]
    pub fn precise_unsigned_nanos(&self, duration: u128) -> u128 {
        let precision_nanos = self.precision().as_nanos();
        let timestamp_rem = duration % precision_nanos;

        if timestamp_rem == 0 {
            // Already rounded, no need to go to next anchor
            return duration;
        }

        let truncated_timestamp = duration - timestamp_rem;

        match self.mode() {
            PrecisionMode::ToNearest => {
                let precision_midpoint = precision_nanos / 2;

                if timestamp_rem.cmp(&precision_midpoint).is_ge() {
                    truncated_timestamp.saturating_add(precision_nanos)
                } else {
                    truncated_timestamp
                }
            },
            PrecisionMode::ToFuture => truncated_timestamp.saturating_add(precision_nanos),
            PrecisionMode::ToPast => truncated_timestamp,
        }
    }

    /// Applies the precision to a given [`i128`] representing a duration
    ///
    /// This operation is mostly designed for use by [`precise_signed_duration`](Precision::precise_signed_duration).
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    #[must_use]
    pub fn precise_signed_nanos(&self, duration: i128) -> i128 {
        let precision_nanos = self.precision().as_nanos();
        let timestamp_rem = duration.unsigned_abs() % precision_nanos;

        if timestamp_rem == 0 {
            // Already rounded, no need to go to next anchor
            return duration;
        }

        // How much needs to be removed to get to the past anchor
        let timestamp_diff_to_past = match duration.signum() {
            1 => timestamp_rem,
            0 => 0, // Unreachable: Previous guard would be triggered (0 mod N = 0)
            -1 => precision_nanos - timestamp_rem,
            _ => unreachable!("core::num::signum is guaranteed to return only in the range -1..=1"),
        };

        let truncated_timestamp = duration.saturating_sub_unsigned(timestamp_diff_to_past);

        match self.mode() {
            PrecisionMode::ToNearest => {
                let precision_midpoint = precision_nanos / 2;

                if timestamp_diff_to_past.cmp(&precision_midpoint).is_ge() {
                    truncated_timestamp.saturating_add_unsigned(precision_nanos)
                } else {
                    truncated_timestamp
                }
            },
            PrecisionMode::ToFuture => truncated_timestamp.saturating_add_unsigned(precision_nanos),
            PrecisionMode::ToPast => truncated_timestamp,
        }
    }

    /// Applies the precision to a given [`Duration`](StdDuration)
    ///
    /// Rounding is based on the multiple of the precision's duration.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] if the computed new duration has an amount of seconds superior
    /// to what [`u64`] can store.
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(15), PrecisionMode::ToPast)?;
    ///
    /// assert_eq!(
    ///     precision.precise_duration(Duration::from_mins(77))?,
    ///     Duration::from_mins(75),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn precise_duration(&self, duration: StdDuration) -> Result<StdDuration, PrecisionOutOfRangeError> {
        let new_timestamp = self.precise_unsigned_nanos(duration.as_nanos());

        // Polyfill for StdDuration::from_nanos_u128() to avoid bumping MSRV
        // & StdDuration::try_from_nanos_u128() doesn't yet exist
        let nanos_per_sec = StdDuration::from_secs(1).as_nanos();
        let secs_component = u64::try_from(new_timestamp / nanos_per_sec).or(Err(PrecisionOutOfRangeError))?;
        let nanos_component = u32::try_from(new_timestamp % nanos_per_sec).or(Err(PrecisionOutOfRangeError))?;

        Ok(StdDuration::new(secs_component, nanos_component))
    }

    /// Applies the precision to a given [`Duration`](StdDuration) based on a given offset
    ///
    /// Rounding is based on the multiple of the precision's duration relative to the given base offset.
    ///
    /// Use [`precise_duration_with_base_offset_via_signed`](Self::precise_duration_with_base_offset_via_signed)
    /// if you expect the given duration to possibly be lower than the given base offset.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] for any of the following reasons:
    /// - The base offset could not be subtracted from the duration without underflow
    /// - [`precise_duration`](Self::precise_duration) returned an error
    /// - The resulting precised duration relative to the base offset overflowed after adding the base offset back
    ///
    /// # Panics
    ///
    /// See [`precise_duration`](Self::precise_duration).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(15), PrecisionMode::ToPast)?;
    ///
    /// assert_eq!(
    ///     precision
    ///         .precise_duration_with_base_offset(Duration::from_mins(77), Duration::from_mins(3))?,
    ///     Duration::from_mins(63),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn precise_duration_with_base_offset(
        &self,
        duration: StdDuration,
        base: StdDuration,
    ) -> Result<StdDuration, PrecisionOutOfRangeError> {
        base.checked_add(self.precise_duration(duration.checked_sub(base).ok_or(PrecisionOutOfRangeError)?)?)
            .ok_or(PrecisionOutOfRangeError)
    }

    /// Applies the precision to a given [`Duration`](StdDuration) based on a given offset via [`SignedDuration`]
    /// conversions
    ///
    /// Similar to [`precise_duration_with_base_offset`](Self::precise_duration_with_base_offset), but converts
    /// the base and the offset to [`SignedDuration`]s to do the computation, before converting the result back
    /// into a [`Duration`](StdDuration).
    ///
    /// This is useful when you expect the given [`Duration`](StdDuration) to be lower than the given base offset.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] for any of the following reasons:
    /// - The duration could not be converted to a [`SignedDuration`]
    /// - The base offset could not be converted to a [`SignedDuration`]
    /// - [`precise_signed_duration_with_base_offset`](Self::precise_signed_duration_with_base_offset) returned an error
    /// - The resulting precised duration could not be converted back to a [`Duration`](StdDuration)
    ///
    /// # Panics
    ///
    /// See [`precise_signed_duration_with_base_offset`](Self::precise_signed_duration_with_base_offset).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(3), PrecisionMode::ToFuture)?;
    ///
    /// assert_eq!(
    ///     precision.precise_duration_with_base_offset_via_signed(
    ///         Duration::from_mins(1),
    ///         Duration::from_mins(2)
    ///     )?,
    ///     Duration::from_mins(2),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn precise_duration_with_base_offset_via_signed(
        &self,
        duration: StdDuration,
        base: StdDuration,
    ) -> Result<StdDuration, PrecisionOutOfRangeError> {
        let signed_duration =
            SignedDuration::try_from_nanos_i128(i128::try_from(duration.as_nanos()).or(Err(PrecisionOutOfRangeError))?)
                .ok_or(PrecisionOutOfRangeError)?;
        let signed_base =
            SignedDuration::try_from_nanos_i128(i128::try_from(base.as_nanos()).or(Err(PrecisionOutOfRangeError))?)
                .ok_or(PrecisionOutOfRangeError)?;

        let unsigned_precised_duration = u128::try_from(
            self.precise_signed_duration_with_base_offset(signed_duration, signed_base)?
                .as_nanos(),
        )
        .or(Err(PrecisionOutOfRangeError))?;

        // Polyfill for StdDuration::from_nanos_u128() to avoid bumping MSRV
        // & StdDuration::try_from_nanos_u128() doesn't yet exist
        let nanos_per_sec = StdDuration::from_secs(1).as_nanos();
        let secs_component =
            u64::try_from(unsigned_precised_duration / nanos_per_sec).or(Err(PrecisionOutOfRangeError))?;
        let nanos_component =
            u32::try_from(unsigned_precised_duration % nanos_per_sec).or(Err(PrecisionOutOfRangeError))?;

        Ok(StdDuration::new(secs_component, nanos_component))
    }

    /// Applies the precision to a given [`SignedDuration`]
    ///
    /// Since a duration is relative, rounding is based on the multiple of the precision's duration.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] if the computed new duration exceeded what [`i128`] can store.
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::SignedDuration;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(15), PrecisionMode::ToFuture)?;
    ///
    /// assert_eq!(
    ///     precision.precise_signed_duration(SignedDuration::from_mins(-44))?,
    ///     SignedDuration::from_mins(-30),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn precise_signed_duration(
        &self,
        signed_duration: SignedDuration,
    ) -> Result<SignedDuration, PrecisionOutOfRangeError> {
        SignedDuration::try_from_nanos_i128(self.precise_signed_nanos(signed_duration.as_nanos()))
            .ok_or(PrecisionOutOfRangeError)
    }

    /// Applies the precision to a given [`SignedDuration`] based on a given offset
    ///
    /// Rounding is based on the multiple of the precision's duration relative to the given base offset.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] for any of the following reasons:
    /// - The base offset could not be subtracted from the duration without underflow
    /// - [`precise_signed_duration`](Self::precise_signed_duration) returned an error
    /// - The resulting precised duration relative to the base offset overflowed after adding the base offset back
    ///
    /// # Panics
    ///
    /// See [`precise_signed_duration`](Self::precise_signed_duration).
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::SignedDuration;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(15), PrecisionMode::ToPast)?;
    ///
    /// assert_eq!(
    ///     precision.precise_signed_duration_with_base_offset(
    ///         SignedDuration::from_mins(-77),
    ///         SignedDuration::from_mins(-3)
    ///     )?,
    ///     SignedDuration::from_mins(-78),
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    pub fn precise_signed_duration_with_base_offset(
        &self,
        duration: SignedDuration,
        base: SignedDuration,
    ) -> Result<SignedDuration, PrecisionOutOfRangeError> {
        base.checked_add(self.precise_signed_duration(duration.checked_sub(base).ok_or(PrecisionOutOfRangeError)?)?)
            .ok_or(PrecisionOutOfRangeError)
    }

    /// Applies the precision to the given time
    ///
    /// If the precision is not a divisor of 24 hours, the rounded times would
    /// differ from one day to another, as the rounding would be based on
    /// the [Unix time][1], which begins on `1970-01-01`.
    ///
    /// Instead, this method assumes this is not your intention and that you
    /// instead want to round the displayed clock time to the duration.
    /// See [`precise_time_with_base_time`](Precision::precise_time_with_base_time)
    /// if this is does not match your desired behavior.
    ///
    /// This method applies the rounding based on the time's date and
    /// temporarily assumes a linear timezone: UTC. This assumption is to
    /// avoid unexpected rounded values that would occur when taking into
    /// account the given time's timezone.
    ///
    /// For example, if the time's date occurs the day the timezone _rolls back_
    /// one hour, rounding based on a higher value than the timezone's
    /// change, e.g. 2 hours, would look weird: the rounded times
    /// would result in even hours before the timezone's change, then would
    /// result in odd hours.
    ///
    /// This is precisely why this method returns an [`AmbiguousZoned`]: since
    /// we are applying the original timezone back on the rounded time (that
    /// was transferred to UTC), then we are not able to know if this time
    /// within the original timezone actually exists or whether it belongs to a
    /// time before/after a timezone change. We instead leave the
    /// disambiguation method up to the caller.
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] if the
    /// transfer to UTC would represent a timestamp too small to be stored
    /// correctly or if the resulting time would result in a time that
    /// cannot be stored in [`Zoned`].
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    ///
    /// # Examples
    ///
    /// ## Simple rounding
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::Zoned;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_hours(2), PrecisionMode::ToFuture)?;
    /// let time = "2026-01-01 07:52:46[Europe/Oslo]".parse::<Zoned>()?;
    ///
    /// assert_eq!(
    ///     precision.precise_time(&time)?.unambiguous()?,
    ///     "2026-01-01 08:00:00[Europe/Oslo]".parse::<Zoned>()?,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    ///
    /// ## Rounding on a DST day
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::Zoned;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(30), PrecisionMode::ToFuture)?;
    /// let ok_time = "2026-03-29 07:52:46[Europe/Oslo]".parse::<Zoned>()?;
    /// let gap_time = "2026-03-29 01:55:34[Europe/Oslo]".parse::<Zoned>()?;
    ///
    /// assert_eq!(
    ///     precision.precise_time(&ok_time)?.unambiguous()?,
    ///     "2026-03-29 08:00:00[Europe/Oslo]".parse::<Zoned>()?,
    /// );
    ///
    /// // since rounding 01:55:34 would end up at 02:00:00, which is when DST starts in this timezone,
    /// // trying to disambiguate the time using the reject strategy will return an error.
    /// assert!(precision.precise_time(&gap_time)?.unambiguous().is_err());
    /// // but if we really want a result, we can use the compatible strategy
    /// assert_eq!(
    ///     precision.precise_time(&gap_time)?.compatible()?,
    ///     // first time after DST time gap
    ///     "2026-03-29 03:00:00[Europe/Oslo]".parse::<Zoned>()?,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    ///
    /// ## A time already rounded won't change
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::Zoned;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(5), PrecisionMode::ToFuture)?;
    /// let time = "2026-01-01 08:45:00[Europe/Oslo]".parse::<Zoned>()?;
    ///
    /// assert_eq!(precision.precise_time(&time)?.unambiguous()?, time,);
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    ///
    /// [1]: https://en.wikipedia.org/w/index.php?title=Unix_time&oldid=1345178064
    pub fn precise_time(&self, time: &Zoned) -> Result<AmbiguousZoned, PrecisionOutOfRangeError> {
        let utc_day_start = time
            .datetime()
            .start_of_day()
            .to_zoned(TimeZone::UTC)
            .or(Err(PrecisionOutOfRangeError))?;
        let duration_diff = time
            .datetime()
            .to_zoned(TimeZone::UTC)
            .or(Err(PrecisionOutOfRangeError))?
            .timestamp()
            .duration_since(utc_day_start.timestamp());
        let precised_datetime = utc_day_start
            .checked_add(self.precise_signed_duration(duration_diff)?)
            .or(Err(PrecisionOutOfRangeError))?
            .datetime();

        Ok(time.time_zone().to_ambiguous_zoned(precised_datetime))
    }

    /// Applies the precision to the given time based on a given time base
    ///
    /// If the precision is not a divisor of 24 hours, the rounded times will
    /// differ from one day to another, as the rounding will be based on the
    /// [Unix time][1], which begins on `1970-01-01`.
    ///
    /// Giving a base allows you to solve this issue by giving away control on
    /// which base time is actually used. It is also useful for dealing with
    /// timezone changes, as timezone changes can introduce/remove
    /// amounts of time from the used time scale, meaning that the rounded
    /// result could end up with an unexpected clock time, but duration-wise
    /// with regards to the given base would match the desired rounding.
    ///
    /// If instead you want rounding based on clock time, see
    /// [`precise_time`](Precision::precise_time).
    ///
    /// # Errors
    ///
    /// Returns [`PrecisionOutOfRangeError`] if the resulting time would result in a time
    /// that cannot be stored in [`Zoned`].
    ///
    /// # Panics
    ///
    /// Panics if [`Precision`]'s invariants are not respected, i.e. the stored precision is zero.
    ///
    /// # Examples
    ///
    /// ## Duration-wise rounding on a DST day
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::Zoned;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_hours(2), PrecisionMode::ToFuture)?;
    /// let time = "2026-03-29 07:55:02[Europe/Oslo]".parse::<Zoned>()?;
    /// let base = time.start_of_day()?.timestamp();
    ///
    /// assert_eq!(
    ///     precision.precise_time_with_base_time(&time, base)?,
    ///     "2026-03-29 09:00:00[Europe/Oslo]".parse::<Zoned>()?,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    ///
    /// ## Rounding using a non-24-hours divisor
    ///
    /// ```
    /// # use std::error::Error;
    /// # use std::time::Duration;
    /// # use jiff::Zoned;
    /// # use periodical::ops::{Precision, PrecisionMode};
    /// let precision = Precision::new(Duration::from_mins(22), PrecisionMode::ToFuture)?;
    /// let time = "2026-01-02 07:55:02[Europe/Oslo]".parse::<Zoned>()?;
    /// let base = "2026-01-01 00:00:00[Europe/Oslo]"
    ///     .parse::<Zoned>()?
    ///     .timestamp();
    ///
    /// assert_eq!(
    ///     precision.precise_time_with_base_time(&time, base)?,
    ///     "2026-01-02 08:16:00[Europe/Oslo]".parse::<Zoned>()?,
    /// );
    /// # Ok::<(), Box<dyn Error>>(())
    /// ```
    ///
    /// [1]: https://en.wikipedia.org/w/index.php?title=Unix_time&oldid=1345178064
    pub fn precise_time_with_base_time(
        &self,
        time: &Zoned,
        base: Timestamp,
    ) -> Result<Zoned, PrecisionOutOfRangeError> {
        let base = base.to_zoned(time.time_zone().clone());

        base.checked_add(self.precise_signed_duration(time.duration_since(&base))?)
            .map_err(|_| PrecisionOutOfRangeError)
    }
}

/// Duration given as a precision was zero when creating a [`Precision`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrecisionCreationPrecisionIsZeroError;

impl Display for PrecisionCreationPrecisionIsZeroError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Duration given as a precision is zero")
    }
}

impl Error for PrecisionCreationPrecisionIsZeroError {}

/// An operation produced an out-of-range value when using [`Precision`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrecisionOutOfRangeError;

impl Display for PrecisionOutOfRangeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Operation produced an out-of-range value")
    }
}

impl Error for PrecisionOutOfRangeError {}

/// Represents a running result
///
/// If returning an unfinished result, for example from an iterator, is useful,
/// this enumerator helps with determining the state of the running result.
///
/// It is currently not used in `periodical` and therefore may be subject to deletion in the future.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum RunningResult<R, D = R> {
    /// Result is unfinished
    ///
    /// Current progress is stored in this variant.
    Running(R),
    /// Result is ready
    ///
    /// Result is stored in this variant.
    Done(D),
}

impl<R, D> RunningResult<R, D> {
    /// Whether the running result is the variant
    /// [`Running`](RunningResult::Running)
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert!(RunningResult::<()>::Running(()).is_running());
    /// assert!(!RunningResult::<()>::Done(()).is_running());
    /// ```
    pub fn is_running(&self) -> bool {
        matches!(self, Self::Running(_))
    }

    /// Whether the running result is the variant [`Done`](RunningResult::Done)
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert!(RunningResult::<()>::Done(()).is_done());
    /// assert!(!RunningResult::<()>::Running(()).is_done());
    /// ```
    pub fn is_done(&self) -> bool {
        matches!(self, Self::Done(_))
    }

    /// Returns the content of the [`Running`](RunningResult::Running) variant
    ///
    /// This operation consumes `self` and puts the content of the
    /// [`Running`](RunningResult::Running) variant in an [`Option`]. If
    /// instead `self` is another variant, this method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert_eq!(RunningResult::<u8>::Running(10).running(), Some(10));
    /// assert_eq!(RunningResult::<u8>::Done(10).running(), None);
    /// ```
    #[must_use]
    pub fn running(self) -> Option<R> {
        match self {
            Self::Running(r) => Some(r),
            Self::Done(_) => None,
        }
    }

    /// Returns the content of the [`Done`](RunningResult::Done) variant
    ///
    /// This operation consumes `self` and puts the content of the
    /// [`Done`](RunningResult::Done) variant in an [`Option`]. If instead
    /// `self` is another variant, this method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert_eq!(RunningResult::<u8>::Done(10).done(), Some(10));
    /// assert_eq!(RunningResult::<u8>::Running(10).done(), None);
    /// ```
    #[must_use]
    pub fn done(self) -> Option<D> {
        match self {
            Self::Running(_) => None,
            Self::Done(d) => Some(d),
        }
    }

    /// Maps the contents of the [`Running`](RunningResult::Running) variant
    ///
    /// If `self` is another variant, the method returns `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert_eq!(
    ///     RunningResult::<u8>::Running(10).map_running(|x| x * 2),
    ///     RunningResult::<u8>::Running(20),
    /// );
    /// assert_eq!(
    ///     RunningResult::<u8>::Done(10).map_running(|x| x * 2),
    ///     RunningResult::<u8>::Done(10),
    /// );
    /// ```
    pub fn map_running<F, T>(self, f: F) -> RunningResult<T, D>
    where
        F: FnOnce(R) -> T,
    {
        match self {
            Self::Running(r) => RunningResult::Running((f)(r)),
            Self::Done(d) => RunningResult::Done(d),
        }
    }

    /// Maps the contents of the [`Done`](RunningResult::Done) variant
    ///
    /// If `self` is another variant, the method returns `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::RunningResult;
    /// assert_eq!(
    ///     RunningResult::<u8>::Done(10).map_done(|x| x * 2),
    ///     RunningResult::<u8>::Done(20),
    /// );
    /// assert_eq!(
    ///     RunningResult::<u8>::Running(10).map_done(|x| x * 2),
    ///     RunningResult::<u8>::Running(10),
    /// );
    /// ```
    pub fn map_done<F, T>(self, f: F) -> RunningResult<R, T>
    where
        F: FnOnce(D) -> T,
    {
        match self {
            Self::Running(r) => RunningResult::Running(r),
            Self::Done(d) => RunningResult::Done((f)(d)),
        }
    }
}

/// Represents the result of a [complement][1]
///
/// [1]: https://en.wikipedia.org/w/index.php?title=Complement_(set_theory)&oldid=1272128427
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum ComplementResult<C> {
    /// Complement was successful and resulted in a single element
    Single(C),
    /// Complement was successful and resulted in two elements
    Split(C, C),
}

impl<C> ComplementResult<C> {
    /// Whether the [`ComplementResult`] is of the [`Single`](ComplementResult::Single) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::ComplementResult;
    /// assert!(ComplementResult::<u8>::Single(10).is_single());
    /// assert!(!ComplementResult::<u8>::Split(10, 20).is_single());
    /// ```
    pub fn is_single(&self) -> bool {
        matches!(self, Self::Single(_))
    }

    /// Whether the [`ComplementResult`] is of the [`Split`](ComplementResult::Split) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::ComplementResult;
    /// assert!(ComplementResult::<u8>::Split(10, 20).is_split());
    /// assert!(!ComplementResult::<u8>::Single(10).is_split());
    /// ```
    pub fn is_split(&self) -> bool {
        matches!(self, Self::Split(..))
    }

    /// Returns the content of the [`Single`](ComplementResult::Single) variant
    ///
    /// This operation consumes `self` and puts the content of the
    /// [`Single`](ComplementResult::Single) variant in an [`Option`]. If
    /// instead `self` is another variant, this method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::ComplementResult;
    /// assert_eq!(ComplementResult::<u8>::Single(10).single(), Some(10));
    /// assert_eq!(ComplementResult::<u8>::Split(10, 20).single(), None);
    /// ```
    #[must_use]
    pub fn single(self) -> Option<C> {
        match self {
            Self::Single(s) => Some(s),
            Self::Split(..) => None,
        }
    }

    /// Returns the content of the [`Split`](ComplementResult::Split) variant
    ///
    /// This operation consumes `self` and puts the content of the
    /// [`Split`](ComplementResult::Split) variant in an [`Option`]. If
    /// instead `self` is another variant, this method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::ComplementResult;
    /// assert_eq!(
    ///     ComplementResult::<u8>::Split(10, 20).split(),
    ///     Some((10, 20))
    /// );
    /// assert_eq!(ComplementResult::<u8>::Single(10).split(), None);
    /// ```
    #[must_use]
    pub fn split(self) -> Option<(C, C)> {
        match self {
            Self::Single(_) => None,
            Self::Split(s1, s2) => Some((s1, s2)),
        }
    }

    /// Maps the contents of the variants using the given transformation closure
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::ComplementResult;
    /// assert_eq!(
    ///     ComplementResult::<u8>::Single(10).map(|x| x * 2),
    ///     ComplementResult::<u8>::Single(20),
    /// );
    /// assert_eq!(
    ///     ComplementResult::<u8>::Split(10, 20).map(|x| x * 2),
    ///     ComplementResult::<u8>::Split(20, 40),
    /// );
    /// ```
    pub fn map<F, T>(self, mut f: F) -> ComplementResult<T>
    where
        F: FnMut(C) -> T,
    {
        match self {
            Self::Single(c) => ComplementResult::Single((f)(c)),
            Self::Split(c1, c2) => ComplementResult::Split((f)(c1), (f)(c2)),
        }
    }
}

/// Represents the result of a [union][1]
///
/// [1]: https://en.wikipedia.org/w/index.php?title=Union_(set_theory)&oldid=1309419266
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum UnionResult<U> {
    /// Union was successful, the united element is contained within this
    /// variant
    United(U),
    /// Union was unsuccessful
    Separate,
}

impl<U> UnionResult<U> {
    /// Whether the [`UnionResult`] is of the [`United`](UnionResult::United) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::UnionResult;
    /// assert!(UnionResult::<u8>::United(10).is_united());
    /// assert!(!UnionResult::<u8>::Separate.is_united());
    /// ```
    pub fn is_united(&self) -> bool {
        matches!(self, Self::United(_))
    }

    /// Whether the [`UnionResult`] is of the [`Separate`](UnionResult::Separate) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::UnionResult;
    /// assert!(UnionResult::<u8>::Separate.is_separate());
    /// assert!(!UnionResult::<u8>::United(10).is_separate());
    /// ```
    pub fn is_separate(&self) -> bool {
        matches!(self, Self::Separate)
    }

    /// Returns the content of the [`United`](UnionResult::United) variant
    ///
    /// Consumes `self` and puts the content of the [`United`](UnionResult::United) variant in an [`Option`].
    /// If instead `self` is another variant, this method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::UnionResult;
    /// assert_eq!(UnionResult::<u8>::United(10).united(), Some(10));
    /// assert_eq!(UnionResult::<u8>::Separate.united(), None);
    /// ```
    #[must_use]
    pub fn united(self) -> Option<U> {
        match self {
            Self::United(u) => Some(u),
            Self::Separate => None,
        }
    }

    /// Maps the contents of the [`United`](UnionResult::United) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::UnionResult;
    /// assert_eq!(
    ///     UnionResult::<u8>::United(10).map_united(|x| x * 2),
    ///     UnionResult::<u8>::United(20),
    /// );
    /// ```
    pub fn map_united<F, T>(self, f: F) -> UnionResult<T>
    where
        F: FnOnce(U) -> T,
    {
        match self {
            UnionResult::United(u) => UnionResult::United((f)(u)),
            UnionResult::Separate => UnionResult::Separate,
        }
    }
}

/// Represents the result of an [intersection][1]
///
/// [1]: https://en.wikipedia.org/w/index.php?title=Intersection_(set_theory)&oldid=1191979994
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum IntersectionResult<I> {
    /// Intersection was successful, the intersected element is contained within
    /// this variant
    Intersected(I),
    /// Intersection was unsuccessful
    Separate,
}

impl<I> IntersectionResult<I> {
    /// Whether the [`IntersectionResult`] is of the [`Intersected`](IntersectionResult::Intersected) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::IntersectionResult;
    /// assert!(IntersectionResult::<u8>::Intersected(10).is_intersected());
    /// assert!(!IntersectionResult::<u8>::Separate.is_intersected());
    /// ```
    pub fn is_intersected(&self) -> bool {
        matches!(self, Self::Intersected(_))
    }

    /// Whether the [`IntersectionResult`] is of the [`Separate`](IntersectionResult::Separate) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::IntersectionResult;
    /// assert!(IntersectionResult::<u8>::Separate.is_separate());
    /// assert!(!IntersectionResult::<u8>::Intersected(10).is_separate());
    /// ```
    pub fn is_separate(&self) -> bool {
        matches!(self, Self::Separate)
    }

    /// Returns the content of the [`Intersected`](IntersectionResult::Intersected) variant
    ///
    /// Consumes `self` and puts the content of the [`Intersected`](IntersectionResult::Intersected) variant
    /// in an [`Option`]. If instead `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::IntersectionResult;
    /// assert_eq!(
    ///     IntersectionResult::<u8>::Intersected(10).intersected(),
    ///     Some(10),
    /// );
    /// assert_eq!(IntersectionResult::<u8>::Separate.intersected(), None,);
    /// ```
    #[must_use]
    pub fn intersected(self) -> Option<I> {
        match self {
            Self::Intersected(i) => Some(i),
            Self::Separate => None,
        }
    }

    /// Maps the contents of the [`Intersected`](IntersectionResult::Intersected) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::IntersectionResult;
    /// assert_eq!(
    ///     IntersectionResult::<u8>::Intersected(10).map_intersected(|x| x * 2),
    ///     IntersectionResult::<u8>::Intersected(20),
    /// );
    /// ```
    pub fn map_intersected<F, T>(self, f: F) -> IntersectionResult<T>
    where
        F: FnOnce(I) -> T,
    {
        match self {
            Self::Intersected(i) => IntersectionResult::Intersected((f)(i)),
            Self::Separate => IntersectionResult::Separate,
        }
    }
}

/// Represents the result of a [difference][1]
///
/// [1]: https://en.wikipedia.org/w/index.php?title=Complement_(set_theory)&oldid=1272128427#Rel_complement
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum DifferenceResult<D> {
    /// Difference was successful and resulted in one single element
    Single(D),
    /// Difference was successful and resulted in two split elements
    Split(D, D),
    /// Difference was unsuccessful
    Separate,
}

impl<D> DifferenceResult<D> {
    /// Whether the [`DifferenceResult`] is of the
    /// [`Single`](DifferenceResult::Single) or
    /// [`Split`](DifferenceResult::Split) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert!(DifferenceResult::<u8>::Single(10).is_difference());
    /// assert!(DifferenceResult::<u8>::Split(10, 20).is_difference());
    /// assert!(!DifferenceResult::<u8>::Separate.is_difference());
    /// ```
    pub fn is_difference(&self) -> bool {
        matches!(self, Self::Single(_) | Self::Split(..))
    }

    /// Whether the [`DifferenceResult`] is of the [`Single`](DifferenceResult::Single) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert!(DifferenceResult::<u8>::Single(10).is_difference_single());
    /// assert!(!DifferenceResult::<u8>::Split(10, 20).is_difference_single());
    /// assert!(!DifferenceResult::<u8>::Separate.is_difference_single());
    /// ```
    pub fn is_difference_single(&self) -> bool {
        matches!(self, Self::Single(_))
    }

    /// Whether the [`DifferenceResult`] is of the [`Split`](DifferenceResult::Split) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert!(DifferenceResult::<u8>::Split(10, 20).is_difference_split());
    /// assert!(!DifferenceResult::<u8>::Single(10).is_difference_split());
    /// assert!(!DifferenceResult::<u8>::Separate.is_difference_split());
    /// ```
    pub fn is_difference_split(&self) -> bool {
        matches!(self, Self::Split(..))
    }

    /// Whether the [`DifferenceResult`] is of the [`Separate`](DifferenceResult::Separate) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert!(DifferenceResult::<u8>::Separate.is_separate());
    /// assert!(!DifferenceResult::<u8>::Single(10).is_separate());
    /// assert!(!DifferenceResult::<u8>::Split(10, 20).is_separate());
    /// ```
    pub fn is_separate(&self) -> bool {
        matches!(self, Self::Separate)
    }

    /// Returns the content of the [`Single`](DifferenceResult::Single) variant
    ///
    /// Consumes `self` and puts the content of the [`Single`](DifferenceResult::Single) variant in an [`Option`].
    /// If instead `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert_eq!(DifferenceResult::<u8>::Single(10).single(), Some(10));
    /// assert_eq!(DifferenceResult::<u8>::Split(10, 20).single(), None);
    /// assert_eq!(DifferenceResult::<u8>::Separate.single(), None);
    /// ```
    #[must_use]
    pub fn single(self) -> Option<D> {
        match self {
            Self::Single(s) => Some(s),
            Self::Split(..) | Self::Separate => None,
        }
    }

    /// Returns the content of the [`Split`](DifferenceResult::Split) variant
    ///
    /// Consumes `self` and puts the content of the [`Split`](DifferenceResult::Split) variant in an [`Option`].
    /// If instead `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert_eq!(
    ///     DifferenceResult::<u8>::Split(10, 20).split(),
    ///     Some((10, 20))
    /// );
    /// assert_eq!(DifferenceResult::<u8>::Single(10).split(), None);
    /// assert_eq!(DifferenceResult::<u8>::Separate.split(), None);
    /// ```
    #[must_use]
    pub fn split(self) -> Option<(D, D)> {
        match self {
            Self::Split(s1, s2) => Some((s1, s2)),
            Self::Single(_) | Self::Separate => None,
        }
    }

    /// Maps the contents of the [`Single`](DifferenceResult::Single)
    /// and [`Split`](DifferenceResult::Split) variants
    ///
    /// Uses a closure that describes the transformation from the original difference elements
    /// to the transformed ones.
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::DifferenceResult;
    /// assert_eq!(
    ///     DifferenceResult::<u8>::Single(10).map_difference(|x| x * 2),
    ///     DifferenceResult::<u8>::Single(20),
    /// );
    /// assert_eq!(
    ///     DifferenceResult::<u8>::Split(10, 20).map_difference(|x| x * 2),
    ///     DifferenceResult::<u8>::Split(20, 40),
    /// );
    /// ```
    pub fn map_difference<F, T>(self, mut f: F) -> DifferenceResult<T>
    where
        F: FnMut(D) -> T,
    {
        match self {
            Self::Single(d) => DifferenceResult::Single((f)(d)),
            Self::Split(d1, d2) => DifferenceResult::Split((f)(d1), (f)(d2)),
            Self::Separate => DifferenceResult::Separate,
        }
    }
}

/// Represents the result of a [symmetric difference][1]
///
/// [1]: https://en.wikipedia.org/w/index.php?title=Symmetric_difference&oldid=1300584821
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum SymmetricDifferenceResult<D> {
    /// Symmetric difference was successful and resulted in one single element
    Single(D),
    /// Symmetric difference was successful and resulted in two split elements
    Split(D, D),
    /// Symmetric difference was unsuccessful
    Separate,
}

impl<D> SymmetricDifferenceResult<D> {
    /// Whether the [`SymmetricDifferenceResult`] is of the
    /// [`Single`](SymmetricDifferenceResult::Single)
    /// or [`Split`](SymmetricDifferenceResult::Split) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert!(SymmetricDifferenceResult::<u8>::Single(10).is_symmetric_difference());
    /// assert!(SymmetricDifferenceResult::<u8>::Split(10, 20).is_symmetric_difference());
    /// assert!(!SymmetricDifferenceResult::<u8>::Separate.is_symmetric_difference());
    /// ```
    pub fn is_symmetric_difference(&self) -> bool {
        matches!(self, Self::Single(_) | Self::Split(..))
    }

    /// Whether the [`SymmetricDifferenceResult`] is of the
    /// [`Single`](SymmetricDifferenceResult::Single) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert!(SymmetricDifferenceResult::<u8>::Single(10).is_single());
    /// assert!(!SymmetricDifferenceResult::<u8>::Split(10, 20).is_single());
    /// assert!(!SymmetricDifferenceResult::<u8>::Separate.is_single());
    /// ```
    pub fn is_single(&self) -> bool {
        matches!(self, Self::Single(_))
    }

    /// Whether the [`SymmetricDifferenceResult`] is of the
    /// [`Split`](SymmetricDifferenceResult::Split) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert!(SymmetricDifferenceResult::<u8>::Split(10, 20).is_split());
    /// assert!(!SymmetricDifferenceResult::<u8>::Single(10).is_split());
    /// assert!(!SymmetricDifferenceResult::<u8>::Separate.is_split());
    /// ```
    pub fn is_split(&self) -> bool {
        matches!(self, Self::Split(..))
    }

    /// Whether the [`SymmetricDifferenceResult`] is of the
    /// [`Separate`](SymmetricDifferenceResult::Separate) variant
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert!(SymmetricDifferenceResult::<u8>::Separate.is_separate());
    /// assert!(!SymmetricDifferenceResult::<u8>::Single(10).is_separate());
    /// assert!(!SymmetricDifferenceResult::<u8>::Split(10, 20).is_separate());
    /// ```
    pub fn is_separate(&self) -> bool {
        matches!(self, Self::Separate)
    }

    /// Returns the content of the [`Single`](SymmetricDifferenceResult::Single) variant
    ///
    /// Consumes `self` and puts the content of the [`Single`](SymmetricDifferenceResult::Single) variant
    /// in an [`Option`]. If instead `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert_eq!(
    ///     SymmetricDifferenceResult::<u8>::Single(10).single(),
    ///     Some(10),
    /// );
    /// assert_eq!(
    ///     SymmetricDifferenceResult::<u8>::Split(10, 20).single(),
    ///     None,
    /// );
    /// assert_eq!(SymmetricDifferenceResult::<u8>::Separate.single(), None,);
    /// ```
    #[must_use]
    pub fn single(self) -> Option<D> {
        match self {
            Self::Single(s) => Some(s),
            Self::Split(..) | Self::Separate => None,
        }
    }

    /// Returns the content of the [`Split`](SymmetricDifferenceResult::Split) variant
    ///
    /// Consumes `self` and puts the content of the [`Split`](SymmetricDifferenceResult::Split) variant
    /// in an [`Option`]. If instead `self` is another variant, the method returns [`None`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert_eq!(
    ///     SymmetricDifferenceResult::<u8>::Split(10, 20).split(),
    ///     Some((10, 20)),
    /// );
    /// assert_eq!(SymmetricDifferenceResult::<u8>::Single(10).split(), None,);
    /// assert_eq!(SymmetricDifferenceResult::<u8>::Separate.split(), None,);
    /// ```
    #[must_use]
    pub fn split(self) -> Option<(D, D)> {
        match self {
            Self::Split(s1, s2) => Some((s1, s2)),
            Self::Single(_) | Self::Separate => None,
        }
    }

    /// Maps the contents of the [`Single`](SymmetricDifferenceResult::Single)
    /// and [`Split`](SymmetricDifferenceResult::Split) variants
    ///
    /// Uses a closure that describes the transformation from the original
    /// difference elements to the transformed ones.
    ///
    /// # Examples
    ///
    /// ```
    /// # use periodical::ops::SymmetricDifferenceResult;
    /// assert_eq!(
    ///     SymmetricDifferenceResult::<u8>::Single(10).map_symmetric_difference(|x| x * 2),
    ///     SymmetricDifferenceResult::<u8>::Single(20),
    /// );
    /// assert_eq!(
    ///     SymmetricDifferenceResult::<u8>::Split(10, 20).map_symmetric_difference(|x| x * 2),
    ///     SymmetricDifferenceResult::<u8>::Split(20, 40),
    /// );
    /// ```
    pub fn map_symmetric_difference<F, T>(self, mut f: F) -> SymmetricDifferenceResult<T>
    where
        F: FnMut(D) -> T,
    {
        match self {
            Self::Single(d) => SymmetricDifferenceResult::Single((f)(d)),
            Self::Split(d1, d2) => SymmetricDifferenceResult::Split((f)(d1), (f)(d2)),
            Self::Separate => SymmetricDifferenceResult::Separate,
        }
    }
}