forked from boa-dev/temporal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalized.rs
More file actions
1386 lines (1264 loc) · 59.9 KB
/
normalized.rs
File metadata and controls
1386 lines (1264 loc) · 59.9 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
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
//! This module implements the normalized `Duration` records.
use core::{cmp, num::NonZeroU128, ops::Add};
use num_traits::AsPrimitive;
use timezone_provider::epoch_nanoseconds::EpochNanoseconds;
use crate::{
builtins::{
core::{time_zone::TimeZone, PlainDate, PlainDateTime},
duration::TWO_POWER_FIFTY_THREE,
},
iso::{IsoDate, IsoDateTime},
options::{
Disambiguation, Overflow, ResolvedRoundingOptions, RoundingIncrement, RoundingMode, Unit,
UNIT_VALUE_TABLE,
},
primitive::{DoubleDouble, FiniteF64},
provider::TimeZoneProvider,
rounding::IncrementRounder,
temporal_assert, Calendar, NonZeroSign, TemporalError, TemporalResult, TemporalUnwrap,
NS_PER_DAY, NS_PER_DAY_NONZERO,
};
use super::{DateDuration, Duration, Sign};
const MAX_TIME_DURATION: i128 = 9_007_199_254_740_991_999_999_999;
const MAX_SAFE_INTEGER: i128 = TWO_POWER_FIFTY_THREE - 1;
// Nanoseconds constants
const NS_PER_DAY_128BIT: i128 = NS_PER_DAY as i128;
const NANOSECONDS_PER_MINUTE: i128 = 60 * 1_000_000_000;
const NANOSECONDS_PER_HOUR: i128 = 60 * NANOSECONDS_PER_MINUTE;
// ==== TimeDuration ====
//
// A time duration represented in pure nanoseconds.
//
// Invariants:
//
// nanoseconds.abs() <= MAX_TIME_DURATION
/// A Normalized `TimeDuration` that represents the current `TimeDuration` in nanoseconds.
#[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd, Eq, Ord)]
pub(crate) struct TimeDuration(pub(crate) i128);
impl TimeDuration {
/// Creates a `TimeDuration` from signed integer components.
/// This method preserves the sign of each component during the calculation.
pub(crate) fn from_components(
hours: i64,
minutes: i64,
seconds: i64,
milliseconds: i64,
microseconds: i128,
nanoseconds: i128,
) -> Self {
let mut total_nanoseconds: i128 = 0;
total_nanoseconds += i128::from(hours) * NANOSECONDS_PER_HOUR;
total_nanoseconds += i128::from(minutes) * NANOSECONDS_PER_MINUTE;
total_nanoseconds += i128::from(seconds) * 1_000_000_000;
total_nanoseconds += i128::from(milliseconds) * 1_000_000;
total_nanoseconds += microseconds * 1_000;
total_nanoseconds += nanoseconds;
debug_assert!(total_nanoseconds.abs() <= MAX_TIME_DURATION);
Self(total_nanoseconds)
}
/// Equivalent: 7.5.20 NormalizeTimeDuration ( hours, minutes, seconds, milliseconds, microseconds, nanoseconds )
pub(crate) fn from_duration(duration: &Duration) -> Self {
// Note: Calculations must be done after casting to `i128` in order to preserve precision
let sign_multiplier = duration.sign().as_sign_multiplier() as i128;
let mut nanoseconds: i128 =
i128::from(duration.hours) * NANOSECONDS_PER_HOUR * sign_multiplier;
nanoseconds += i128::from(duration.minutes) * NANOSECONDS_PER_MINUTE * sign_multiplier;
nanoseconds += i128::from(duration.seconds) * 1_000_000_000 * sign_multiplier;
nanoseconds += i128::from(duration.milliseconds) * 1_000_000 * sign_multiplier;
nanoseconds += duration.microseconds as i128 * 1_000 * sign_multiplier;
nanoseconds += duration.nanoseconds as i128 * sign_multiplier;
// NOTE(nekevss): Is it worth returning a `RangeError` below.
debug_assert!(nanoseconds.abs() <= MAX_TIME_DURATION);
Self(nanoseconds)
}
/// Equivalent to 7.5.27 TimeDurationFromEpochNanosecondsDifference ( one, two )
pub(crate) fn from_nanosecond_difference(one: i128, two: i128) -> TemporalResult<Self> {
let result = one - two;
if result.abs() > MAX_TIME_DURATION {
return Err(
TemporalError::range().with_message("TimeDuration exceeds maxTimeDuration.")
);
}
Ok(Self(result))
}
/// Equivalent: 7.5.23 Add24HourDaysToTimeDuration ( d, days )
/// Add24HourDaysToTimeDuration??
pub(crate) fn add_days(&self, days: i64) -> TemporalResult<Self> {
let result = self.0 + i128::from(days) * i128::from(NS_PER_DAY);
if result.abs() > MAX_TIME_DURATION {
return Err(TemporalError::range()
.with_message("SubtractTimeDuration exceeded a valid Duration range."));
}
Ok(Self(result))
}
/// `Divide the NormalizedTimeDuraiton` by a divisor, truncating
/// the result
pub(crate) fn truncated_divide(&self, divisor: u64) -> i128 {
// TODO: Validate.
self.0 / i128::from(divisor)
}
pub(crate) fn divide(&self, divisor: f64) -> f64 {
self.0 as f64 / divisor
}
/// Equivalent: 7.5.31 TimeDurationSign ( d )
#[inline]
#[must_use]
pub(crate) fn sign(&self) -> Sign {
Sign::from(self.0.cmp(&0) as i8)
}
// NOTE(nekevss): non-euclid is required here for negative rounding.
/// Return the seconds value of the `TimeDuration`.
pub(crate) fn seconds(&self) -> i64 {
// SAFETY: See validate_second_cast test.
(self.0 / 1_000_000_000) as i64
}
// NOTE(nekevss): non-euclid is required here for negative rounding.
/// Returns the subsecond components of the `TimeDuration`.
pub(crate) fn subseconds(&self) -> i32 {
// SAFETY: Remainder is 10e9 which is in range of i32
(self.0 % 1_000_000_000) as i32
}
fn negate(&self) -> Self {
Self(-self.0)
}
pub(crate) fn checked_sub(&self, other: &Self) -> TemporalResult<Self> {
let result = self.0 - other.0;
if result.abs() > MAX_TIME_DURATION {
return Err(TemporalError::range()
.with_message("SubtractTimeDuration exceeded a valid TimeDuration range."));
}
Ok(Self(result))
}
/// The equivalent of `RoundTimeDuration` abstract operation.
pub(crate) fn round(&self, options: ResolvedRoundingOptions) -> TemporalResult<Self> {
// a. Assert: The value in the "Category" column of the row of Table 22 whose "Singular" column contains unit, is time.
// b. Let divisor be the value in the "Length in Nanoseconds" column of the row of Table 22 whose "Singular" column contains unit.
let divisor = options.smallest_unit.as_nanoseconds().temporal_unwrap()?;
// c. Let total be DivideTimeDuration(norm, divisor).
let increment = options
.increment
.as_extended_increment()
.checked_mul(divisor)
.temporal_unwrap()?;
// d. Set norm to ? RoundTimeDurationToIncrement(norm, divisor × increment, roundingMode).
self.round_inner(increment, options.rounding_mode)
}
/// Equivalent: 7.5.31 TotalTimeDuration ( timeDuration, unit )
/// TODO Fix: Arithemtic on floating point numbers is not safe. According to NOTE 2 in the spec
pub(crate) fn total(&self, unit: Unit) -> TemporalResult<FiniteF64> {
let time_duration = self.0;
// 1. Let divisor be the value in the "Length in Nanoseconds" column of the row of Table 21 whose "Value" column contains unit.
let unit_nanoseconds = unit.as_nanoseconds().temporal_unwrap()?;
// 2. NOTE: The following step cannot be implemented directly using floating-point arithmetic when 𝔽(timeDuration) is not a safe integer.
// The division can be implemented in C++ with the __float128 type if the compiler supports it, or with software emulation such as in the SoftFP library.
// 3. Return timeDuration / divisor.
Ok(Fraction::new(time_duration, unit_nanoseconds.get() as f64).to_finite_f64())
}
pub(crate) fn round_to_fractional_days(
&self,
increment: RoundingIncrement,
mode: RoundingMode,
) -> TemporalResult<i64> {
let adjusted_increment = increment
.as_extended_increment()
.saturating_mul(NS_PER_DAY_NONZERO);
let rounded =
IncrementRounder::<i128>::from_signed_num(self.0, adjusted_increment)?.round(mode);
Ok((rounded / NS_PER_DAY_128BIT) as i64)
}
/// Round the current `TimeDuration`.
pub(super) fn round_inner(
&self,
increment: NonZeroU128,
mode: RoundingMode,
) -> TemporalResult<Self> {
let rounded = IncrementRounder::<i128>::from_signed_num(self.0, increment)?.round(mode);
if rounded.abs() > MAX_TIME_DURATION {
return Err(
TemporalError::range().with_message("TimeDuration exceeds maxTimeDuration.")
);
}
Ok(Self(rounded))
}
pub(super) fn checked_add(&self, other: i128) -> TemporalResult<Self> {
let result = self.0 + other;
if result.abs() > MAX_TIME_DURATION {
return Err(
TemporalError::range().with_message("TimeDuration exceeds maxTimeDuration.")
);
}
Ok(Self(result))
}
}
// NOTE(nekevss): As this `Add` impl is fallible. Maybe it would be best implemented as a method.
/// Equivalent: 7.5.22 AddTimeDuration ( one, two )
impl Add<Self> for TimeDuration {
type Output = TemporalResult<Self>;
fn add(self, rhs: Self) -> Self::Output {
let result = self.0 + rhs.0;
if result.abs() > MAX_TIME_DURATION {
return Err(
TemporalError::range().with_message("TimeDuration exceeds maxTimeDuration.")
);
}
Ok(Self(result))
}
}
// Struct to fractional division steps in `TotalTimeDuration`
struct Fraction {
numerator: i128,
denominator: f64,
}
impl Fraction {
pub fn new(numerator: i128, denominator: f64) -> Self {
Self {
numerator,
denominator,
}
}
// NOTE: Functionally similar to SM and JSC's `fractionToDouble`
//
// For more information on this implementation, see the
// JavaScriptCore's [fractionToDouble.cpp](https://github.com/WebKit/WebKit/blob/main/Source/JavaScriptCore/runtime/FractionToDouble.cpp)
// or SpiderMonkey's [FractionToDouble](https://github.com/mozilla-firefox/firefox/blob/main/js/src/builtin/temporal/Temporal.cpp#L683)
//
// The JavaScriptCore implementation is recommended as it has fairly robust documentation
// on the underlying papers that have informed this approach.
/// Calculate an `f64` from a numerator and denominator that may
/// be beyond the max safe integer range.
pub(crate) fn to_finite_f64(&self) -> FiniteF64 {
if self.denominator == 1. {
return FiniteF64(self.numerator as f64); // This operation is lossy.
}
if self.numerator.abs() < MAX_SAFE_INTEGER {
return FiniteF64(self.numerator as f64 / self.denominator);
}
self.to_finite_f64_slow()
}
/// The slow path for calculating a `f64` beyond the max safe integer range.
#[cold]
pub(crate) fn to_finite_f64_slow(&self) -> FiniteF64 {
let dd_numerator = DoubleDouble::from(self.numerator);
// First approx quotient
let q0 = dd_numerator.hi / self.denominator;
// Find remainder
let product = DoubleDouble::mul(q0, self.denominator);
let remainder = DoubleDouble::sum(dd_numerator.hi, -product.hi);
// Find second approx. quotient
let error = remainder.lo + dd_numerator.lo - product.lo;
let q1 = (remainder.hi + error) / self.denominator;
FiniteF64(q0 + q1)
}
}
// ==== Internal Duration record ====
//
// A record consisting of a DateDuration and TimeDuration
//
/// An InternalDurationRecord is a duration record that contains
/// a `DateDuration` and `TimeDuration`.
#[derive(Debug, Default, Clone, Copy)]
pub struct InternalDurationRecord {
date: DateDuration,
norm: TimeDuration,
}
impl InternalDurationRecord {
pub(crate) fn combine(date: DateDuration, norm: TimeDuration) -> Self {
// 1. Let dateSign be DateDurationSign(dateDuration).
// 2. Let timeSign be TimeDurationSign(timeDuration).
// 3. Assert: If dateSign ≠ 0 and timeSign ≠ 0, dateSign = timeSign.
// 4. Return Internal Duration Record { [[Date]]: dateDuration, [[Time]]: timeDuration }.
Self { date, norm }
}
/// Creates a new `NormalizedDurationRecord`.
///
/// Equivalent: `CreateNormalizedDurationRecord` & `CombineDateAndTimeDuration`.
pub(crate) fn new(date: DateDuration, norm: TimeDuration) -> TemporalResult<Self> {
if date.sign() != Sign::Zero && norm.sign() != Sign::Zero && date.sign() != norm.sign() {
return Err(TemporalError::range()
.with_message("DateDuration and TimeDuration must agree if both are not zero."));
}
Ok(Self { date, norm })
}
/// Equivalent of `7.5.6 ToInternalDurationRecordWith24HourDays ( duration )`
///
/// Spec: <https://tc39.es/proposal-temporal/#sec-temporal-tointernaldurationrecordwith24hourdays>
pub(crate) fn from_duration_with_24_hour_days(duration: &Duration) -> TemporalResult<Self> {
// 1. Let timeDuration be TimeDurationFromComponents(duration.[[Hours]], duration.[[Minutes]],
// duration.[[Seconds]], duration.[[Milliseconds]], duration.[[Microseconds]], duration.[[Nanoseconds]]).
let normalized_time = TimeDuration::from_duration(duration);
// 2. Set timeDuration to ! Add24HourDaysToTimeDuration(timeDuration, duration.[[Days]]).
let normalized_time = normalized_time.add_days(duration.days())?;
// 3. Let dateDuration be ! CreateDateDurationRecord(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], 0).
let date =
DateDuration::new_unchecked(duration.years(), duration.months(), duration.weeks(), 0);
// 4. Return CombineDateAndTimeDuration(dateDuration, timeDuration).
Self::new(date, normalized_time)
}
/// Equivalent of [`7.5.7 ToDateDurationRecordWithoutTime ( duration )`][spec]
///
/// [spec]: <https://tc39.es/proposal-temporal/#sec-temporal-tointernaldurationrecordwith24hourdays>
///
// spec(2025-06-23): https://github.com/tc39/proposal-temporal/tree/ed49b0b482981119c9b5e28b0686d877d4a9bae0
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_date_duration_record_without_time(&self) -> TemporalResult<DateDuration> {
// 1. Let internalDuration be ToInternalDurationRecordWith24HourDays(duration).
let internal_duration = self;
// NOTE: days SHOULD be in range of an i64.
// MAX_TIME_DURATION / NS_PER_DAY <= i64::MAX
// 2. Let days be truncate(internalDuration.[[Time]] / nsPerDay).
let days = (internal_duration.normalized_time_duration().0 / i128::from(NS_PER_DAY)) as i64;
// 3. Return ! CreateDateDurationRecord(internalDuration.[[Date]].[[Years]], internalDuration.[[Date]].[[Months]], internalDuration.[[Date]].[[Weeks]], days).
DateDuration::new(
internal_duration.date().years,
internal_duration.date().months,
internal_duration.date().weeks,
days,
)
}
pub(crate) fn from_date_duration(date: DateDuration) -> TemporalResult<Self> {
Self::new(date, TimeDuration::default())
}
pub(crate) fn date(&self) -> DateDuration {
self.date
}
pub(crate) fn normalized_time_duration(&self) -> TimeDuration {
self.norm
}
pub(crate) fn sign(&self) -> Sign {
let date_sign = self.date.sign();
if date_sign == Sign::Zero {
self.norm.sign()
} else {
date_sign
}
}
}
// ==== Nudge Duration Rounding Functions ====
// Below implements the nudge rounding functionality for Duration.
//
// Generally, this rounding is implemented on a NormalizedDurationRecord,
// which is the reason the functionality lives below.
#[derive(Debug)]
struct NudgeRecord {
normalized: InternalDurationRecord,
nudge_epoch_ns: i128,
expanded: bool,
}
#[derive(Debug)]
struct NudgeWindow {
r1: i128,
r2: i128,
start_epoch_ns: EpochNanoseconds,
end_epoch_ns: EpochNanoseconds,
start_duration: DateDuration,
end_duration: DateDuration,
}
impl InternalDurationRecord {
/// `compute_and_adjust_nudge_window` in `temporal_rs` refers to step 1-12 of `NudgeToCalendarUnit`.
fn compute_and_adjust_nudge_window(
&self,
sign: NonZeroSign,
origin_epoch_ns: EpochNanoseconds,
dest_epoch_ns: i128,
dt: &PlainDateTime,
time_zone: Option<(&TimeZone, &(impl TimeZoneProvider + ?Sized))>, // ???
options: ResolvedRoundingOptions,
) -> TemporalResult<(NudgeWindow, bool)> {
let dest_epoch_ns = EpochNanoseconds(dest_epoch_ns);
// 1. Let didExpandCalendarUnit be false.
let mut did_expand_calendar_unit = false;
// 2. Let nudgeWindow be ? ComputeNudgeWindow(sign, duration, originEpochNs, isoDateTime, timeZone, calendar, increment, unit, false).
let mut nudge_window =
self.compute_nudge_window(sign, origin_epoch_ns, dt, time_zone, options, false)?;
// 3. Let startEpochNs be nudgeWindow.[[StartEpochNs]].
// 4. Let endEpochNs be nudgeWindow.[[EndEpochNs]].
// (implicitly used)
// 5. If sign is 1, then
match sign {
NonZeroSign::Positive => {
// a. If startEpochNs ≤ destEpochNs ≤ endEpochNs is false, then
if !(nudge_window.start_epoch_ns <= dest_epoch_ns
&& dest_epoch_ns <= nudge_window.end_epoch_ns)
{
// i. Set nudgeWindow to ? ComputeNudgeWindow(sign, duration, originEpochNs, isoDateTime, timeZone, calendar, increment, unit, true).
nudge_window = self.compute_nudge_window(
sign,
origin_epoch_ns,
dt,
time_zone,
options,
true,
)?;
// ii. Assert: nudgeWindow.[[StartEpochNs]] ≤ destEpochNs ≤ nudgeWindow.[[EndEpochNs]].
temporal_assert!(
nudge_window.start_epoch_ns <= dest_epoch_ns
&& dest_epoch_ns <= nudge_window.end_epoch_ns
);
// iii. Set didExpandCalendarUnit to true.
did_expand_calendar_unit = true;
}
}
NonZeroSign::Negative => {
// a. If endEpochNs ≤ destEpochNs ≤ startEpochNs is false, then
if !(nudge_window.end_epoch_ns <= dest_epoch_ns
&& dest_epoch_ns <= nudge_window.start_epoch_ns)
{
// i. Set nudgeWindow to ? ComputeNudgeWindow(sign, duration, originEpochNs, isoDateTime, timeZone, calendar, increment, unit, true).
nudge_window = self.compute_nudge_window(
sign,
origin_epoch_ns,
dt,
time_zone,
options,
true,
)?;
// ii. Assert: nudgeWindow.[[EndEpochNs]] ≤ destEpochNs ≤ nudgeWindow.[[StartEpochNs]].
temporal_assert!(
nudge_window.end_epoch_ns <= dest_epoch_ns
&& dest_epoch_ns <= nudge_window.start_epoch_ns
);
// iii. Set didExpandCalendarUnit to true.
did_expand_calendar_unit = true;
}
}
}
Ok((nudge_window, did_expand_calendar_unit))
}
/// <https://tc39.es/proposal-temporal/#sec-temporal-computenudgewindow>
fn compute_nudge_window(
&self,
sign: NonZeroSign,
origin_epoch_ns: EpochNanoseconds,
dt: &PlainDateTime,
time_zone: Option<(&TimeZone, &(impl TimeZoneProvider + ?Sized))>, // ???
options: ResolvedRoundingOptions,
additional_shift: bool,
) -> TemporalResult<NudgeWindow> {
// NOTE: r2 may never be used...need to test.
let (r1, r2, start_duration, end_duration) = match options.smallest_unit {
// 1. If unit is "year", then
Unit::Year => {
// a. Let years be RoundNumberToIncrement(duration.[[Years]], increment, "trunc").
let years = IncrementRounder::from_signed_num(
self.date().years,
options.increment.as_extended_increment(),
)?
.round(RoundingMode::Trunc);
let increment_x_sign =
i128::from(options.increment.get()) * i128::from(sign.as_sign_multiplier());
// b. If additionalShift is false, then
let r1 = if !additional_shift {
// i. Let r1 be years.
years
} else {
// i. Let r1 be years + increment × sign.
years + increment_x_sign
};
// c. Let r2 be r1 + increment × sign.
let r2 = r1 + increment_x_sign;
// d. Let startDuration be ? CreateNormalizedDurationRecord(r1, 0, 0, 0, ZeroTimeDuration()).
// e. Let endDuration be ? CreateNormalizedDurationRecord(r2, 0, 0, 0, ZeroTimeDuration()).
(
r1,
r2,
DateDuration::new(
i64::try_from(r1).map_err(|_| TemporalError::range())?,
0,
0,
0,
)?,
DateDuration::new(
i64::try_from(r2).map_err(|_| TemporalError::range())?,
0,
0,
0,
)?,
)
}
// 2. Else if unit is "month", then
Unit::Month => {
// a. Let months be RoundNumberToIncrement(duration.[[Months]], increment, "trunc").
let months = IncrementRounder::from_signed_num(
self.date().months,
options.increment.as_extended_increment(),
)?
.round(RoundingMode::Trunc);
let increment_x_sign =
i128::from(options.increment.get()) * i128::from(sign.as_sign_multiplier());
// b. If additionalShift is false, then
let r1 = if !additional_shift {
// i. Let r1 be months.
months
// c. Else
} else {
// i. Let r1 be months + increment × sign.
months + increment_x_sign
};
// d. Let r2 be r1 + increment × sign.
let r2 = r1 + increment_x_sign;
// e. Let startDuration be ? AdjustDateDurationRecord(duration.[[Date]], 0, 0, r1).
// f. Let endDuration be ? AdjustDateDurationRecord(duration.[[Date]], 0, 0, r2).
(
r1,
r2,
self.date().adjust(
0,
None,
Some(i64::try_from(r1).map_err(|_| TemporalError::range())?),
)?,
self.date().adjust(
0,
None,
Some(i64::try_from(r2).map_err(|_| TemporalError::range())?),
)?,
)
}
// 3. Else if unit is "week", then
Unit::Week => {
// TODO: Reconcile potential overflow on years as i32. `ValidateDuration`
// requires years, months, weeks to be abs(x) <= 2^32.
//
// Do we even care? This needs tests, but even a truncated i32::MAX is still
// FAR TOO LARGE for adding to a duration and will throw at steps c-d. This
// is only really an issue, because we are trying to optimize out floating
// points, but it may really show that a Duration's max range is very very
// very big. Too big. To be tested and determined.
//
// In other words, our year range is roughly +/- 280_000? Let's add 2^32 to
// that. It won't overflow, right?
// a. Let isoResult1 be BalanceISODate(dateTime.[[Year]] + duration.[[Years]],
// dateTime.[[Month]] + duration.[[Months]], dateTime.[[Day]]).
let iso_one = IsoDate::try_balance(
dt.iso_year() + self.date().years as i32,
i32::from(dt.iso_month()) + self.date().months as i32,
i64::from(dt.iso_day()),
)?;
// b. Let isoResult2 be BalanceISODate(dateTime.[[Year]] + duration.[[Years]], dateTime.[[Month]] +
// duration.[[Months]], dateTime.[[Day]] + duration.[[Days]]).
let iso_two = IsoDate::try_balance(
dt.iso_year() + self.date().years as i32,
i32::from(dt.iso_month()) + self.date().months as i32,
i64::from(dt.iso_day()) + self.date().days,
)?;
// c. Let weeksStart be ! CreateTemporalDate(isoResult1.[[Year]], isoResult1.[[Month]], isoResult1.[[Day]],
// calendarRec.[[Receiver]]).
let weeks_start = PlainDate::try_new(
iso_one.year,
iso_one.month,
iso_one.day,
dt.calendar().clone(),
)?;
// d. Let weeksEnd be ! CreateTemporalDate(isoResult2.[[Year]], isoResult2.[[Month]], isoResult2.[[Day]],
// calendarRec.[[Receiver]]).
let weeks_end = PlainDate::try_new(
iso_two.year,
iso_two.month,
iso_two.day,
dt.calendar().clone(),
)?;
// e. Let untilOptions be OrdinaryObjectCreate(null).
// f. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "week").
// g. Let untilResult be ? DifferenceDate(calendarRec, weeksStart, weeksEnd, untilOptions).
let until_result = weeks_start.internal_diff_date(&weeks_end, Unit::Week)?;
// h. Let weeks be RoundNumberToIncrement(duration.[[Weeks]] + untilResult.[[Weeks]], increment, "trunc").
let weeks = IncrementRounder::from_signed_num(
self.date().weeks + until_result.weeks(),
options.increment.as_extended_increment(),
)?
.round(RoundingMode::Trunc);
// i. Let r1 be weeks.
let r1 = weeks;
// j. Let r2 be weeks + increment × sign.
let r2 = weeks
+ i128::from(options.increment.get()) * i128::from(sign.as_sign_multiplier());
// k. Let startDuration be ? CreateNormalizedDurationRecord(duration.[[Years]], duration.[[Months]], r1, 0, ZeroTimeDuration()).
// l. Let endDuration be ? CreateNormalizedDurationRecord(duration.[[Years]], duration.[[Months]], r2, 0, ZeroTimeDuration()).
(
r1,
r2,
DateDuration::new(
self.date().years,
self.date().months,
i64::try_from(r1).map_err(|_| TemporalError::range())?,
0,
)?,
DateDuration::new(
self.date().years,
self.date().months,
i64::try_from(r2).map_err(|_| TemporalError::range())?,
0,
)?,
)
}
Unit::Day => {
// 4. Else,
// a. Assert: unit is "day".
// b. Let days be RoundNumberToIncrement(duration.[[Days]], increment, "trunc").
let days = IncrementRounder::from_signed_num(
self.date().days,
options.increment.as_extended_increment(),
)?
.round(RoundingMode::Trunc);
// c. Let r1 be days.
let r1 = days;
// d. Let r2 be days + increment × sign.
let r2 = days
+ i128::from(options.increment.get()) * i128::from(sign.as_sign_multiplier());
// e. Let startDuration be ? CreateNormalizedDurationRecord(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], r1, ZeroTimeDuration()).
// f. Let endDuration be ? CreateNormalizedDurationRecord(duration.[[Years]], duration.[[Months]], duration.[[Weeks]], r2, ZeroTimeDuration()).
(
r1,
r2,
DateDuration::new(
self.date().years,
self.date().months,
self.date().weeks,
i64::try_from(r1).map_err(|_| TemporalError::range())?,
)?,
DateDuration::new(
self.date().years,
self.date().months,
self.date().weeks,
i64::try_from(r2).map_err(|_| TemporalError::range())?,
)?,
)
}
_ => {
debug_assert!(
false,
"Found unexpected unit {} in NudgeToCalendarUnit",
options.smallest_unit
);
return Err(TemporalError::assert()
.with_message("NudgeCalendarUnit invoked with unexpected unit"));
}
};
// 5. Assert: If sign is 1, r1 ≥ 0 and r1 < r2.
// 6. Assert: If sign is -1, r1 ≤ 0 and r1 > r2.
// n.b. sign == 1 means nonnegative
crate::temporal_assert!(
(sign != NonZeroSign::Negative && r1 >= 0 && r1 < r2)
|| (sign == NonZeroSign::Negative && r1 <= 0 && r1 > r2)
);
let start_epoch_ns = if r1 == 0 {
origin_epoch_ns
} else {
// 7. Let start be ? CalendarDateAdd(calendar, isoDateTime.[[ISODate]], startDuration, constrain).
let start =
dt.calendar()
.date_add(&dt.iso.date, &start_duration, Overflow::Constrain)?;
// 9. Let startDateTime be CombineISODateAndTimeRecord(start, isoDateTime.[[Time]]).
let start_date_time = IsoDateTime::new_unchecked(start.iso, dt.iso.time);
if let Some((time_zone, provider)) = time_zone {
time_zone
.get_epoch_nanoseconds_for(
start_date_time,
Disambiguation::Compatible,
provider,
)?
.ns
} else {
start_date_time.as_nanoseconds()
}
};
// 8. Let end be ? CalendarDateAdd(calendar, isoDateTime.[[ISODate]], endDuration, constrain).
let end = dt
.calendar()
.date_add(&dt.iso.date, &end_duration, Overflow::Constrain)?;
// 10. Let endDateTime be CombineISODateAndTimeRecord(end, isoDateTime.[[Time]]).
let end = IsoDateTime::new_unchecked(end.iso, dt.iso.time);
// 12. Else,
let end_epoch_ns = if let Some((time_zone, provider)) = time_zone {
// a. Let startEpochNs be ? GetEpochNanosecondsFor(timeZone, startDateTime, compatible).
// b. Let endEpochNs be ? GetEpochNanosecondsFor(timeZone, endDateTime, compatible).
time_zone
.get_epoch_nanoseconds_for(end, Disambiguation::Compatible, provider)?
.ns
// 11. If timeZoneRec is unset, then
} else {
// a. Let startEpochNs be GetUTCEpochNanoseconds(start.[[Year]], start.[[Month]], start.[[Day]], start.[[Hour]], start.[[Minute]], start.[[Second]], start.[[Millisecond]], start.[[Microsecond]], start.[[Nanosecond]]).
// b. Let endEpochNs be GetUTCEpochNanoseconds(end.[[Year]], end.[[Month]], end.[[Day]], end.[[Hour]], end.[[Minute]], end.[[Second]], end.[[Millisecond]], end.[[Microsecond]], end.[[Nanosecond]]).
end.as_nanoseconds()
};
Ok(NudgeWindow {
r1,
r2,
start_epoch_ns,
end_epoch_ns,
start_duration,
end_duration,
})
}
fn nudge_calendar_unit_total(
&self,
sign: NonZeroSign,
origin_epoch_ns: EpochNanoseconds,
dest_epoch_ns: i128,
dt: &PlainDateTime,
time_zone: Option<(&TimeZone, &(impl TimeZoneProvider + ?Sized))>, // ???
options: ResolvedRoundingOptions,
) -> TemporalResult<FiniteF64> {
let (nudge_window, _) = self.compute_and_adjust_nudge_window(
sign,
origin_epoch_ns,
dest_epoch_ns,
dt,
time_zone,
options,
)?;
// 7. Let r1 be nudgeWindow.[[R1]].
// 8. Let r2 be nudgeWindow.[[R2]].
// 9. Set startEpochNs to nudgeWindow.[[StartEpochNs]].
// 10. Set endEpochNs to nudgeWindow.[[EndEpochNs]].
// 11. Let startDuration be nudgeWindow.[[StartDuration]].
// 12. Let endDuration be nudgeWindow.[[EndDuration]].
let NudgeWindow {
r1,
start_epoch_ns,
end_epoch_ns,
..
} = nudge_window;
// 13. Assert: startEpochNs ≠ endEpochNs.
temporal_assert!(start_epoch_ns != end_epoch_ns);
// NOTE (nekevss): re: nudge_calendar_unit
//
// We change our calculations here to limit f64 usage, but also to preserve
// precision on the calculation.
//
// So let's go over what we do to handle this ... well, basically,
// just math.
//
// We take `r1 + progress * increment * sign` and plug in the progress calculation
//
// So, in other words, stepping through the calculations
//
// NOTE: For shorthand,
//
// dividend = (destEpochNS - startEpochNS)
// divisor = (endEpochNS - startEpochNS)
//
// progress = dividend / divisor
//
// 1. r1 + progress * increment * sign
// 2. r1 + (dividend / divisor) * increment * sign
//
// Bring in increment and sign
//
// 3. r1 + (dividend * increment * sign) / divisor
//
// Now also move the r1 into the progress fraction.
//
// 4. ((r1 * divisor) + dividend * increment * sign) / divisor
//
// 14. Let progress be (destEpochNs - startEpochNs) / (endEpochNs - startEpochNs).
// 15. Let total be r1 + progress × increment × sign.
let progress_numerator = dest_epoch_ns - start_epoch_ns.0;
let denominator = end_epoch_ns.0 - start_epoch_ns.0;
let total_numerator = (r1 * denominator)
+ progress_numerator
* options.increment.get() as i128
* i128::from(sign.as_sign_multiplier());
Ok(Fraction::new(total_numerator, denominator as f64).to_finite_f64())
}
// TODO: Add assertion into impl.
// TODO: Add unit tests specifically for nudge_calendar_unit if possible.
fn nudge_calendar_unit(
&self,
sign: NonZeroSign,
origin_epoch_ns: EpochNanoseconds,
dest_epoch_ns: i128,
dt: &PlainDateTime,
time_zone: Option<(&TimeZone, &(impl TimeZoneProvider + ?Sized))>, // ???
options: ResolvedRoundingOptions,
) -> TemporalResult<NudgeRecord> {
let (nudge_window, did_expand_calendar_unit) = self.compute_and_adjust_nudge_window(
sign,
origin_epoch_ns,
dest_epoch_ns,
dt,
time_zone,
options,
)?;
// 7. Let r1 be nudgeWindow.[[R1]].
// 8. Let r2 be nudgeWindow.[[R2]].
// 9. Set startEpochNs to nudgeWindow.[[StartEpochNs]].
// 10. Set endEpochNs to nudgeWindow.[[EndEpochNs]].
// 11. Let startDuration be nudgeWindow.[[StartDuration]].
// 12. Let endDuration be nudgeWindow.[[EndDuration]].
let NudgeWindow {
r1,
r2,
start_epoch_ns,
end_epoch_ns,
start_duration,
end_duration,
} = nudge_window;
// 13. Assert: startEpochNs ≠ endEpochNs.
temporal_assert!(start_epoch_ns != end_epoch_ns);
// NOTE (nekevss):
//
// We change our calculations to remove any f64 usage.
//
// So let's go over what we do to handle this ... well, basically,
// just math.
//
// We take `r1 + progress * increment * sign` and plug in the progress calculation
//
// So, in other words, stepping through the calculations
//
// NOTE: For shorthand,
//
// dividend = (destEpochNS - startEpochNS)
// divisor = (endEpochNS - startEpochNS)
//
// progress = dividend / divisor
//
// 1. total = r1 + progress * increment * sign
// 2. total = r1 + (dividend / divisor) * increment * sign
//
// Bring in increment and sign
//
// 3. total = r1 + (dividend * increment * sign) / divisor
//
// Now also move the r1 into the progress fraction.
//
// 4. total = ((r1 * divisor) + dividend * increment * sign) / divisor
//
// 14. Let progress be (destEpochNs - startEpochNs) / (endEpochNs - startEpochNs).
// 15. Let total be r1 + progress × increment × sign.
let dividend = dest_epoch_ns - start_epoch_ns.0;
let divisor = end_epoch_ns.0 - start_epoch_ns.0;
// We add r1 to the dividend
let total_times_divisor = (r1 * divisor)
+ dividend * options.increment.get() as i128 * i128::from(sign.as_sign_multiplier());
// 16. NOTE: The above two steps cannot be implemented directly using floating-point arithmetic.
// This division can be implemented as if constructing Normalized Time Duration Records for the denominator
// and numerator of total and performing one division operation with a floating-point result.
// 17. Assert: 0 ≤ progress ≤ 1.
// 18. If sign < 0, let isNegative be negative; else let isNegative be positive.
// (used implicitly)
// 19. Let unsignedRoundingMode be GetUnsignedRoundingMode(roundingMode, isNegative).
// n.b. get_unsigned_round_mode takes is_positive, but it actually cares about nonnegative
let unsigned_rounding_mode = options
.rounding_mode
.get_unsigned_round_mode(sign != NonZeroSign::Negative);
// NOTE (nekevss):
//
// Now we need to eliminate whether our "total" would be the value of r2
// exactly, AKA `progress = 1`.
//
// To do this, we check if the quotient of dividend and divisor is r2 and
// that there is no remainder caused by the calculation.
//
// 20. If progress = 1, then
let total_is_r2 = total_times_divisor.div_euclid(divisor) == r2
&& total_times_divisor.rem_euclid(divisor) == 0;
let rounded_unit = if total_is_r2 {
// a. Let roundedUnit be abs(r2).
r2.abs()
} else {
// a. Assert: abs(r1) ≤ abs(total) < abs(r2).
// b. Let roundedUnit be ApplyUnsignedRoundingMode(abs(total), abs(r1), abs(r2), unsignedRoundingMode).
// TODO: what happens to r2 here?
unsigned_rounding_mode.apply(
total_times_divisor.unsigned_abs(),
divisor.unsigned_abs(),
r1.abs(),
r2.abs(),
)
};
// 22. If roundedUnit is abs(r2), then
if rounded_unit == r2.abs() {
// a. Let didExpandCalendarUnit be true.
// b. Let resultDuration be endDuration.
// c. Let nudgedEpochNs be endEpochNs.
Ok(NudgeRecord {
normalized: InternalDurationRecord::new(end_duration, TimeDuration::default())?,
nudge_epoch_ns: end_epoch_ns.0,
expanded: true,
})
// 18. Else,
} else {
// b. Let resultDuration be startDuration.
// c. Let nudgedEpochNs be startEpochNs.
Ok(NudgeRecord {
normalized: InternalDurationRecord::new(start_duration, TimeDuration::default())?,
nudge_epoch_ns: start_epoch_ns.0,
expanded: did_expand_calendar_unit,
})
}
}
// Round a duration to a time unit based on a relative `ZonedDateTime`
#[inline]
fn nudge_to_zoned_time(
&self,
sign: NonZeroSign,
dt: &PlainDateTime,
time_zone: &TimeZone,
options: ResolvedRoundingOptions,
provider: &(impl TimeZoneProvider + ?Sized),
) -> TemporalResult<NudgeRecord> {
let d = self.date();
// 1.Let start be ? CalendarDateAdd(calendar, isoDateTime.[[ISODate]], duration.[[Date]], constrain).
let start = dt
.calendar()
.date_add(&dt.iso.date, &d, Overflow::Constrain)?;
// 2. Let startDateTime be CombineISODateAndTimeRecord(start, isoDateTime.[[Time]]).
let start_dt = IsoDateTime::new_unchecked(start.iso, dt.iso.time);
// 3. Let endDate be BalanceISODate(start.[[Year]], start.[[Month]], start.[[Day]] + sign).
let end_date = IsoDate::balance(
start.iso_year(),
start.iso_month().into(),
// Use sign_multiplier here, not sign as i8, since spec wants sign to be nonzero (0 => +1)
start.iso_day() as i32 + i32::from(sign.as_sign_multiplier()),