-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathoptions.rs
More file actions
921 lines (827 loc) · 30.1 KB
/
options.rs
File metadata and controls
921 lines (827 loc) · 30.1 KB
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
//! Native implementation of the `Temporal` options.
//!
//! Temporal has various instances where user's can define options for how an
//! operation may be completed.
use crate::parsers::Precision;
use crate::{TemporalError, TemporalResult, MS_PER_DAY, NS_PER_DAY};
use core::ops::Add;
use core::{fmt, str::FromStr};
mod increment;
mod relative_to;
pub use increment::RoundingIncrement;
pub use relative_to::RelativeTo;
// ==== RoundingOptions / DifferenceSettings ====
#[derive(Debug, Clone, Copy)]
pub(crate) enum DifferenceOperation {
Until,
Since,
}
#[derive(Debug, Default)]
pub struct ToStringRoundingOptions {
pub precision: Precision,
pub smallest_unit: Option<TemporalUnit>,
pub rounding_mode: Option<TemporalRoundingMode>,
}
#[derive(Debug)]
pub(crate) struct ResolvedToStringRoundingOptions {
pub(crate) precision: Precision,
pub(crate) smallest_unit: TemporalUnit,
pub(crate) rounding_mode: TemporalRoundingMode,
pub(crate) increment: RoundingIncrement,
}
impl ToStringRoundingOptions {
pub(crate) fn resolve(&self) -> TemporalResult<ResolvedToStringRoundingOptions> {
let rounding_mode = self.rounding_mode.unwrap_or(TemporalRoundingMode::Trunc);
match self.smallest_unit {
Some(TemporalUnit::Minute) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Minute,
smallest_unit: TemporalUnit::Minute,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Some(TemporalUnit::Second) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(0),
smallest_unit: TemporalUnit::Second,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Some(TemporalUnit::Millisecond) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(3),
smallest_unit: TemporalUnit::Millisecond,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Some(TemporalUnit::Microsecond) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(6),
smallest_unit: TemporalUnit::Microsecond,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Some(TemporalUnit::Nanosecond) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(9),
smallest_unit: TemporalUnit::Nanosecond,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
None => {
match self.precision {
Precision::Auto => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Auto,
smallest_unit: TemporalUnit::Nanosecond,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Precision::Digit(0) => Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(0),
smallest_unit: TemporalUnit::Second,
rounding_mode,
increment: RoundingIncrement::ONE,
}),
Precision::Digit(d) if (1..=3).contains(&d) => {
Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(d),
smallest_unit: TemporalUnit::Millisecond,
rounding_mode,
increment: RoundingIncrement::try_new(10_u32.pow(3 - d as u32))
.expect("a valid increment"),
})
}
Precision::Digit(d) if (4..=6).contains(&d) => {
Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(d),
smallest_unit: TemporalUnit::Microsecond,
rounding_mode,
increment: RoundingIncrement::try_new(10_u32.pow(6 - d as u32))
.expect("a valid increment"),
})
}
Precision::Digit(d) if (7..=9).contains(&d) => {
Ok(ResolvedToStringRoundingOptions {
precision: Precision::Digit(d),
smallest_unit: TemporalUnit::Nanosecond,
rounding_mode,
increment: RoundingIncrement::try_new(10_u32.pow(9 - d as u32))
.expect("a valid increment"),
})
}
_ => Err(TemporalError::range()
.with_message("Invalid fractionalDigits precision value")),
}
}
_ => {
Err(TemporalError::range().with_message("smallestUnit must be a valid time unit."))
}
}
}
}
#[non_exhaustive]
#[derive(Debug, Default, Clone, Copy)]
pub struct DifferenceSettings {
pub largest_unit: Option<TemporalUnit>,
pub smallest_unit: Option<TemporalUnit>,
pub rounding_mode: Option<TemporalRoundingMode>,
pub increment: Option<RoundingIncrement>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct RoundingOptions {
pub largest_unit: Option<TemporalUnit>,
pub smallest_unit: Option<TemporalUnit>,
pub rounding_mode: Option<TemporalRoundingMode>,
pub increment: Option<RoundingIncrement>,
}
// Note: Specification does not clearly state a default, but
// having both largest and smallest unit None would auto throw.
impl Default for RoundingOptions {
fn default() -> Self {
Self {
largest_unit: Some(TemporalUnit::Auto),
smallest_unit: None,
rounding_mode: None,
increment: None,
}
}
}
/// Internal options object that represents the resolved rounding options.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ResolvedRoundingOptions {
pub(crate) largest_unit: TemporalUnit,
pub(crate) smallest_unit: TemporalUnit,
pub(crate) increment: RoundingIncrement,
pub(crate) rounding_mode: TemporalRoundingMode,
}
impl ResolvedRoundingOptions {
pub(crate) fn from_to_string_options(options: &ResolvedToStringRoundingOptions) -> Self {
Self {
largest_unit: TemporalUnit::Auto,
smallest_unit: options.smallest_unit,
increment: options.increment,
rounding_mode: options.rounding_mode,
}
}
pub(crate) fn from_diff_settings(
options: DifferenceSettings,
operation: DifferenceOperation,
fallback_largest: TemporalUnit,
fallback_smallest: TemporalUnit,
) -> TemporalResult<Self> {
// 4. Let resolvedOptions be ? SnapshotOwnProperties(? GetOptionsObject(options), null).
// 5. Let settings be ? GetDifferenceSettings(operation, resolvedOptions, DATE, « », "day", "day").
let increment = options.increment.unwrap_or_default();
let rounding_mode = match operation {
DifferenceOperation::Since => options
.rounding_mode
.unwrap_or(TemporalRoundingMode::Trunc)
.negate(),
DifferenceOperation::Until => {
options.rounding_mode.unwrap_or(TemporalRoundingMode::Trunc)
}
};
let smallest_unit = options.smallest_unit.unwrap_or(fallback_smallest);
// Use the defaultlargestunit which is max smallestlargestdefault and smallestunit
let largest_unit = options
.largest_unit
.unwrap_or(smallest_unit.max(fallback_largest));
// 11. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
// 12. Let maximum be MaximumTemporalDurationRoundingIncrement(smallestUnit).
// 13. If maximum is not unset, perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, false).
if largest_unit < smallest_unit {
return Err(TemporalError::range().with_message(
"largestUnit when rounding Duration was not the largest provided unit",
));
}
let maximum = smallest_unit.to_maximum_rounding_increment();
if let Some(max) = maximum {
increment.validate(max.into(), false)?;
}
let resolved = ResolvedRoundingOptions {
largest_unit,
smallest_unit,
increment,
rounding_mode,
};
Ok(resolved)
}
pub(crate) fn from_duration_options(
options: RoundingOptions,
existing_largest: TemporalUnit,
) -> TemporalResult<Self> {
// 22. If smallestUnitPresent is false and largestUnitPresent is false, then
if options.largest_unit.is_none() && options.smallest_unit.is_none() {
// a. Throw a RangeError exception.
return Err(TemporalError::range()
.with_message("smallestUnit and largestUnit cannot both be None."));
}
// 14. Let roundingIncrement be ? ToTemporalRoundingIncrement(roundTo).
let increment = options.increment.unwrap_or_default();
// 15. Let roundingMode be ? ToTemporalRoundingMode(roundTo, "halfExpand").
let rounding_mode = options.rounding_mode.unwrap_or_default();
// 16. Let smallestUnit be ? GetTemporalUnit(roundTo, "smallestUnit", DATETIME, undefined).
// 17. If smallestUnit is undefined, then
// a. Set smallestUnitPresent to false.
// b. Set smallestUnit to "nanosecond".
// 18. Let existingLargestUnit be ! DefaultTemporalLargestUnit(duration.[[Years]],
// duration.[[Months]], duration.[[Weeks]], duration.[[Days]], duration.[[Hours]],
// duration.[[Minutes]], duration.[[Seconds]], duration.[[Milliseconds]],
// duration.[[Microseconds]]).
// 19. Let defaultLargestUnit be LargerOfTwoTemporalUnits(existingLargestUnit, smallestUnit).
// 20. If largestUnit is undefined, then
// a. Set largestUnitPresent to false.
// b. Set largestUnit to defaultLargestUnit.
// 21. Else if largestUnit is "auto", then
// a. Set largestUnit to defaultLargestUnit.
// 23. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
// 24. Let maximum be MaximumTemporalDurationRoundingIncrement(smallestUnit).
// 25. If maximum is not undefined, perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, false).
let smallest_unit = options.smallest_unit.unwrap_or(TemporalUnit::Nanosecond);
let default_largest = existing_largest.max(smallest_unit);
let largest_unit = match options.largest_unit {
Some(TemporalUnit::Auto) | None => default_largest,
Some(unit) => unit,
};
if largest_unit < smallest_unit {
return Err(TemporalError::range().with_message(
"largestUnit when rounding Duration was not the largest provided unit",
));
}
let maximum = smallest_unit.to_maximum_rounding_increment();
// 25. If maximum is not undefined, perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, false).
if let Some(max) = maximum {
increment.validate(max.into(), false)?;
}
Ok(Self {
largest_unit,
smallest_unit,
increment,
rounding_mode,
})
}
// NOTE: Should the GetTemporalUnitValuedOption check be integrated into these validations.
pub(crate) fn from_dt_options(options: RoundingOptions) -> TemporalResult<Self> {
let increment = options.increment.unwrap_or_default();
let rounding_mode = options.rounding_mode.unwrap_or_default();
let smallest_unit = options.smallest_unit.unwrap_or(TemporalUnit::Day);
let (maximum, inclusive) = if smallest_unit == TemporalUnit::Day {
(1, true)
} else {
let maximum = smallest_unit
.to_maximum_rounding_increment()
.ok_or(TemporalError::range().with_message("smallestUnit must be a time unit."))?;
(maximum, false)
};
increment.validate(maximum.into(), inclusive)?;
Ok(Self {
largest_unit: TemporalUnit::Auto,
smallest_unit,
increment,
rounding_mode,
})
}
pub(crate) fn from_instant_options(options: RoundingOptions) -> TemporalResult<Self> {
let increment = options.increment.unwrap_or_default();
let rounding_mode = options.rounding_mode.unwrap_or_default();
let Some(smallest_unit) = options.smallest_unit else {
return Err(TemporalError::range()
.with_message("smallestUnit is required for an Instant.round operation."));
};
let maximum = match smallest_unit {
TemporalUnit::Hour => 24u64,
TemporalUnit::Minute => 24 * 60,
TemporalUnit::Second => 24 * 3600,
TemporalUnit::Millisecond => MS_PER_DAY as u64,
TemporalUnit::Microsecond => MS_PER_DAY as u64 * 1000,
TemporalUnit::Nanosecond => NS_PER_DAY,
_ => return Err(TemporalError::range().with_message("Invalid roundTo unit provided.")),
};
increment.validate(maximum, true)?;
Ok(Self {
largest_unit: TemporalUnit::Auto,
smallest_unit,
increment,
rounding_mode,
})
}
pub(crate) fn is_noop(&self) -> bool {
self.smallest_unit == TemporalUnit::Nanosecond && self.increment == RoundingIncrement::ONE
}
}
// ==== Options enums and methods ====
/// The relevant unit that should be used for the operation that
/// this option is provided as a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TemporalUnit {
/// The `Auto` unit
Auto = 0,
/// The `Nanosecond` unit
Nanosecond,
/// The `Microsecond` unit
Microsecond,
/// The `Millisecond` unit
Millisecond,
/// The `Second` unit
Second,
/// The `Minute` unit
Minute,
/// The `Hour` unit
Hour,
/// The `Day` unit
Day,
/// The `Week` unit
Week,
/// The `Month` unit
Month,
/// The `Year` unit
Year,
}
impl TemporalUnit {
#[inline]
#[must_use]
/// Returns the `MaximumRoundingIncrement` for the current `TemporalUnit`.
pub fn to_maximum_rounding_increment(self) -> Option<u32> {
use TemporalUnit::{
Auto, Day, Hour, Microsecond, Millisecond, Minute, Month, Nanosecond, Second, Week,
Year,
};
// 1. If unit is "year", "month", "week", or "day", then
// a. Return undefined.
// 2. If unit is "hour", then
// a. Return 24.
// 3. If unit is "minute" or "second", then
// a. Return 60.
// 4. Assert: unit is one of "millisecond", "microsecond", or "nanosecond".
// 5. Return 1000.
let max = match self {
Year | Month | Week | Day => return None,
Hour => 24,
Minute | Second => 60,
Millisecond | Microsecond | Nanosecond => 1000,
Auto => unreachable!(),
};
Some(max)
}
// TODO: potentiall use a u64
/// Returns the `Nanosecond amount for any given value.`
#[must_use]
pub fn as_nanoseconds(&self) -> Option<u64> {
use TemporalUnit::{
Auto, Day, Hour, Microsecond, Millisecond, Minute, Month, Nanosecond, Second, Week,
Year,
};
match self {
Year | Month | Week | Auto => None,
Day => Some(NS_PER_DAY),
Hour => Some(3_600_000_000_000),
Minute => Some(60_000_000_000),
Second => Some(1_000_000_000),
Millisecond => Some(1_000_000),
Microsecond => Some(1_000),
Nanosecond => Some(1),
}
}
#[inline]
#[must_use]
pub fn is_calendar_unit(&self) -> bool {
use TemporalUnit::{Month, Week, Year};
matches!(self, Year | Month | Week)
}
#[inline]
#[must_use]
pub fn is_time_unit(&self) -> bool {
use TemporalUnit::{Hour, Microsecond, Millisecond, Minute, Nanosecond, Second};
matches!(
self,
Hour | Minute | Second | Millisecond | Microsecond | Nanosecond
)
}
}
impl From<usize> for TemporalUnit {
fn from(value: usize) -> Self {
match value {
10 => Self::Year,
9 => Self::Month,
8 => Self::Week,
7 => Self::Day,
6 => Self::Hour,
5 => Self::Minute,
4 => Self::Second,
3 => Self::Millisecond,
2 => Self::Microsecond,
1 => Self::Nanosecond,
_ => Self::Auto,
}
}
}
impl Add<usize> for TemporalUnit {
type Output = TemporalUnit;
fn add(self, rhs: usize) -> Self::Output {
TemporalUnit::from(self as usize + rhs)
}
}
/// A parsing error for `TemporalUnit`
#[derive(Debug, Clone, Copy)]
pub struct ParseTemporalUnitError;
impl fmt::Display for ParseTemporalUnitError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("provided string was not a valid TemporalUnit")
}
}
impl FromStr for TemporalUnit {
type Err = ParseTemporalUnitError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Self::Auto),
"year" | "years" => Ok(Self::Year),
"month" | "months" => Ok(Self::Month),
"week" | "weeks" => Ok(Self::Week),
"day" | "days" => Ok(Self::Day),
"hour" | "hours" => Ok(Self::Hour),
"minute" | "minutes" => Ok(Self::Minute),
"second" | "seconds" => Ok(Self::Second),
"millisecond" | "milliseconds" => Ok(Self::Millisecond),
"microsecond" | "microseconds" => Ok(Self::Microsecond),
"nanosecond" | "nanoseconds" => Ok(Self::Nanosecond),
_ => Err(ParseTemporalUnitError),
}
}
}
impl fmt::Display for TemporalUnit {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Auto => "auto",
Self::Year => "year",
Self::Month => "month",
Self::Week => "week",
Self::Day => "day",
Self::Hour => "hour",
Self::Minute => "minute",
Self::Second => "second",
Self::Millisecond => "millsecond",
Self::Microsecond => "microsecond",
Self::Nanosecond => "nanosecond",
}
.fmt(f)
}
}
/// `ArithmeticOverflow` can also be used as an
/// assignment overflow and consists of the "constrain"
/// and "reject" options.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ArithmeticOverflow {
/// Constrain option
#[default]
Constrain,
/// Constrain option
Reject,
}
/// A parsing error for `ArithemeticOverflow`
#[derive(Debug, Clone, Copy)]
pub struct ParseArithmeticOverflowError;
impl fmt::Display for ParseArithmeticOverflowError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("provided string was not a valid overflow value")
}
}
impl FromStr for ArithmeticOverflow {
type Err = ParseArithmeticOverflowError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"constrain" => Ok(Self::Constrain),
"reject" => Ok(Self::Reject),
_ => Err(ParseArithmeticOverflowError),
}
}
}
impl fmt::Display for ArithmeticOverflow {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Constrain => "constrain",
Self::Reject => "reject",
}
.fmt(f)
}
}
/// `Duration` overflow options.
#[derive(Debug, Clone, Copy)]
pub enum DurationOverflow {
/// Constrain option
Constrain,
/// Balance option
Balance,
}
/// A parsing error for `DurationOverflow`.
#[derive(Debug, Clone, Copy)]
pub struct ParseDurationOverflowError;
impl fmt::Display for ParseDurationOverflowError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("provided string was not a valid duration overflow value")
}
}
impl FromStr for DurationOverflow {
type Err = ParseDurationOverflowError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"constrain" => Ok(Self::Constrain),
"balance" => Ok(Self::Balance),
_ => Err(ParseDurationOverflowError),
}
}
}
impl fmt::Display for DurationOverflow {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Constrain => "constrain",
Self::Balance => "balance",
}
.fmt(f)
}
}
/// The disambiguation options for an instant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Disambiguation {
/// Compatible option
Compatible,
/// Earlier option
Earlier,
/// Later option
Later,
/// Reject option
Reject,
}
/// A parsing error on `InstantDisambiguation` options.
#[derive(Debug, Clone, Copy)]
pub struct ParseDisambiguationError;
impl fmt::Display for ParseDisambiguationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("provided string was not a valid instant disambiguation value")
}
}
impl FromStr for Disambiguation {
type Err = ParseDisambiguationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"compatible" => Ok(Self::Compatible),
"earlier" => Ok(Self::Earlier),
"later" => Ok(Self::Later),
"reject" => Ok(Self::Reject),
_ => Err(ParseDisambiguationError),
}
}
}
impl fmt::Display for Disambiguation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Compatible => "compatible",
Self::Earlier => "earlier",
Self::Later => "later",
Self::Reject => "reject",
}
.fmt(f)
}
}
/// Offset disambiguation options.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum OffsetDisambiguation {
/// Use option
Use,
/// Prefer option
Prefer,
/// Ignore option
Ignore,
/// Reject option
Reject,
}
/// A parsing error for `OffsetDisambiguation` parsing.
#[derive(Debug, Clone, Copy)]
pub struct ParseOffsetDisambiguationError;
impl fmt::Display for ParseOffsetDisambiguationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("provided string was not a valid offset disambiguation value")
}
}
impl FromStr for OffsetDisambiguation {
type Err = ParseOffsetDisambiguationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"use" => Ok(Self::Use),
"prefer" => Ok(Self::Prefer),
"ignore" => Ok(Self::Ignore),
"reject" => Ok(Self::Reject),
_ => Err(ParseOffsetDisambiguationError),
}
}
}
impl fmt::Display for OffsetDisambiguation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Use => "use",
Self::Prefer => "prefer",
Self::Ignore => "ignore",
Self::Reject => "reject",
}
.fmt(f)
}
}
// TODO: Figure out what to do with intl's RoundingMode
/// Declares the specified `RoundingMode` for the operation.
#[derive(Debug, Copy, Clone, Default)]
pub enum TemporalRoundingMode {
/// Ceil RoundingMode
Ceil,
/// Floor RoundingMode
Floor,
/// Expand RoundingMode
Expand,
/// Truncate RoundingMode
Trunc,
/// HalfCeil RoundingMode
HalfCeil,
/// HalfFloor RoundingMode
HalfFloor,
/// HalfExpand RoundingMode - Default
#[default]
HalfExpand,
/// HalfTruncate RoundingMode
HalfTrunc,
/// HalfEven RoundingMode
HalfEven,
}
/// The `UnsignedRoundingMode`
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TemporalUnsignedRoundingMode {
/// `Infinity` `RoundingMode`
Infinity,
/// `Zero` `RoundingMode`
Zero,
/// `HalfInfinity` `RoundingMode`
HalfInfinity,
/// `HalfZero` `RoundingMode`
HalfZero,
/// `HalfEven` `RoundingMode`
HalfEven,
}
impl TemporalRoundingMode {
#[inline]
#[must_use]
/// Negates the current `RoundingMode`.
pub const fn negate(self) -> Self {
use TemporalRoundingMode::{
Ceil, Expand, Floor, HalfCeil, HalfEven, HalfExpand, HalfFloor, HalfTrunc, Trunc,
};
match self {
Ceil => Self::Floor,
Floor => Self::Ceil,
HalfCeil => Self::HalfFloor,
HalfFloor => Self::HalfCeil,
Trunc => Self::Trunc,
Expand => Self::Expand,
HalfTrunc => Self::HalfTrunc,
HalfExpand => Self::HalfExpand,
HalfEven => Self::HalfEven,
}
}
#[inline]
#[must_use]
/// Returns the `UnsignedRoundingMode`
pub const fn get_unsigned_round_mode(self, is_positive: bool) -> TemporalUnsignedRoundingMode {
use TemporalRoundingMode::{
Ceil, Expand, Floor, HalfCeil, HalfEven, HalfExpand, HalfFloor, HalfTrunc, Trunc,
};
match self {
Ceil if is_positive => TemporalUnsignedRoundingMode::Infinity,
Ceil | Trunc => TemporalUnsignedRoundingMode::Zero,
Floor if is_positive => TemporalUnsignedRoundingMode::Zero,
Floor | Expand => TemporalUnsignedRoundingMode::Infinity,
HalfCeil if is_positive => TemporalUnsignedRoundingMode::HalfInfinity,
HalfCeil | HalfTrunc => TemporalUnsignedRoundingMode::HalfZero,
HalfFloor if is_positive => TemporalUnsignedRoundingMode::HalfZero,
HalfFloor | HalfExpand => TemporalUnsignedRoundingMode::HalfInfinity,
HalfEven => TemporalUnsignedRoundingMode::HalfEven,
}
}
}
impl FromStr for TemporalRoundingMode {
type Err = TemporalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ceil" => Ok(Self::Ceil),
"floor" => Ok(Self::Floor),
"expand" => Ok(Self::Expand),
"trunc" => Ok(Self::Trunc),
"halfCeil" => Ok(Self::HalfCeil),
"halfFloor" => Ok(Self::HalfFloor),
"halfExpand" => Ok(Self::HalfExpand),
"halfTrunc" => Ok(Self::HalfTrunc),
"halfEven" => Ok(Self::HalfEven),
_ => Err(TemporalError::range().with_message("RoundingMode not an accepted value.")),
}
}
}
impl fmt::Display for TemporalRoundingMode {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Ceil => "ceil",
Self::Floor => "floor",
Self::Expand => "expand",
Self::Trunc => "trunc",
Self::HalfCeil => "halfCeil",
Self::HalfFloor => "halfFloor",
Self::HalfExpand => "halfExpand",
Self::HalfTrunc => "halfTrunc",
Self::HalfEven => "halfEven",
}
.fmt(f)
}
}
/// values for `CalendarName`, whether to show the calendar in toString() methods
/// <https://tc39.es/proposal-temporal/#sec-temporal-gettemporalshowcalendarnameoption>
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DisplayCalendar {
#[default]
/// `Auto` option
Auto,
/// `Always` option
Always,
/// `Never` option
Never,
// `Critical` option
Critical,
}
impl fmt::Display for DisplayCalendar {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
DisplayCalendar::Auto => "auto",
DisplayCalendar::Always => "always",
DisplayCalendar::Never => "never",
DisplayCalendar::Critical => "critical",
}
.fmt(f)
}
}
impl FromStr for DisplayCalendar {
type Err = TemporalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Self::Auto),
"always" => Ok(Self::Always),
"never" => Ok(Self::Never),
"critical" => Ok(Self::Critical),
_ => Err(TemporalError::range().with_message("Invalid calendarName provided.")),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DisplayOffset {
#[default]
Auto,
Never,
}
impl fmt::Display for DisplayOffset {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
DisplayOffset::Auto => "auto",
DisplayOffset::Never => "never",
}
.fmt(f)
}
}
impl FromStr for DisplayOffset {
type Err = TemporalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Self::Auto),
"never" => Ok(Self::Never),
_ => Err(TemporalError::range().with_message("Invalid offset option provided.")),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DisplayTimeZone {
#[default]
/// `Auto` option
Auto,
/// `Never` option
Never,
// `Critical` option
Critical,
}
impl fmt::Display for DisplayTimeZone {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
DisplayTimeZone::Auto => "auto",
DisplayTimeZone::Never => "never",
DisplayTimeZone::Critical => "critical",
}
.fmt(f)
}
}
impl FromStr for DisplayTimeZone {
type Err = TemporalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Self::Auto),
"never" => Ok(Self::Never),
"critical" => Ok(Self::Critical),
_ => Err(TemporalError::range().with_message("Invalid timeZoneName option provided.")),
}
}
}