nish 0.45.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/std/temporal.ts CHANGED
@@ -71,15 +71,27 @@ const TEMPORAL_NS_PER_DAY: i64 = 86400000000000
71
71
  /** The epoch day of +275760-09-13, the last date Temporal can represent. */
72
72
  const TEMPORAL_MAX_EPOCH_DAY: i64 = 100000000
73
73
 
74
+ /** The last instant Temporal represents, in epoch seconds: the start of `TEMPORAL_MAX_EPOCH_DAY`. */
75
+ const TEMPORAL_MAX_EPOCH_SECOND: i64 = 8640000000000
76
+
77
+ /** The negation of `TEMPORAL_MAX_EPOCH_SECOND`. */
78
+ const TEMPORAL_MIN_EPOCH_SECOND: i64 = -8640000000000
79
+
74
80
  /** The epoch day of -271821-04-19, the first date Temporal can represent. */
75
81
  const TEMPORAL_MIN_EPOCH_DAY: i64 = -100000001
76
82
 
77
83
  /** The largest magnitude of a duration's normalized seconds: 2^53 - 1. */
78
84
  const TEMPORAL_MAX_DURATION_SECONDS: i64 = 9007199254740991
79
85
 
86
+ /** The negation of `TEMPORAL_MAX_DURATION_SECONDS`. */
87
+ const TEMPORAL_MIN_DURATION_SECONDS: i64 = -9007199254740991
88
+
80
89
  /** The bound on `years`, `months` and `weeks`: 2^32, exclusive. */
81
90
  const TEMPORAL_MAX_CALENDAR_FIELD: i64 = 4294967296
82
91
 
92
+ /** The negation of `TEMPORAL_MAX_CALENDAR_FIELD`, the bound below. */
93
+ const TEMPORAL_MIN_CALENDAR_FIELD: i64 = -4294967296
94
+
83
95
  /** The units, smallest first, so that "larger" is `>`. */
84
96
  const TEMPORAL_UNIT_NANOSECOND: i32 = 0
85
97
  const TEMPORAL_UNIT_MICROSECOND: i32 = 1
@@ -93,22 +105,97 @@ const TEMPORAL_UNIT_MONTH: i32 = 8
93
105
  const TEMPORAL_UNIT_YEAR: i32 = 9
94
106
 
95
107
  // ---------------------------------------------------------------------------
96
- // Integer helpers. Every division here is written `toI64(a / b)` so that it
97
- // truncates under Node exactly as the native `sdiv` does, and every value that
98
- // is divided stays below 2^53 so that Node's doubles hold it exactly.
108
+ // Integer helpers. Every divisor in this file is a positive constant, so an
109
+ // `i64` division truncates under Node exactly as the native `sdiv` does, and
110
+ // the floor helpers below build on that truncation.
99
111
  // ---------------------------------------------------------------------------
100
112
 
101
- /** `a / b` rounded toward negative infinity, for `b > 0`. */
113
+ /** Panic with Temporal's `RangeError`, naming `what`. */
114
+ const temporalRangeError = (what: string): void => {
115
+ panic(`RangeError: ${what}`)
116
+ }
117
+
118
+ // The checked sums. Each wraps in `u64`, where a sum cannot panic, and then
119
+ // tests the signs: `a + b` overflowed exactly when `a` and `b` share a sign the
120
+ // result lacks, and `a - b` exactly when `a` and `b` differ in sign and the
121
+ // result's sign is not `a`'s. Past the i64 range JavaScript's Temporal throws a
122
+ // `RangeError` long before, so these raise one too.
123
+
124
+ /** `a + b`, raising a `RangeError` where it leaves the i64 range. */
125
+ const temporalAdd = (a: i64, b: i64): i64 => {
126
+ const r: i64 = toI64(toU64(a) + toU64(b))
127
+ if (((a ^ r) & (b ^ r)) < 0) {
128
+ temporalRangeError("the arithmetic leaves the integer range")
129
+ }
130
+ return r
131
+ }
132
+
133
+ /** `a - b`, raising a `RangeError` where it leaves the i64 range. */
134
+ const temporalSub = (a: i64, b: i64): i64 => {
135
+ const r: i64 = toI64(toU64(a) - toU64(b))
136
+ if (((a ^ b) & (a ^ r)) < 0) {
137
+ temporalRangeError("the arithmetic leaves the integer range")
138
+ }
139
+ return r
140
+ }
141
+
142
+ /**
143
+ * A `Duration` field negated. The constructor refuses the least `i64` in every
144
+ * field (its bounds, or for microseconds and nanoseconds, a test of its own),
145
+ * so the wrapping negation is exact.
146
+ */
147
+ const temporalNegField = (x: i64): i64 => toI64(0 - toU64(x))
148
+
149
+ /** The magnitude of a `Duration` field `x` whose sign is negative when `negative`. */
150
+ const temporalMagnitude = (x: i64, negative: boolean): i64 => (negative ? temporalNegField(x) : x)
151
+
152
+ /** `x` negated when `negative`, raising a `RangeError` where that leaves the i64 range. */
153
+ const temporalSigned = (x: i64, negative: boolean): i64 => (negative ? temporalSub(0, x) : x)
154
+
155
+ /** `a * k` for a factor `k` of at least 1, raising a `RangeError` where it leaves the i64 range. */
156
+ const temporalMul = (a: i64, k: i64): i64 => {
157
+ const r: i64 = toI64(toU64(a) * toU64(k))
158
+ if (k < 1 || r / k !== a) {
159
+ temporalRangeError("the arithmetic leaves the integer range")
160
+ }
161
+ return r
162
+ }
163
+
164
+ // The divisions. Every divisor here is a constant from 2 to a day's
165
+ // nanoseconds, so the test that opens each is never true; it is what lets the
166
+ // compiler prove the quotient and the remainder cannot overflow.
167
+
168
+ /** The largest divisor any caller passes: the nanoseconds in a day. */
169
+ const TEMPORAL_MAX_DIVISOR: i64 = 86400000000000
170
+
171
+ /** `a / b` rounded toward negative infinity, for `2 <= b <= TEMPORAL_MAX_DIVISOR`. */
102
172
  const temporalFloorDiv = (a: i64, b: i64): i64 => {
103
- const q: i64 = toI64(a / b)
104
- return q * b > a ? q - 1 : q
173
+ if (b < 2 || b > TEMPORAL_MAX_DIVISOR) {
174
+ temporalRangeError("a divisor outside 2 to a day's nanoseconds")
175
+ return 0
176
+ }
177
+ const q: i64 = a / b
178
+ return a % b < 0 ? temporalSub(q, 1) : q
105
179
  }
106
180
 
107
- /** `a` modulo `b` in `[0, b)`, for `b > 0`. */
108
- const temporalFloorMod = (a: i64, b: i64): i64 => a - temporalFloorDiv(a, b) * b
181
+ /** `a` modulo `b` in `[0, b)`, for `2 <= b <= TEMPORAL_MAX_DIVISOR`. */
182
+ const temporalFloorMod = (a: i64, b: i64): i64 => {
183
+ if (b < 2 || b > TEMPORAL_MAX_DIVISOR) {
184
+ temporalRangeError("a divisor outside 2 to a day's nanoseconds")
185
+ return 0
186
+ }
187
+ const r: i64 = a % b
188
+ return r < 0 ? r + b : r
189
+ }
109
190
 
110
- /** `a / b` rounded toward zero, for `b > 0`. */
111
- const temporalTruncDiv = (a: i64, b: i64): i64 => toI64(a / b)
191
+ /** `a / b` rounded toward zero, for `2 <= b <= TEMPORAL_MAX_DIVISOR`. */
192
+ const temporalTruncDiv = (a: i64, b: i64): i64 => {
193
+ if (b < 2 || b > TEMPORAL_MAX_DIVISOR) {
194
+ temporalRangeError("a divisor outside 2 to a day's nanoseconds")
195
+ return 0
196
+ }
197
+ return a / b
198
+ }
112
199
 
113
200
  /** -1, 0 or 1 as `a` is negative, zero or positive. */
114
201
  const temporalSign = (a: i64): i32 => {
@@ -126,6 +213,15 @@ const temporalSign = (a: i64): i32 => {
126
213
  /** The most bytes any `toString` here writes: a `Duration` of ten 19-digit fields. */
127
214
  const TEMPORAL_TEXT_MAX: i32 = 256
128
215
 
216
+ /**
217
+ * The text of `out` up to `end`, the index the last writer answered. Each
218
+ * `toString` sizes `out` at `TEMPORAL_TEXT_MAX`, which holds its longest text,
219
+ * so `end` stays inside `out`; the slice still keeps its bounds check, since
220
+ * the prover does not carry a writer's answer back to its caller (#2208), and
221
+ * this is the one slice site every `toString` here shares.
222
+ */
223
+ const temporalText = (out: u8[], end: i32): string => String.fromBytes(out, 0, end)
224
+
129
225
  /** Write the ASCII byte `c` at `at`. */
130
226
  const temporalPutByte = (out: u8[], at: i32, c: i32): i32 => {
131
227
  if (at < 0 || at >= toI32(out.length)) {
@@ -135,44 +231,47 @@ const temporalPutByte = (out: u8[], at: i32, c: i32): i32 => {
135
231
  return at + 1
136
232
  }
137
233
 
138
- /** Write `n`, which is not negative, in decimal, zero-padded to at least `width` digits. */
139
- const temporalPutNumber = (out: u8[], at: i32, n: i64, width: i32): i32 => {
234
+ /** Write `n`, which is not negative, in decimal; when the digits would run past `out`, none are written. */
235
+ const temporalPutNumber = (out: u8[], at: i32, n: i64): i32 => {
140
236
  let count: i32 = 1
141
237
  let rest: i64 = n
142
- while (rest >= 10) {
143
- rest = toI64(rest / 10)
238
+ // An i64 has at most nineteen digits.
239
+ while (rest >= 10 && count < 19) {
240
+ rest = rest / 10
144
241
  count = count + 1
145
242
  }
146
- if (count < width) {
147
- count = width
148
- }
243
+ // Two `i32`s summed in `i64` cannot overflow.
244
+ const end: i64 = toI64(at) + toI64(count)
149
245
  let v: i64 = n
150
- for (let i: i32 = count - 1; i >= 0; i--) {
151
- out[at + i] = toU8(48 + toI32(v % 10))
152
- v = toI64(v / 10)
246
+ for (let k: i32 = toI32(toI64(at) + toI64(count) - 1); k >= at && k >= 0 && k < toI32(out.length); k--) {
247
+ out[k] = toU8(48) + toU8(v % 10)
248
+ v = v / 10
153
249
  }
154
- return at + count
250
+ return toI32(end)
155
251
  }
156
252
 
157
253
  // The fixed-width writers: a date or a time is always the same digits, so
158
254
  // they are written two at a time, with one bounds test that covers both, and
159
- // no count of digits first. `n / 10` of an `i32` is a multiply and a shift.
255
+ // no count of digits first. `n / 10` of an `i32` is a multiply and a shift,
256
+ // and each digit is a `u8` sum, which wraps rather than checks.
160
257
 
161
258
  /** Write `n`, 0 to 99, as two digits. */
162
259
  const temporalPut2 = (out: u8[], at: i32, n: i32): i32 => {
163
260
  if (at < 0 || at > toI32(out.length) - 2) {
164
261
  return at
165
262
  }
166
- const tens: i32 = toI32(n / 10)
263
+ const u: u32 = toU32(n)
264
+ const tens: u32 = u / 10
167
265
  out[at] = toU8(48 + tens)
168
- out[at + 1] = toU8(48 + n - tens * 10)
266
+ out[at + 1] = toU8(48 + u - tens * 10)
169
267
  return at + 2
170
268
  }
171
269
 
172
270
  /** Write `n`, 0 to 9999, as four digits. */
173
271
  const temporalPut4 = (out: u8[], at: i32, n: i32): i32 => {
174
- const high: i32 = toI32(n / 100)
175
- return temporalPut2(out, temporalPut2(out, at, high), n - high * 100)
272
+ const u: u32 = toU32(n)
273
+ const high: u32 = u / 100
274
+ return temporalPut2(out, temporalPut2(out, at, toI32(high)), toI32(u - high * 100))
176
275
  }
177
276
 
178
277
  /** Write a year as Temporal does: four digits for 0 to 9999, otherwise a sign and six digits. */
@@ -180,10 +279,10 @@ const temporalPutYear = (out: u8[], at: i32, year: i32): i32 => {
180
279
  if (year >= 0 && year <= 9999) {
181
280
  return temporalPut4(out, at, year)
182
281
  }
183
- const magnitude: i32 = year < 0 ? -year : year
184
- const high: i32 = toI32(magnitude / 10000)
282
+ // The negation wraps in `u32`, so it holds even for the least `i32`.
283
+ const magnitude: u32 = year < 0 ? toU32(0) - toU32(year) : toU32(year)
185
284
  const signed: i32 = temporalPutByte(out, at, year < 0 ? 45 : 43)
186
- return temporalPut4(out, temporalPut2(out, signed, high), magnitude - high * 10000)
285
+ return temporalPut4(out, temporalPut2(out, signed, toI32(magnitude / 10000)), toI32(magnitude % 10000))
187
286
  }
188
287
 
189
288
  /**
@@ -191,13 +290,13 @@ const temporalPutYear = (out: u8[], at: i32, year: i32): i32 => {
191
290
  * two-digit groups are lanes of a `u16x8`, each lane's tens are
192
291
  * `(v * 103) >> 10` (exact below 100), one shuffle interleaves the tens and
193
292
  * ones bytes with a zero byte where each `-` goes, and adding a template of
194
- * `0` and `-` makes the text. `out` must have 16 bytes from `at`.
293
+ * `0` and `-` makes the text. `out` must have 16 bytes from `at`; the store's
294
+ * test is never false for a caller here.
195
295
  */
196
296
  const temporalPutDate4 = (out: u8[], at: i32, year: i32, month: i32, day: i32): i32 => {
197
- const century: i32 = toI32(year / 100)
198
297
  const v: u16x8 = u16x8(
199
- toU16(century),
200
- toU16(year - century * 100),
298
+ toU16(year / 100),
299
+ toU16(year % 100),
201
300
  toU16(month),
202
301
  toU16(day),
203
302
  toU16(0),
@@ -246,8 +345,14 @@ const temporalPutDate4 = (out: u8[], at: i32, year: i32, month: i32, day: i32):
246
345
  toU8(0),
247
346
  toU8(0)
248
347
  )
249
- store(addWrapping(digits, template), out, at)
250
- return at + 10
348
+ // The text is built before the test: a call between the test and the store
349
+ // would leave the prover without the test's bound.
350
+ const text: u8x16 = addWrapping(digits, template)
351
+ if (at >= 0 && at <= toI32(out.length) - 16) {
352
+ store(text, out, at)
353
+ return at + 10
354
+ }
355
+ return at
251
356
  }
252
357
 
253
358
  /**
@@ -255,7 +360,8 @@ const temporalPutDate4 = (out: u8[], at: i32, year: i32, month: i32, day: i32):
255
360
  * as `temporalPutDate4` writes a date: seven two-digit groups in one `u16x8`,
256
361
  * the first sixteen bytes of text from one shuffle and the last three from a
257
362
  * second. `out` must have 32 bytes from `at`; the bytes past the nineteenth
258
- * are zeros for the caller to write over.
363
+ * are zeros for the caller to write over. The test that opens it is never
364
+ * true for a caller here, whose buffer is `TEMPORAL_TEXT_MAX` bytes.
259
365
  */
260
366
  const temporalPutDateTime4 = (
261
367
  out: u8[],
@@ -267,10 +373,9 @@ const temporalPutDateTime4 = (
267
373
  minute: i32,
268
374
  second: i32
269
375
  ): i32 => {
270
- const century: i32 = toI32(year / 100)
271
376
  const v: u16x8 = u16x8(
272
- toU16(century),
273
- toU16(year - century * 100),
377
+ toU16(year / 100),
378
+ toU16(year % 100),
274
379
  toU16(month),
275
380
  toU16(day),
276
381
  toU16(hour),
@@ -321,6 +426,9 @@ const temporalPutDateTime4 = (
321
426
  toU8(0),
322
427
  toU8(0)
323
428
  )
429
+ if (at < 0 || at > toI32(out.length) - 32) {
430
+ return at
431
+ }
324
432
  store(addWrapping(head, headText), out, at)
325
433
  store(addWrapping(tail, tailText), out, at + 16)
326
434
  return at + 19
@@ -343,15 +451,16 @@ const temporalPutFraction = (out: u8[], at: i32, ns: i32): i32 => {
343
451
  if (ns === 0) {
344
452
  return at
345
453
  }
346
- const head: i32 = toI32(ns / 100000000)
347
- const rest: i32 = ns - head * 100000000
348
- const middle: i32 = toI32(rest / 10000)
349
- let end: i32 = temporalPutByte(out, temporalPutByte(out, at, 46), 48 + head)
350
- end = temporalPut4(out, temporalPut4(out, end, middle), rest - middle * 10000)
351
- while (end > at + 2 && end <= toI32(out.length) && out[end - 1] === 48) {
352
- end = end - 1
454
+ const rest: i32 = ns % 100000000
455
+ let end: i32 = temporalPutByte(out, temporalPutByte(out, at, 46), 48 + toI32(ns / 100000000))
456
+ end = temporalPut4(out, temporalPut4(out, end, toI32(rest / 10000)), rest % 10000)
457
+ // Give back the zeros after the first digit, `last` the byte before `end`.
458
+ const first: i64 = toI64(at) + 1
459
+ let last: i32 = toI32(toI64(end) - 1)
460
+ while (toI64(last) > first && last >= 0 && last < toI32(out.length) && out[last] === 48) {
461
+ last = last - 1
353
462
  }
354
- return end
463
+ return toI32(toI64(last) + 1)
355
464
  }
356
465
 
357
466
  /** Write `HH:MM:SS` and the fraction of the second. */
@@ -371,19 +480,14 @@ const temporalPutNanoOfDay = (out: u8[], at: i32, ns: i64): i32 => {
371
480
  at,
372
481
  toI32(minutes / 60),
373
482
  minutes % 60,
374
- secs - minutes * 60,
483
+ secs % 60,
375
484
  toI32(ns % TEMPORAL_NS_PER_SECOND)
376
485
  )
377
486
  }
378
487
 
379
488
  /** Write `n` and the designator `c`, as a duration field is written. */
380
489
  const temporalPutField = (out: u8[], at: i32, n: i64, c: i32): i32 =>
381
- temporalPutByte(out, temporalPutNumber(out, at, n, 1), c)
382
-
383
- /** Panic with Temporal's `RangeError`, naming `what`. */
384
- const temporalRangeError = (what: string): void => {
385
- panic(`RangeError: ${what}`)
386
- }
490
+ temporalPutByte(out, temporalPutNumber(out, at, n), c)
387
491
 
388
492
  // ---------------------------------------------------------------------------
389
493
  // The proleptic Gregorian calendar (Hinnant, "chrono-Compatible Low-Level Date
@@ -441,46 +545,88 @@ const temporalMonthCode = (month: i32): string => {
441
545
  }
442
546
  }
443
547
 
444
- /** The days from 1970-01-01 to the given date, negative before it. */
445
- const temporalEpochDay = (year: i64, month: i32, day: i32): i64 => {
446
- const y: i64 = month <= 2 ? year - 1 : year
447
- const era: i64 = temporalFloorDiv(y, 400)
448
- const yoe: i64 = y - era * 400
449
- const mp: i64 = toI64(month > 2 ? month - 3 : month + 9)
450
- const doy: i64 = temporalTruncDiv(153 * mp + 2, 5) + toI64(day) - 1
451
- const doe: i64 = yoe * 365 + temporalTruncDiv(yoe, 4) - temporalTruncDiv(yoe, 100) + doy
452
- return era * 146097 + doe - 719468
548
+ /** Whether `year` is inside Temporal's range of -271821 to 275760. */
549
+ const temporalYearInRange = (year: i32): boolean => year >= -271821 && year <= 275760
550
+
551
+ /**
552
+ * The days from 1970-01-01 to the given date, negative before it. Every
553
+ * caller has checked the date, its year with `temporalYearInRange` or a
554
+ * four-digit read, so the test is never true for one here; it is
555
+ * what bounds each term below. The years count from 1 March of the year
556
+ * 400,000 years before 0, a whole number of 400-year eras, so every term is
557
+ * nonnegative and the divisions need no floor.
558
+ */
559
+ const temporalEpochDay = (year: i32, month: i32, day: i32): i64 => {
560
+ const shifted: i64 = toI64(year) + 399999
561
+ if (shifted < 0 || shifted > 799999 || month < 1 || month > 12 || day < 1 || day > 31) {
562
+ temporalRangeError("PlainDate: the fields are not a date")
563
+ return 0
564
+ }
565
+ const m9: i64 = toI64(month) + 9
566
+ const y: i64 = shifted + m9 / 12
567
+ const yoe: i64 = y % 400
568
+ const doy: i64 = (toI64(153) * (m9 % 12) + 2) / 5 + toI64(day) - 1
569
+ // 146,816,468 is the 1,000 eras' 146,097,000 days plus the 719,468 from
570
+ // 0000-03-01 to 1970-01-01.
571
+ return (y / 400) * 146097 + yoe * 365 + yoe / 4 + doy - yoe / 100 - 146816468
453
572
  }
454
573
 
455
574
  /** The days from 1 January to the given date, plus one, in a year that is a leap year when `leap`. */
456
575
  const temporalDayOfYear = (month: i32, day: i32, leap: boolean): i32 => {
457
576
  const before: i32 = month >= 1 && month <= 12 ? TEMPORAL_DAYS_BEFORE_MONTH[month - 1] : 0
458
- return before + day + (leap && month > 2 ? 1 : 0)
577
+ // A checked day is below 32, so the `u32` sum is exact.
578
+ return toI32(toU32(before) + toU32(day) + (leap && month > 2 ? 1 : 0))
459
579
  }
460
580
 
461
- /** The ISO weekday of an epoch day: 1 for Monday to 7 for Sunday. */
462
- const temporalDayOfWeek = (epochDay: i64): i32 => toI32(temporalFloorMod(epochDay + 3, 7)) + 1
581
+ /**
582
+ * The ISO weekday of an epoch day in Temporal's range: 1 for Monday to 7 for
583
+ * Sunday. The day counts from 1,000 eras before 0000-03-01, a nonnegative `u64`
584
+ * there, and 146,816,470 days is 3 more than a whole number of weeks, which
585
+ * puts 1970-01-01, a Thursday, on 4.
586
+ */
587
+ const temporalDayOfWeek = (epochDay: i64): i32 => toI32(((toU64(epochDay) + 146816470) % 7) + 1)
463
588
 
464
589
  /** How many ISO weeks `year` has: 53 when it starts on a Thursday, or is a leap year starting on a Wednesday. */
465
- const temporalWeeksInYear = (year: i64): i32 =>
466
- temporalWeekdayOfDecember31(year) === 4 || temporalWeekdayOfDecember31(year - 1) === 3 ? 53 : 52
590
+ const temporalWeeksInYear = (year: i32): i32 =>
591
+ temporalWeekdayOfDecember31(toI64(year)) === 4 || temporalWeekdayOfDecember31(toI64(year) - 1) === 3
592
+ ? 53
593
+ : 52
467
594
 
468
- /** The weekday of 31 December of `year`, 0 for Sunday to 6 for Saturday. */
469
- const temporalWeekdayOfDecember31 = (y: i64): i64 =>
470
- temporalFloorMod(y + temporalFloorDiv(y, 4) - temporalFloorDiv(y, 100) + temporalFloorDiv(y, 400), 7)
595
+ /**
596
+ * The weekday of 31 December of `y`, a year in Temporal's range, 0 for Sunday
597
+ * to 6 for Saturday. The year counts from 400,000 years before 0, a
598
+ * nonnegative `u64` there; the shift adds 497,000 days, a whole number of
599
+ * weeks, so the weekday is unchanged.
600
+ */
601
+ const temporalWeekdayOfDecember31 = (y: i64): i64 => {
602
+ const ys: u64 = toU64(y) + 400000
603
+ return toI64((ys + ys / 4 - ys / 100 + ys / 400) % 7)
604
+ }
471
605
 
472
606
  /** Panic unless `year`, `month` and `day` name a real date. */
473
607
  const temporalCheckDate = (what: string, year: i64, month: i64, day: i64): void => {
608
+ const problem: string = temporalDateProblem(what, year, month, day)
609
+ if (problem.length > 0) {
610
+ temporalRangeError(problem)
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Why the fields name no date `temporalCheckDate` accepts, as its
616
+ * `RangeError` words it, or `""` when they name one.
617
+ */
618
+ const temporalDateProblem = (what: string, year: i64, month: i64, day: i64): string => {
474
619
  if (year < -271821 || year > 275760) {
475
- temporalRangeError(`${what}: year ${year} is outside -271821 to 275760`)
620
+ return `${what}: year ${year} is outside -271821 to 275760`
476
621
  }
477
622
  if (month < 1 || month > 12) {
478
- temporalRangeError(`${what}: month ${month} is outside 1 to 12`)
623
+ return `${what}: month ${month} is outside 1 to 12`
479
624
  }
480
625
  const most: i32 = temporalDaysInMonth(year, toI32(month))
481
626
  if (day < 1 || day > toI64(most)) {
482
- temporalRangeError(`${what}: day ${day} is outside 1 to ${most}`)
627
+ return `${what}: day ${day} is outside 1 to ${most}`
483
628
  }
629
+ return ""
484
630
  }
485
631
 
486
632
  /** Panic unless the fields name a time of day. */
@@ -513,7 +659,11 @@ const temporalCheckTime = (
513
659
  }
514
660
  }
515
661
 
516
- /** The nanoseconds since midnight of a time of day whose fields are in range. */
662
+ /**
663
+ * The nanoseconds since midnight of a time of day. Every caller has checked
664
+ * the fields, so the test is never true for one here; it is what bounds the
665
+ * sum.
666
+ */
517
667
  const temporalNanoOfDay = (
518
668
  hour: i32,
519
669
  minute: i32,
@@ -521,11 +671,31 @@ const temporalNanoOfDay = (
521
671
  millisecond: i32,
522
672
  microsecond: i32,
523
673
  nanosecond: i32
524
- ): i64 =>
525
- (toI64(hour) * 3600 + toI64(minute) * 60 + toI64(second)) * TEMPORAL_NS_PER_SECOND +
526
- toI64(millisecond) * 1000000 +
527
- toI64(microsecond) * 1000 +
528
- toI64(nanosecond)
674
+ ): i64 => {
675
+ if (
676
+ hour < 0 ||
677
+ hour > 23 ||
678
+ minute < 0 ||
679
+ minute > 59 ||
680
+ second < 0 ||
681
+ second > 59 ||
682
+ millisecond < 0 ||
683
+ millisecond > 999 ||
684
+ microsecond < 0 ||
685
+ microsecond > 999 ||
686
+ nanosecond < 0 ||
687
+ nanosecond > 999
688
+ ) {
689
+ temporalRangeError("PlainTime: a field is outside its range")
690
+ return 0
691
+ }
692
+ return (
693
+ (toI64(hour) * 3600 + toI64(minute) * 60 + toI64(second)) * TEMPORAL_NS_PER_SECOND +
694
+ toI64(millisecond) * 1000000 +
695
+ toI64(microsecond) * 1000 +
696
+ toI64(nanosecond)
697
+ )
698
+ }
529
699
 
530
700
  /** A date on an epoch day, after checking the day is inside Temporal's range. */
531
701
  const temporalDateOfEpochDay = (epochDay: i64): PlainDate => {
@@ -540,26 +710,29 @@ const temporalDateOfEpochDay = (epochDay: i64): PlainDate => {
540
710
  * The year, month and day of an epoch day, packed into one integer so that
541
711
  * nothing is allocated: `(year + 400000) * 512 + month * 32 + day`, which
542
712
  * stays below 2^31 over Temporal's whole range. `temporalCivilYear`,
543
- * `temporalCivilMonth` and `temporalCivilDay` take it apart.
713
+ * `temporalCivilMonth` and `temporalCivilDay` take it apart. Every caller has
714
+ * checked the day is in that range, so the test is never true for one here.
715
+ * The days count from 0000-03-01 less 1,000 eras of 400 years, so every term
716
+ * is a nonnegative `u64` below 2^28 and the arithmetic is exact.
544
717
  */
545
718
  const temporalCivilOfEpochDay = (epochDay: i64): i64 => {
546
- const z: i64 = epochDay + 719468
547
- const era: i64 = temporalFloorDiv(z, 146097)
548
- const doe: i64 = z - era * 146097
549
- const yoe: i64 = temporalTruncDiv(
550
- doe - temporalTruncDiv(doe, 1460) + temporalTruncDiv(doe, 36524) - temporalTruncDiv(doe, 146096),
551
- 365
552
- )
553
- const doy: i64 = doe - (365 * yoe + temporalTruncDiv(yoe, 4) - temporalTruncDiv(yoe, 100))
554
- const mp: i64 = temporalTruncDiv(5 * doy + 2, 153)
555
- const day: i64 = doy - temporalTruncDiv(153 * mp + 2, 5) + 1
556
- const month: i64 = mp < 10 ? mp + 3 : mp - 9
557
- const year: i64 = yoe + era * 400 + (month <= 2 ? 1 : 0)
558
- return (year + 400000) * 512 + month * 32 + day
719
+ const z: u64 = toU64(epochDay) + 146816468
720
+ if (z < 46816467 || z > 246816468) {
721
+ temporalRangeError("PlainDate: the date is outside Temporal's range")
722
+ return 0
723
+ }
724
+ const doe: u64 = z % 146097
725
+ const yoe: u64 = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
726
+ const doy: u64 = doe - (yoe * 365 + yoe / 4 - yoe / 100)
727
+ const mp: u64 = (doy * 5 + 2) / 153
728
+ const day: u64 = doy + 1 - (mp * 153 + 2) / 5
729
+ const month: u64 = mp < 10 ? mp + 3 : mp - 9
730
+ const year: u64 = (z / 146097) * 400 + yoe + (month <= 2 ? 1 : 0)
731
+ return toI64(year * 512 + month * 32 + day)
559
732
  }
560
733
 
561
- /** The year of a packed civil date. */
562
- const temporalCivilYear = (civil: i64): i32 => toI32(toI64(civil / 512) - 400000)
734
+ /** The year of a packed civil date: the packed year less 400,000, which `u32` holds and `i32` reads back exactly. */
735
+ const temporalCivilYear = (civil: i64): i32 => toI32(toU32(toI64(civil / 512)) - 400000)
563
736
 
564
737
  /** The month of a packed civil date. */
565
738
  const temporalCivilMonth = (civil: i64): i32 => toI32(toI64(civil / 32) % 16)
@@ -601,7 +774,7 @@ class TemporalSpan {
601
774
  * @param nanos nanoseconds to add, of any sign and size below 2^53
602
775
  */
603
776
  constructor(seconds: i64, nanos: i64) {
604
- this.seconds = seconds + temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND)
777
+ this.seconds = temporalAdd(seconds, temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND))
605
778
  this.nanos = toI32(temporalFloorMod(nanos, TEMPORAL_NS_PER_SECOND))
606
779
  }
607
780
 
@@ -612,7 +785,7 @@ class TemporalSpan {
612
785
  * @returns the sum
613
786
  */
614
787
  plus(other: TemporalSpan): TemporalSpan {
615
- return new TemporalSpan(this.seconds + other.seconds, toI64(this.nanos) + toI64(other.nanos))
788
+ return new TemporalSpan(temporalAdd(this.seconds, other.seconds), toI64(this.nanos) + toI64(other.nanos))
616
789
  }
617
790
 
618
791
  /**
@@ -621,7 +794,7 @@ class TemporalSpan {
621
794
  * @returns the span of the same length in the other direction
622
795
  */
623
796
  negated(): TemporalSpan {
624
- return new TemporalSpan(-this.seconds, -toI64(this.nanos))
797
+ return new TemporalSpan(temporalSub(0, this.seconds), -toI64(this.nanos))
625
798
  }
626
799
 
627
800
  /**
@@ -646,7 +819,7 @@ class TemporalSpan {
646
819
  return temporalFloorDiv(this.seconds, TEMPORAL_SECONDS_PER_DAY)
647
820
  }
648
821
  const magnitude: TemporalSpan = this.negated()
649
- return -temporalFloorDiv(magnitude.seconds, TEMPORAL_SECONDS_PER_DAY)
822
+ return temporalSub(0, temporalFloorDiv(magnitude.seconds, TEMPORAL_SECONDS_PER_DAY))
650
823
  }
651
824
  }
652
825
 
@@ -661,35 +834,39 @@ const temporalSpanOfDuration = (d: Duration, withDays: boolean): TemporalSpan =>
661
834
  * below 2^53 for every valid duration.
662
835
  */
663
836
  const temporalDurationSeconds = (d: Duration, withDays: boolean): i64 => {
664
- let seconds: i64 = d.hours * 3600 + d.minutes * 60 + d.seconds
837
+ let seconds: i64 = temporalAdd(
838
+ temporalAdd(temporalMul(d.hours, 3600), temporalMul(d.minutes, 60)),
839
+ d.seconds
840
+ )
665
841
  if (withDays) {
666
- seconds = seconds + d.days * TEMPORAL_SECONDS_PER_DAY
842
+ seconds = temporalAdd(seconds, temporalMul(d.days, TEMPORAL_SECONDS_PER_DAY))
667
843
  }
668
844
  if (d.milliseconds !== 0) {
669
- seconds = seconds + temporalFloorDiv(d.milliseconds, 1000)
845
+ seconds = temporalAdd(seconds, temporalFloorDiv(d.milliseconds, 1000))
670
846
  }
671
847
  if (d.microseconds !== 0) {
672
- seconds = seconds + temporalFloorDiv(d.microseconds, 1000000)
848
+ seconds = temporalAdd(seconds, temporalFloorDiv(d.microseconds, 1000000))
673
849
  }
674
850
  if (d.nanoseconds !== 0) {
675
- seconds = seconds + temporalFloorDiv(d.nanoseconds, TEMPORAL_NS_PER_SECOND)
851
+ seconds = temporalAdd(seconds, temporalFloorDiv(d.nanoseconds, TEMPORAL_NS_PER_SECOND))
676
852
  }
677
853
  return seconds
678
854
  }
679
855
 
680
856
  /** The nanoseconds `temporalDurationSeconds` leaves out, each field's in `[0, 10^9)`, so below 3 × 10^9. */
681
857
  const temporalDurationNanos = (d: Duration): i64 => {
682
- let nanos: i64 = 0
858
+ // Each remainder is below 10^9, so the `u64` sum is exact.
859
+ let nanos: u64 = 0
683
860
  if (d.milliseconds !== 0) {
684
- nanos = temporalFloorMod(d.milliseconds, 1000) * 1000000
861
+ nanos = toU64(temporalFloorMod(d.milliseconds, 1000)) * 1000000
685
862
  }
686
863
  if (d.microseconds !== 0) {
687
- nanos = nanos + temporalFloorMod(d.microseconds, 1000000) * 1000
864
+ nanos = nanos + toU64(temporalFloorMod(d.microseconds, 1000000)) * 1000
688
865
  }
689
866
  if (d.nanoseconds !== 0) {
690
- nanos = nanos + temporalFloorMod(d.nanoseconds, TEMPORAL_NS_PER_SECOND)
867
+ nanos = nanos + toU64(temporalFloorMod(d.nanoseconds, TEMPORAL_NS_PER_SECOND))
691
868
  }
692
- return nanos
869
+ return toI64(nanos)
693
870
  }
694
871
 
695
872
  /** Whether every time field of `d`, hours to nanoseconds, is zero. */
@@ -704,10 +881,11 @@ const temporalNoTime = (d: Duration): boolean =>
704
881
  /**
705
882
  * The epoch day `(year, month, day)` lands on after `years` and `months`,
706
883
  * with the day constrained to the new month, then `days` more; `epochDay` is
707
- * where it starts, used as it is when there are no years or months. Panics
708
- * with a `RangeError` outside Temporal's range.
884
+ * where it starts, used as it is when there are no years or months. A year
885
+ * outside Temporal's range answers the day after `TEMPORAL_MAX_EPOCH_DAY`, so
886
+ * the caller's one range test refuses every answer that is not a date.
709
887
  */
710
- const temporalAddToDate = (
888
+ const temporalMovedEpochDay = (
711
889
  year0: i32,
712
890
  month0: i32,
713
891
  day0: i32,
@@ -718,17 +896,30 @@ const temporalAddToDate = (
718
896
  ): i64 => {
719
897
  let start: i64 = epochDay
720
898
  if (years !== 0 || months !== 0) {
721
- let year: i64 = toI64(year0) + years
722
- let month: i64 = toI64(month0) + months
723
- year = year + temporalFloorDiv(month - 1, 12)
724
- month = temporalFloorMod(month - 1, 12) + 1
899
+ const month1: i64 = temporalSub(temporalAdd(toI64(month0), months), 1)
900
+ const year: i64 = temporalAdd(temporalAdd(toI64(year0), years), temporalFloorDiv(month1, 12))
901
+ // The remainder is in [0, 12), so the `u64` sum is exact.
902
+ const month: i64 = toI64(toU64(temporalFloorMod(month1, 12)) + 1)
725
903
  if (year < -271821 || year > 275760) {
726
- temporalRangeError("PlainDate: the date is outside Temporal's range")
904
+ return TEMPORAL_MAX_EPOCH_DAY + 1
727
905
  }
728
906
  const most: i32 = temporalDaysInMonth(year, toI32(month))
729
- start = temporalEpochDay(year, toI32(month), day0 > most ? most : day0)
907
+ start = temporalEpochDay(toI32(year), toI32(month), day0 > most ? most : day0)
730
908
  }
731
- const result: i64 = start + days
909
+ return temporalAdd(start, days)
910
+ }
911
+
912
+ /** `temporalMovedEpochDay`, panicking with a `RangeError` outside Temporal's range. */
913
+ const temporalAddToDate = (
914
+ year0: i32,
915
+ month0: i32,
916
+ day0: i32,
917
+ epochDay: i64,
918
+ years: i64,
919
+ months: i64,
920
+ days: i64
921
+ ): i64 => {
922
+ const result: i64 = temporalMovedEpochDay(year0, month0, day0, epochDay, years, months, days)
732
923
  if (result < TEMPORAL_MIN_EPOCH_DAY || result > TEMPORAL_MAX_EPOCH_DAY) {
733
924
  temporalRangeError("PlainDate: the date is outside Temporal's range")
734
925
  }
@@ -777,18 +968,32 @@ const temporalBalance = (span: TemporalSpan, largest: i32): Duration => {
777
968
  temporalRangeError("Duration: the length does not fit this module's i64 fields in that unit")
778
969
  }
779
970
  if (largest === TEMPORAL_UNIT_MILLISECOND) {
780
- ms = s * 1000 + ms
971
+ ms = temporalAdd(temporalMul(s, 1000), ms)
781
972
  } else if (largest === TEMPORAL_UNIT_MICROSECOND) {
782
- us = s * 1000000 + ms * 1000 + us
973
+ us = temporalAdd(temporalAdd(temporalMul(s, 1000000), temporalMul(ms, 1000)), us)
783
974
  ms = 0
784
975
  } else {
785
- ns = s * 1000000000 + ms * 1000000 + us * 1000 + ns
976
+ ns = temporalAdd(
977
+ temporalAdd(temporalAdd(temporalMul(s, 1000000000), temporalMul(ms, 1000000)), temporalMul(us, 1000)),
978
+ ns
979
+ )
786
980
  ms = 0
787
981
  us = 0
788
982
  }
789
983
  }
790
- const k: i64 = toI64(sign < 0 ? -1 : 1)
791
- return new Duration(0, 0, 0, days * k, hours * k, minutes * k, seconds * k, ms * k, us * k, ns * k)
984
+ const neg: boolean = sign < 0
985
+ return new Duration(
986
+ 0,
987
+ 0,
988
+ 0,
989
+ temporalSigned(days, neg),
990
+ temporalSigned(hours, neg),
991
+ temporalSigned(minutes, neg),
992
+ temporalSigned(seconds, neg),
993
+ temporalSigned(ms, neg),
994
+ temporalSigned(us, neg),
995
+ temporalSigned(ns, neg)
996
+ )
792
997
  }
793
998
 
794
999
  // ---------------------------------------------------------------------------
@@ -858,21 +1063,35 @@ class TemporalReader {
858
1063
  /**
859
1064
  * The character code at `at + ahead`, or -1 past the end.
860
1065
  *
861
- * @param ahead how far past `at` to look
1066
+ * @param ahead how far past `at` to look, 0 or 1
862
1067
  * @returns the code
863
1068
  */
864
1069
  peek(ahead: i32): i32 {
865
- const i: i32 = this.at + ahead
1070
+ const i: i32 = this.at
866
1071
  if (i < 0 || i >= toI32(this.text.length)) {
867
1072
  return -1
868
1073
  }
869
- return toI32(this.text.charCodeAt(i))
1074
+ if (ahead === 0) {
1075
+ return toI32(this.text.charCodeAt(i))
1076
+ }
1077
+ if (ahead !== 1 || i >= toI32(this.text.length) - 1) {
1078
+ return -1 // the reader looks at most one character ahead
1079
+ }
1080
+ return toI32(this.text.charCodeAt(i + 1))
1081
+ }
1082
+
1083
+ /** Move `at` one character on; at the end it stays there, and every caller has just seen a character. */
1084
+ step(): void {
1085
+ const i: i32 = this.at
1086
+ if (i >= 0 && i < toI32(this.text.length)) {
1087
+ this.at = i + 1
1088
+ }
870
1089
  }
871
1090
 
872
1091
  /**
873
1092
  * Whether the character `ahead` past `at` is a decimal digit.
874
1093
  *
875
- * @param ahead how far past `at` to look
1094
+ * @param ahead how far past `at` to look, 0 or 1
876
1095
  * @returns whether it is one
877
1096
  */
878
1097
  digitAt(ahead: i32): boolean {
@@ -897,7 +1116,7 @@ class TemporalReader {
897
1116
  */
898
1117
  eat(c: i32): boolean {
899
1118
  if (this.peek(toI32(0)) === c) {
900
- this.at = this.at + 1
1119
+ this.step()
901
1120
  return true
902
1121
  }
903
1122
  return false
@@ -910,16 +1129,18 @@ class TemporalReader {
910
1129
  * @returns their value, or 0 on failure
911
1130
  */
912
1131
  digits(count: i32): i32 {
913
- let value: i32 = 0
1132
+ // At most six digits, so the u32 sum never wraps.
1133
+ let value: u32 = 0
914
1134
  for (let i: i32 = 0; i < count; i++) {
915
- if (!this.digitAt(toI32(0))) {
1135
+ const c: i32 = this.peek(toI32(0))
1136
+ if (c < 48 || c > 57) {
916
1137
  this.ok = false
917
1138
  return 0
918
1139
  }
919
- value = value * 10 + this.peek(toI32(0)) - 48
920
- this.at = this.at + 1
1140
+ value = value * 10 + toU32(c - 48)
1141
+ this.step()
921
1142
  }
922
- return value
1143
+ return toI32(value)
923
1144
  }
924
1145
 
925
1146
  /**
@@ -932,23 +1153,24 @@ class TemporalReader {
932
1153
  if ((c !== 46 && c !== 44) || !this.digitAt(toI32(1))) {
933
1154
  return 0
934
1155
  }
935
- this.at = this.at + 1
936
- let value: i32 = 0
1156
+ this.step()
1157
+ // At most nine digits, so the u32 sum never wraps.
1158
+ let value: u32 = 0
937
1159
  let count: i32 = 0
938
1160
  while (this.digitAt(toI32(0))) {
939
- if (count === 9) {
1161
+ if (count >= 9) {
940
1162
  this.ok = false
941
1163
  return 0
942
1164
  }
943
- value = value * 10 + this.peek(toI32(0)) - 48
1165
+ value = value * 10 + toU32(this.peek(toI32(0))) - 48
944
1166
  count = count + 1
945
- this.at = this.at + 1
1167
+ this.step()
946
1168
  }
947
1169
  while (count < 9) {
948
1170
  value = value * 10
949
1171
  count = count + 1
950
1172
  }
951
- return value
1173
+ return toI32(value)
952
1174
  }
953
1175
 
954
1176
  /** Read a date: `YYYY-MM-DD`, `±YYYYYY-MM-DD`, or either without the dashes. */
@@ -956,13 +1178,13 @@ class TemporalReader {
956
1178
  const sign: i32 = this.peek(toI32(0))
957
1179
  let year: i32 = 0
958
1180
  if (sign === 43 || sign === 45) {
959
- this.at = this.at + 1
1181
+ this.step()
960
1182
  year = this.digits(toI32(6))
961
1183
  if (sign !== 43 && year === 0) {
962
1184
  this.ok = false // -000000 is not a year
963
1185
  }
964
1186
  if (sign !== 43) {
965
- year = -year
1187
+ year = toI32(0 - toI64(year))
966
1188
  }
967
1189
  } else {
968
1190
  year = this.digits(toI32(4))
@@ -994,7 +1216,7 @@ class TemporalReader {
994
1216
  this.minute = this.digits(toI32(2))
995
1217
  if ((extended && this.peek(toI32(0)) === 58) || (!extended && this.digitAt(toI32(0)))) {
996
1218
  if (extended) {
997
- this.at = this.at + 1
1219
+ this.step()
998
1220
  }
999
1221
  this.second = this.digits(toI32(2))
1000
1222
  this.fraction = this.fractionDigits()
@@ -1013,14 +1235,14 @@ class TemporalReader {
1013
1235
  readOffset(): void {
1014
1236
  const c: i32 = this.peek(toI32(0))
1015
1237
  if (c === 90 || c === 122) {
1016
- this.at = this.at + 1
1238
+ this.step()
1017
1239
  this.utc = true
1018
1240
  return
1019
1241
  }
1020
1242
  if (c !== 43 && c !== 45) {
1021
1243
  return
1022
1244
  }
1023
- this.at = this.at + 1
1245
+ this.step()
1024
1246
  const hours: i32 = this.digits(toI32(2))
1025
1247
  let minutes: i32 = 0
1026
1248
  let seconds: i32 = 0
@@ -1030,7 +1252,7 @@ class TemporalReader {
1030
1252
  minutes = this.digits(toI32(2))
1031
1253
  if ((extended && this.peek(toI32(0)) === 58) || (!extended && this.digitAt(toI32(0)))) {
1032
1254
  if (extended) {
1033
- this.at = this.at + 1
1255
+ this.step()
1034
1256
  }
1035
1257
  seconds = this.digits(toI32(2))
1036
1258
  fraction = this.fractionDigits()
@@ -1040,10 +1262,11 @@ class TemporalReader {
1040
1262
  this.ok = false
1041
1263
  return
1042
1264
  }
1043
- const total: i64 =
1044
- (toI64(hours) * 3600 + toI64(minutes) * 60 + toI64(seconds)) * TEMPORAL_NS_PER_SECOND + toI64(fraction)
1265
+ // Every field is a small count of digits here, so the u64 sum never wraps.
1266
+ const total: u64 =
1267
+ (toU64(hours) * 3600 + toU64(minutes) * 60 + toU64(seconds)) * 1000000000 + toU64(fraction)
1045
1268
  this.hasOffset = true
1046
- this.offsetNanos = c === 43 ? total : -total
1269
+ this.offsetNanos = c === 43 ? toI64(total) : toI64(0 - total)
1047
1270
  }
1048
1271
 
1049
1272
  /**
@@ -1061,7 +1284,7 @@ class TemporalReader {
1061
1284
  const critical: boolean = this.eat(toI32(33))
1062
1285
  const start: i32 = this.at
1063
1286
  while (!this.done() && this.peek(toI32(0)) !== 93) {
1064
- this.at = this.at + 1
1287
+ this.step()
1065
1288
  }
1066
1289
  if (this.done() || this.at === start) {
1067
1290
  this.ok = false
@@ -1070,12 +1293,12 @@ class TemporalReader {
1070
1293
  // The annotation is `text[start, end)`, read in place: a substring per
1071
1294
  // pass would be kept until the caller's memory is released (NL9018).
1072
1295
  const end: i32 = this.at
1073
- this.at = this.at + 1
1296
+ this.step()
1074
1297
  let eq: i32 = start
1075
1298
  while (eq < end && temporalCharAt(this.text, eq) !== 61) {
1076
1299
  eq = eq + 1
1077
1300
  }
1078
- if (eq === end) {
1301
+ if (eq >= end) {
1079
1302
  // A time zone: only first, only once, and spelled as the grammar's
1080
1303
  // TimeZoneIdentifier. Whether the zone exists is not asked: no type
1081
1304
  // here holds one.
@@ -1091,7 +1314,9 @@ class TemporalReader {
1091
1314
  return
1092
1315
  }
1093
1316
  if (temporalRangeIs(text, start, eq, "u-ca")) {
1094
- calendars = calendars + 1
1317
+ if (calendars < 2) {
1318
+ calendars = calendars + 1 // only none, one or more than one matters
1319
+ }
1095
1320
  criticalCalendar = criticalCalendar || critical
1096
1321
  // The first calendar is the string's; only a type that holds a
1097
1322
  // calendar refuses one other than iso8601 (`isoCalendar`).
@@ -1121,7 +1346,7 @@ class TemporalReader {
1121
1346
  }
1122
1347
  const c: i32 = this.peek(toI32(0))
1123
1348
  if ((c === 84 || c === 116 || c === 32) && this.digitAt(toI32(1))) {
1124
- this.at = this.at + 1
1349
+ this.step()
1125
1350
  this.readTime()
1126
1351
  if (this.ok) {
1127
1352
  this.readOffset()
@@ -1160,25 +1385,18 @@ const temporalIsAlphaNumeric = (c: i32): boolean =>
1160
1385
 
1161
1386
  /** Whether `text[from, to)` is an annotation value: runs of ASCII letters and digits joined by single `-`. */
1162
1387
  const temporalIsAnnotationValue = (text: string, from: i32, to: i32): boolean => {
1163
- let run: i32 = 0
1388
+ let inRun: boolean = false
1164
1389
  for (let i: i32 = from; i < to; i++) {
1165
1390
  const c: i32 = temporalCharAt(text, i)
1166
1391
  if (temporalIsAlphaNumeric(c)) {
1167
- run = run + 1
1168
- } else if (c === 45 && run > 0) {
1169
- run = 0
1392
+ inRun = true
1393
+ } else if (c === 45 && inRun) {
1394
+ inRun = false
1170
1395
  } else {
1171
1396
  return false
1172
1397
  }
1173
1398
  }
1174
- return run > 0
1175
- }
1176
-
1177
- /** The two decimal digits at `at` as a number, or -1, for the annotation checks. */
1178
- const temporalAnnotationTwo = (text: string, at: i32): i32 => {
1179
- const high: i32 = temporalCharAt(text, at) - 48
1180
- const low: i32 = temporalCharAt(text, at + 1) - 48
1181
- return high >= 0 && high <= 9 && low >= 0 && low <= 9 ? high * 10 + low : -1
1399
+ return inRun
1182
1400
  }
1183
1401
 
1184
1402
  /**
@@ -1188,46 +1406,54 @@ const temporalAnnotationTwo = (text: string, at: i32): i32 => {
1188
1406
  * `+`.
1189
1407
  */
1190
1408
  const temporalIsTimeZoneName = (text: string, from: i32, to: i32): boolean => {
1191
- const n: i32 = to - from
1409
+ if (from < 0 || from >= to) {
1410
+ return false
1411
+ }
1412
+ const n: i64 = toI64(to) - toI64(from)
1192
1413
  const first: i32 = temporalCharAt(text, from)
1193
1414
  if (first === 43 || first === 45) {
1194
- const hours: i32 = temporalAnnotationTwo(text, from + 1)
1415
+ const hours: i32 = temporalFastTwo(text, from + 1)
1195
1416
  if (hours < 0 || hours > 23) {
1196
1417
  return false
1197
1418
  }
1198
1419
  if (n === 3) {
1199
1420
  return true
1200
1421
  }
1201
- const at: i32 = n === 6 && temporalCharAt(text, from + 3) === 58 ? from + 4 : from + 3
1202
- const minutes: i32 = temporalAnnotationTwo(text, at)
1203
- return (n === 5 || n === 6) && at + 2 === to && minutes >= 0 && minutes <= 59
1422
+ // `±HHMM`, or `±HH:MM` with the colon; positions are summed in i64,
1423
+ // which `from + 4` cannot leave.
1424
+ const colon: boolean = n === 6 && temporalCharAt(text, toI32(toI64(from) + 3)) === 58
1425
+ if (n !== 5 && !colon) {
1426
+ return false
1427
+ }
1428
+ const minutes: i32 = temporalFastTwo(text, toI32(colon ? toI64(from) + 4 : toI64(from) + 3))
1429
+ return minutes >= 0 && minutes <= 59
1204
1430
  }
1205
- let length: i32 = 0
1206
- for (let i: i32 = from; i <= to; i++) {
1207
- const c: i32 = i < to ? temporalCharAt(text, i) : 47
1431
+ let empty: boolean = true
1432
+ for (let i: i32 = from; i < to; i++) {
1433
+ const c: i32 = temporalCharAt(text, i)
1208
1434
  if (c === 47) {
1209
- if (length === 0) {
1435
+ if (empty) {
1210
1436
  return false
1211
1437
  }
1212
- length = 0
1438
+ empty = true
1213
1439
  } else {
1214
1440
  const leading: boolean = (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 46 || c === 95
1215
- if (!leading && (length === 0 || !(temporalIsAlphaNumeric(c) || c === 45 || c === 43))) {
1441
+ if (!leading && (empty || !(temporalIsAlphaNumeric(c) || c === 45 || c === 43))) {
1216
1442
  return false
1217
1443
  }
1218
- length = length + 1
1444
+ empty = false
1219
1445
  }
1220
1446
  }
1221
- return true
1447
+ return !empty // the last name may not be empty either
1222
1448
  }
1223
1449
 
1224
1450
  /** Whether `text[from, to)` is `want`, ignoring the case of ASCII letters; `want` is lowercase. */
1225
1451
  const temporalRangeIs = (text: string, from: i32, to: i32, want: string): boolean => {
1226
- if (to - from !== toI32(want.length)) {
1452
+ if (toI64(to) - toI64(from) !== toI64(want.length)) {
1227
1453
  return false
1228
1454
  }
1229
- for (let i: i32 = 0; i < to - from; i++) {
1230
- let c: i32 = temporalCharAt(text, from + i)
1455
+ for (let i: i32 = 0; i < toI32(want.length); i++) {
1456
+ let c: i32 = temporalCharAt(text, toI32(toI64(from) + toI64(i)))
1231
1457
  if (c >= 65 && c <= 90) {
1232
1458
  c = c + 32
1233
1459
  }
@@ -1254,12 +1480,16 @@ const temporalIsTimeDesignator = (c: i32): boolean => c === 84 || c === 116 || c
1254
1480
 
1255
1481
  /** The two decimal digits at `at` as a number, or -1 when either is not a digit. */
1256
1482
  const temporalFastTwo = (text: string, at: i32): i32 => {
1257
- const high: i32 = temporalCharAt(text, at) - 48
1258
- const low: i32 = temporalCharAt(text, at + 1) - 48
1259
- if (high < 0 || high > 9 || low < 0 || low > 9) {
1483
+ if (at < 0 || at >= toI32(text.length) - 1) {
1484
+ return -1
1485
+ }
1486
+ // A code below `0` wraps past 9 here, so one test refuses either side.
1487
+ const high: u32 = toU32(toI32(text.charCodeAt(at))) - 48
1488
+ const low: u32 = toU32(toI32(text.charCodeAt(at + 1))) - 48
1489
+ if (high > 9 || low > 9) {
1260
1490
  return -1
1261
1491
  }
1262
- return high * 10 + low
1492
+ return toI32(high * 10 + low)
1263
1493
  }
1264
1494
 
1265
1495
  /**
@@ -1278,26 +1508,28 @@ const temporalFastDate = (text: string): i64 => {
1278
1508
  if (temporalCharAt(text, 4) !== 45 || temporalCharAt(text, 7) !== 45) {
1279
1509
  return -1
1280
1510
  }
1281
- const year: i32 = century * 100 + yy
1511
+ // Each field is two digits, so the unsigned sums never wrap.
1512
+ const year: u32 = toU32(century) * 100 + toU32(yy)
1282
1513
  if (day > temporalDaysInMonth(toI64(year), month)) {
1283
1514
  return -1
1284
1515
  }
1285
- return (toI64(year) + 400000) * 512 + toI64(month) * 32 + toI64(day)
1516
+ return toI64((toU64(year) + 400000) * 512 + toU64(month) * 32 + toU64(day))
1286
1517
  }
1287
1518
 
1288
1519
  /**
1289
- * The time `HH:MM`, `HH:MM:SS` or `HH:MM:SS.f` that runs from `at` to
1290
- * exactly `end`, as nanoseconds since midnight, or -1 when it is not in that
1291
- * form. Second 60 reads as 59, as the reader reads it.
1520
+ * The time `HH:MM`, `HH:MM:SS` or `HH:MM:SS.f` that runs from index 11, just
1521
+ * past a date and its designator, to exactly `end`, as nanoseconds since
1522
+ * midnight, or -1 when it is not in that form. Second 60 reads as 59, as the reader reads it.
1292
1523
  */
1293
- const temporalFastTime = (text: string, at: i32, end: i32): i64 => {
1524
+ const temporalFastTime = (text: string, end: i32): i64 => {
1525
+ const at: i32 = 11
1294
1526
  const hour: i32 = temporalFastTwo(text, at)
1295
1527
  const minute: i32 = temporalFastTwo(text, at + 3)
1296
1528
  if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || temporalCharAt(text, at + 2) !== 58) {
1297
1529
  return -1
1298
1530
  }
1299
1531
  let second: i32 = 0
1300
- let fraction: i32 = 0
1532
+ let fraction: u32 = 0
1301
1533
  let i: i32 = at + 5
1302
1534
  if (i < end) {
1303
1535
  second = temporalFastTwo(text, i + 1)
@@ -1315,8 +1547,8 @@ const temporalFastTime = (text: string, at: i32, end: i32): i64 => {
1315
1547
  return -1
1316
1548
  }
1317
1549
  for (let k: i32 = i + 1; k < end; k++) {
1318
- const d: i32 = temporalCharAt(text, k) - 48
1319
- if (d < 0 || d > 9) {
1550
+ const d: u32 = toU32(temporalCharAt(text, k)) - 48
1551
+ if (d > 9) {
1320
1552
  return -1
1321
1553
  }
1322
1554
  fraction = fraction * 10 + d
@@ -1330,16 +1562,21 @@ const temporalFastTime = (text: string, at: i32, end: i32): i64 => {
1330
1562
  if (i !== end) {
1331
1563
  return -1
1332
1564
  }
1333
- return (toI64(hour) * 3600 + toI64(minute) * 60 + toI64(second)) * TEMPORAL_NS_PER_SECOND + toI64(fraction)
1565
+ // Two-digit fields and a nine-digit fraction: the u64 sum never wraps.
1566
+ return toI64((toU64(hour) * 3600 + toU64(minute) * 60 + toU64(second)) * 1000000000 + toU64(fraction))
1334
1567
  }
1335
1568
 
1336
1569
  /**
1337
1570
  * Whether the date `r` read is inside Temporal's range: a date from
1338
1571
  * -271821-04-19 to +275760-09-13, and with `withTime`, a date-time after
1339
- * -271821-04-19T00:00. The reader has already checked the fields.
1572
+ * -271821-04-19T00:00. The reader has already checked the month and day,
1573
+ * and reads a year of up to six digits.
1340
1574
  */
1341
1575
  const temporalReadInRange = (r: TemporalReader, withTime: boolean): boolean => {
1342
- const day: i64 = temporalEpochDay(toI64(r.year), r.month, r.day)
1576
+ if (!temporalYearInRange(r.year)) {
1577
+ return false
1578
+ }
1579
+ const day: i64 = temporalEpochDay(r.year, r.month, r.day)
1343
1580
  if (day < TEMPORAL_MIN_EPOCH_DAY || day > TEMPORAL_MAX_EPOCH_DAY) {
1344
1581
  return false
1345
1582
  }
@@ -1405,7 +1642,7 @@ export class PlainDate {
1405
1642
  */
1406
1643
  constructor(isoYear: i32, isoMonth: i32, isoDay: i32) {
1407
1644
  temporalCheckDate("PlainDate", toI64(isoYear), toI64(isoMonth), toI64(isoDay))
1408
- const epochDay: i64 = temporalEpochDay(toI64(isoYear), isoMonth, isoDay)
1645
+ const epochDay: i64 = temporalEpochDay(isoYear, isoMonth, isoDay)
1409
1646
  if (epochDay < TEMPORAL_MIN_EPOCH_DAY || epochDay > TEMPORAL_MAX_EPOCH_DAY) {
1410
1647
  temporalRangeError("PlainDate: the date is outside Temporal's range")
1411
1648
  }
@@ -1413,15 +1650,16 @@ export class PlainDate {
1413
1650
  const leap: boolean = temporalIsLeapYear(y)
1414
1651
  const doy: i32 = temporalDayOfYear(isoMonth, isoDay, leap)
1415
1652
  const dow: i32 = temporalDayOfWeek(epochDay)
1416
- let week: i32 = toI32((doy - dow + 10) / 7)
1653
+ let week: i32 = toI32((toI64(doy) - toI64(dow) + 10) / 7)
1417
1654
  let weekYear: i32 = isoYear
1418
1655
  // Only the first and last days of a year can be in another year's week, so
1419
- // the 52-or-53 question is asked only there.
1656
+ // the 52-or-53 question is asked only there. The checked year is far
1657
+ // inside `i32`, so the year either side of it is exact.
1420
1658
  if (week < 1) {
1421
- weekYear = isoYear - 1
1422
- week = temporalWeeksInYear(y - 1)
1423
- } else if (week === 53 && temporalWeeksInYear(y) === 52) {
1424
- weekYear = isoYear + 1
1659
+ weekYear = toI32(toI64(isoYear) - 1)
1660
+ week = temporalWeeksInYear(weekYear)
1661
+ } else if (week === 53 && temporalWeeksInYear(isoYear) === 52) {
1662
+ weekYear = toI32(toI64(isoYear) + 1)
1425
1663
  week = 1
1426
1664
  }
1427
1665
  this.year = isoYear
@@ -1450,10 +1688,10 @@ export class PlainDate {
1450
1688
  toString(): string {
1451
1689
  const out: u8[] = new Array<u8>(TEMPORAL_TEXT_MAX)
1452
1690
  if (this.year >= 0 && this.year <= 9999) {
1453
- return String.fromBytes(out, 0, temporalPutDate4(out, 0, this.year, this.month, this.day))
1691
+ return temporalText(out, temporalPutDate4(out, 0, this.year, this.month, this.day))
1454
1692
  }
1455
1693
  const end: i32 = temporalPutDate(out, 0, this.year, this.month, this.day)
1456
- return String.fromBytes(out, 0, end)
1694
+ return temporalText(out, end)
1457
1695
  }
1458
1696
 
1459
1697
  /**
@@ -1486,9 +1724,9 @@ export class PlainDate {
1486
1724
  * @returns the new date
1487
1725
  */
1488
1726
  add(duration: Duration): PlainDate {
1489
- let days: i64 = duration.weeks * 7 + duration.days
1727
+ let days: i64 = temporalAdd(temporalMul(duration.weeks, 7), duration.days)
1490
1728
  if (!temporalNoTime(duration)) {
1491
- days = days + temporalSpanOfDuration(duration, false).truncDays()
1729
+ days = temporalAdd(days, temporalSpanOfDuration(duration, false).truncDays())
1492
1730
  }
1493
1731
  const epochDay: i64 = temporalAddToDate(
1494
1732
  this.year,
@@ -1512,6 +1750,35 @@ export class PlainDate {
1512
1750
  return this.add(duration.negated())
1513
1751
  }
1514
1752
 
1753
+ /**
1754
+ * `add`, answering an answer outside Temporal's range as `Err` where `add`
1755
+ * panics. Not part of Temporal.
1756
+ *
1757
+ * @param duration how far to move
1758
+ * @returns the new date, or `Err` with the `RangeError` text `add` panics with
1759
+ */
1760
+ tryAdd(duration: Duration): Result<PlainDate, string> {
1761
+ // A duration's calendar fields are below 2^32 and its time below 2^53
1762
+ // seconds, so these sums cannot leave `i64`: only the range test fails.
1763
+ let days: i64 = temporalAdd(temporalMul(duration.weeks, 7), duration.days)
1764
+ if (!temporalNoTime(duration)) {
1765
+ days = temporalAdd(days, temporalSpanOfDuration(duration, false).truncDays())
1766
+ }
1767
+ const epochDay: i64 = temporalMovedEpochDay(
1768
+ this.year,
1769
+ this.month,
1770
+ this.day,
1771
+ this.epochDay,
1772
+ duration.years,
1773
+ duration.months,
1774
+ days
1775
+ )
1776
+ if (epochDay < TEMPORAL_MIN_EPOCH_DAY || epochDay > TEMPORAL_MAX_EPOCH_DAY) {
1777
+ return Err("PlainDate: the date is outside Temporal's range")
1778
+ }
1779
+ return Ok(temporalDateOfEpochDay(epochDay))
1780
+ }
1781
+
1515
1782
  /**
1516
1783
  * The days from this date to `other`, as a duration of days alone
1517
1784
  * (Temporal's default `largestUnit: "day"`); negative when `other` is
@@ -1521,7 +1788,7 @@ export class PlainDate {
1521
1788
  * @returns the difference
1522
1789
  */
1523
1790
  until(other: PlainDate): Duration {
1524
- return new Duration(0, 0, 0, other.epochDay - this.epochDay)
1791
+ return new Duration(0, 0, 0, temporalSub(other.epochDay, this.epochDay))
1525
1792
  }
1526
1793
 
1527
1794
  /**
@@ -1531,7 +1798,7 @@ export class PlainDate {
1531
1798
  * @returns the difference
1532
1799
  */
1533
1800
  since(other: PlainDate): Duration {
1534
- return new Duration(0, 0, 0, this.epochDay - other.epochDay)
1801
+ return new Duration(0, 0, 0, temporalSub(this.epochDay, other.epochDay))
1535
1802
  }
1536
1803
 
1537
1804
  /**
@@ -1555,6 +1822,9 @@ export class PlainDate {
1555
1822
  }
1556
1823
  }
1557
1824
 
1825
+ /** The `RangeError` text for a string `plainDateFrom` refuses. */
1826
+ const temporalDateParseError = (text: string): string => `PlainDate: cannot parse "${text}"`
1827
+
1558
1828
  /**
1559
1829
  * `Temporal.PlainDate.from(text)`: the date an RFC 9557 string names. A time,
1560
1830
  * an offset and annotations may follow the date and are ignored but for a
@@ -1567,7 +1837,7 @@ export class PlainDate {
1567
1837
  export const plainDateFrom = (text: string): PlainDate => {
1568
1838
  const date: PlainDate | null = plainDateFromOrNull(text)
1569
1839
  if (date === null) {
1570
- temporalRangeError(`PlainDate: cannot parse "${text}"`)
1840
+ temporalRangeError(temporalDateParseError(text))
1571
1841
  return new PlainDate(1970, 1, 1)
1572
1842
  }
1573
1843
  return date
@@ -1594,6 +1864,43 @@ export const plainDateFromOrNull = (text: string): PlainDate | null => {
1594
1864
  return new PlainDate(r.year, r.month, r.day)
1595
1865
  }
1596
1866
 
1867
+ /**
1868
+ * `new PlainDate(isoYear, isoMonth, isoDay)`, answering fields that name no
1869
+ * date, or one outside Temporal's range, as `Err` where the constructor
1870
+ * panics. Not part of Temporal.
1871
+ *
1872
+ * @param isoYear the year
1873
+ * @param isoMonth the month, 1 to 12
1874
+ * @param isoDay the day of the month, from 1
1875
+ * @returns the date, or `Err` with the `RangeError` text the constructor panics with
1876
+ */
1877
+ export const tryPlainDate = (isoYear: i32, isoMonth: i32, isoDay: i32): Result<PlainDate, string> => {
1878
+ const problem: string = temporalDateProblem("PlainDate", toI64(isoYear), toI64(isoMonth), toI64(isoDay))
1879
+ if (problem.length > 0) {
1880
+ return Err(problem)
1881
+ }
1882
+ const epochDay: i64 = temporalEpochDay(isoYear, isoMonth, isoDay)
1883
+ if (epochDay < TEMPORAL_MIN_EPOCH_DAY || epochDay > TEMPORAL_MAX_EPOCH_DAY) {
1884
+ return Err("PlainDate: the date is outside Temporal's range")
1885
+ }
1886
+ return Ok(new PlainDate(isoYear, isoMonth, isoDay))
1887
+ }
1888
+
1889
+ /**
1890
+ * `plainDateFrom`, answering a string it refuses as `Err` where
1891
+ * `plainDateFrom` panics. Not part of Temporal.
1892
+ *
1893
+ * @param text such as `2024-01-15`
1894
+ * @returns the date, or `Err` with the `RangeError` text `plainDateFrom` panics with
1895
+ */
1896
+ export const tryPlainDateFrom = (text: string): Result<PlainDate, string> => {
1897
+ const date: PlainDate | null = plainDateFromOrNull(text)
1898
+ if (date === null) {
1899
+ return Err(temporalDateParseError(text))
1900
+ }
1901
+ return Ok(date)
1902
+ }
1903
+
1597
1904
  /**
1598
1905
  * `Temporal.PlainDate.compare(a, b)`: -1, 0 or 1 as `a` is before, the same
1599
1906
  * as, or after `b`, which is the comparator `sort` takes.
@@ -1602,7 +1909,8 @@ export const plainDateFromOrNull = (text: string): PlainDate | null => {
1602
1909
  * @param b the second date
1603
1910
  * @returns the order of the two
1604
1911
  */
1605
- export const plainDateCompare = (a: PlainDate, b: PlainDate): i32 => temporalSign(a.epochDay - b.epochDay)
1912
+ export const plainDateCompare = (a: PlainDate, b: PlainDate): i32 =>
1913
+ temporalSign(temporalSub(a.epochDay, b.epochDay))
1606
1914
 
1607
1915
  // ---------------------------------------------------------------------------
1608
1916
  // PlainTime
@@ -1672,9 +1980,11 @@ export class PlainTime {
1672
1980
  */
1673
1981
  toString(): string {
1674
1982
  const out: u8[] = new Array<u8>(TEMPORAL_TEXT_MAX)
1675
- const sub: i32 = this.millisecond * 1000000 + this.microsecond * 1000 + this.nanosecond
1676
- const end: i32 = temporalPutTime(out, 0, this.hour, this.minute, this.second, sub)
1677
- return String.fromBytes(out, 0, end)
1983
+ // Each field is under 1000, so the u32 sum never wraps.
1984
+ const sub: u32 =
1985
+ toU32(this.millisecond) * 1000000 + toU32(this.microsecond) * 1000 + toU32(this.nanosecond)
1986
+ const end: i32 = temporalPutTime(out, 0, this.hour, this.minute, this.second, toI32(sub))
1987
+ return temporalText(out, end)
1678
1988
  }
1679
1989
 
1680
1990
  /**
@@ -1706,8 +2016,10 @@ export class PlainTime {
1706
2016
  add(duration: Duration): PlainTime {
1707
2017
  const span: TemporalSpan = temporalSpanOfDuration(duration, false)
1708
2018
  const seconds: i64 = temporalFloorMod(span.seconds, TEMPORAL_SECONDS_PER_DAY)
1709
- const ns: i64 = seconds * TEMPORAL_NS_PER_SECOND + toI64(span.nanos) + this.nanoOfDay
1710
- return temporalTimeOfNanos(temporalFloorMod(ns, TEMPORAL_NS_PER_DAY))
2019
+ // `seconds` is below a day, `span.nanos` below a second and `nanoOfDay` below a day's
2020
+ // nanoseconds, so the `u64` sum stays under 2 × 10^14 and never wraps.
2021
+ const ns: u64 = toU64(seconds) * 1000000000 + toU64(span.nanos) + toU64(this.nanoOfDay)
2022
+ return temporalTimeOfNanos(temporalFloorMod(toI64(ns), TEMPORAL_NS_PER_DAY))
1711
2023
  }
1712
2024
 
1713
2025
  /**
@@ -1728,7 +2040,10 @@ export class PlainTime {
1728
2040
  * @returns the difference
1729
2041
  */
1730
2042
  until(other: PlainTime): Duration {
1731
- return temporalBalance(new TemporalSpan(0, other.nanoOfDay - this.nanoOfDay), TEMPORAL_UNIT_HOUR)
2043
+ return temporalBalance(
2044
+ new TemporalSpan(0, temporalSub(other.nanoOfDay, this.nanoOfDay)),
2045
+ TEMPORAL_UNIT_HOUR
2046
+ )
1732
2047
  }
1733
2048
 
1734
2049
  /**
@@ -1738,7 +2053,10 @@ export class PlainTime {
1738
2053
  * @returns the difference
1739
2054
  */
1740
2055
  since(other: PlainTime): Duration {
1741
- return temporalBalance(new TemporalSpan(0, this.nanoOfDay - other.nanoOfDay), TEMPORAL_UNIT_HOUR)
2056
+ return temporalBalance(
2057
+ new TemporalSpan(0, temporalSub(this.nanoOfDay, other.nanoOfDay)),
2058
+ TEMPORAL_UNIT_HOUR
2059
+ )
1742
2060
  }
1743
2061
  }
1744
2062
 
@@ -1827,26 +2145,22 @@ const temporalLooksLikeYearMonthOrMonthDay = (text: string): boolean => {
1827
2145
  return false
1828
2146
  }
1829
2147
  }
1830
- if (n === 7 && toI32(head.charCodeAt(4)) === 45) {
1831
- const m: i32 = temporalTwoDigits(head, 5)
2148
+ if (n === 7 && temporalCharAt(head, 4) === 45) {
2149
+ const m: i32 = temporalFastTwo(head, 5)
1832
2150
  return m >= 1 && m <= 12
1833
2151
  }
1834
2152
  if (n === 6 && toI32(head.indexOf("-")) < 0) {
1835
- const m: i32 = temporalTwoDigits(head, 4)
2153
+ const m: i32 = temporalFastTwo(head, 4)
1836
2154
  return m >= 1 && m <= 12
1837
2155
  }
1838
- if ((n === 5 && toI32(head.charCodeAt(2)) === 45) || (n === 4 && toI32(head.indexOf("-")) < 0)) {
1839
- const m: i32 = temporalTwoDigits(head, 0)
1840
- const d: i32 = temporalTwoDigits(head, n === 5 ? 3 : 2)
2156
+ if ((n === 5 && temporalCharAt(head, 2) === 45) || (n === 4 && toI32(head.indexOf("-")) < 0)) {
2157
+ const m: i32 = temporalFastTwo(head, 0)
2158
+ const d: i32 = temporalFastTwo(head, n === 5 ? 3 : 2)
1841
2159
  return m >= 1 && m <= 12 && d >= 1 && d <= temporalDaysInMonth(1972, m)
1842
2160
  }
1843
2161
  return false
1844
2162
  }
1845
2163
 
1846
- /** The two decimal digits of `text` at `at` as a number. */
1847
- const temporalTwoDigits = (text: string, at: i32): i32 =>
1848
- (toI32(text.charCodeAt(at)) - 48) * 10 + toI32(text.charCodeAt(at + 1)) - 48
1849
-
1850
2164
  /**
1851
2165
  * `Temporal.PlainTime.compare(a, b)`: -1, 0 or 1 as `a` is earlier than, the
1852
2166
  * same as, or later than `b`.
@@ -1855,7 +2169,8 @@ const temporalTwoDigits = (text: string, at: i32): i32 =>
1855
2169
  * @param b the second time
1856
2170
  * @returns the order of the two
1857
2171
  */
1858
- export const plainTimeCompare = (a: PlainTime, b: PlainTime): i32 => temporalSign(a.nanoOfDay - b.nanoOfDay)
2172
+ export const plainTimeCompare = (a: PlainTime, b: PlainTime): i32 =>
2173
+ temporalSign(temporalSub(a.nanoOfDay, b.nanoOfDay))
1859
2174
 
1860
2175
  // ---------------------------------------------------------------------------
1861
2176
  // PlainDateTime
@@ -1984,7 +2299,10 @@ export class PlainDateTime {
1984
2299
  */
1985
2300
  toString(): string {
1986
2301
  const out: u8[] = new Array<u8>(TEMPORAL_TEXT_MAX)
1987
- const sub: i32 = this.millisecond * 1000000 + this.microsecond * 1000 + this.nanosecond
2302
+ // Each field is under 1000, so the u32 sum never wraps.
2303
+ const sub: i32 = toI32(
2304
+ toU32(this.millisecond) * 1000000 + toU32(this.microsecond) * 1000 + toU32(this.nanosecond)
2305
+ )
1988
2306
  if (this.year >= 0 && this.year <= 9999) {
1989
2307
  const seconds: i32 = temporalPutDateTime4(
1990
2308
  out,
@@ -1996,7 +2314,7 @@ export class PlainDateTime {
1996
2314
  this.minute,
1997
2315
  this.second
1998
2316
  )
1999
- return String.fromBytes(out, 0, temporalPutFraction(out, seconds, sub))
2317
+ return temporalText(out, temporalPutFraction(out, seconds, sub))
2000
2318
  }
2001
2319
  const date: i32 = temporalPutDate(out, 0, this.year, this.month, this.day)
2002
2320
  const end: i32 = temporalPutTime(
@@ -2007,7 +2325,7 @@ export class PlainDateTime {
2007
2325
  this.second,
2008
2326
  sub
2009
2327
  )
2010
- return String.fromBytes(out, 0, end)
2328
+ return temporalText(out, end)
2011
2329
  }
2012
2330
 
2013
2331
  /**
@@ -2078,12 +2396,15 @@ export class PlainDateTime {
2078
2396
  let nanoOfDay: i64 = this.nanoOfDay
2079
2397
  if (!temporalNoTime(duration)) {
2080
2398
  const seconds: i64 = temporalDurationSeconds(duration, false)
2081
- const nanos: i64 = temporalDurationNanos(duration) + this.nanoOfDay
2082
- const total: i64 = seconds + temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND)
2399
+ // The duration's nanoseconds are below 3 × 10^9 and `nanoOfDay` below a day's,
2400
+ // so neither `u64` sum below wraps.
2401
+ const nanos: i64 = toI64(toU64(temporalDurationNanos(duration)) + toU64(this.nanoOfDay))
2402
+ const total: i64 = temporalAdd(seconds, temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND))
2083
2403
  carryDays = temporalFloorDiv(total, TEMPORAL_SECONDS_PER_DAY)
2084
- nanoOfDay =
2085
- temporalFloorMod(total, TEMPORAL_SECONDS_PER_DAY) * TEMPORAL_NS_PER_SECOND +
2086
- temporalFloorMod(nanos, TEMPORAL_NS_PER_SECOND)
2404
+ nanoOfDay = toI64(
2405
+ toU64(temporalFloorMod(total, TEMPORAL_SECONDS_PER_DAY)) * 1000000000 +
2406
+ toU64(temporalFloorMod(nanos, TEMPORAL_NS_PER_SECOND))
2407
+ )
2087
2408
  }
2088
2409
  const epochDay: i64 = temporalAddToDate(
2089
2410
  this.year,
@@ -2092,7 +2413,7 @@ export class PlainDateTime {
2092
2413
  this.epochDay,
2093
2414
  duration.years,
2094
2415
  duration.months,
2095
- duration.weeks * 7 + duration.days + carryDays
2416
+ temporalAdd(temporalAdd(temporalMul(duration.weeks, 7), duration.days), carryDays)
2096
2417
  )
2097
2418
  const civil: i64 = temporalCivilOfEpochDay(epochDay)
2098
2419
  const secs: i64 = toI64(nanoOfDay / TEMPORAL_NS_PER_SECOND)
@@ -2144,7 +2465,10 @@ export class PlainDateTime {
2144
2465
 
2145
2466
  /** The span from `a` to `b`, every day 24 hours. */
2146
2467
  const temporalDateTimeSpan = (a: PlainDateTime, b: PlainDateTime): TemporalSpan =>
2147
- new TemporalSpan((b.epochDay - a.epochDay) * TEMPORAL_SECONDS_PER_DAY, b.nanoOfDay - a.nanoOfDay)
2468
+ new TemporalSpan(
2469
+ temporalMul(temporalSub(b.epochDay, a.epochDay), TEMPORAL_SECONDS_PER_DAY),
2470
+ temporalSub(b.nanoOfDay, a.nanoOfDay)
2471
+ )
2148
2472
 
2149
2473
  /**
2150
2474
  * `Temporal.PlainDateTime.from(text)`: the date-time an RFC 9557 string
@@ -2175,7 +2499,7 @@ export const plainDateTimeFromOrNull = (text: string): PlainDateTime | null => {
2175
2499
  const length: i32 = toI32(text.length)
2176
2500
  if (length >= 16 && temporalIsTimeDesignator(temporalCharAt(text, 10))) {
2177
2501
  const civil: i64 = temporalFastDate(text)
2178
- const nanoOfDay: i64 = civil < 0 ? -1 : temporalFastTime(text, 11, length)
2502
+ const nanoOfDay: i64 = civil < 0 ? -1 : temporalFastTime(text, length)
2179
2503
  if (nanoOfDay >= 0) {
2180
2504
  const secs: i32 = toI32(nanoOfDay / TEMPORAL_NS_PER_SECOND)
2181
2505
  const sub: i32 = toI32(nanoOfDay % TEMPORAL_NS_PER_SECOND)
@@ -2218,8 +2542,8 @@ export const plainDateTimeFromOrNull = (text: string): PlainDateTime | null => {
2218
2542
  * @returns the order of the two
2219
2543
  */
2220
2544
  export const plainDateTimeCompare = (a: PlainDateTime, b: PlainDateTime): i32 => {
2221
- const byDay: i32 = temporalSign(a.epochDay - b.epochDay)
2222
- return byDay !== 0 ? byDay : temporalSign(a.nanoOfDay - b.nanoOfDay)
2545
+ const byDay: i32 = temporalSign(temporalSub(a.epochDay, b.epochDay))
2546
+ return byDay !== 0 ? byDay : temporalSign(temporalSub(a.nanoOfDay, b.nanoOfDay))
2223
2547
  }
2224
2548
 
2225
2549
  // ---------------------------------------------------------------------------
@@ -2260,8 +2584,9 @@ export class Duration {
2260
2584
  /**
2261
2585
  * The duration, as `new Temporal.Duration(...)`; every field defaults to 0.
2262
2586
  * Panics with a `RangeError` when two fields have different signs, when
2263
- * `years`, `months` or `weeks` reaches 2^32, or when the rest comes to 2^53
2264
- * seconds or more.
2587
+ * `years`, `months` or `weeks` reaches 2^32, when the rest comes to 2^53
2588
+ * seconds or more, or when `microseconds` or `nanoseconds` is the least
2589
+ * `i64`, whose negation does not fit.
2265
2590
  *
2266
2591
  * @param years years
2267
2592
  * @param months months
@@ -2289,7 +2614,8 @@ export class Duration {
2289
2614
  // The checks are written out here, not a call of `temporalDurationProblem`,
2290
2615
  // because every `until` and `add` builds a `Duration`: as a call they cost
2291
2616
  // `until` on a date 70% (bench/temporal.ts). Each bound is tested on both
2292
- // sides, so the least `i64`, whose magnitude does not fit, is refused too.
2617
+ // sides. The least `i64` as microseconds or nanoseconds is within them, so
2618
+ // a guard after them refuses it.
2293
2619
  let sign: i32 = temporalSignOf(0, years)
2294
2620
  sign = temporalSignOf(sign, months)
2295
2621
  sign = temporalSignOf(sign, weeks)
@@ -2301,7 +2627,8 @@ export class Duration {
2301
2627
  sign = temporalSignOf(sign, microseconds)
2302
2628
  sign = temporalSignOf(sign, nanoseconds)
2303
2629
  const c: i64 = TEMPORAL_MAX_CALENDAR_FIELD
2304
- if (years <= -c || years >= c || months <= -c || months >= c || weeks <= -c || weeks >= c) {
2630
+ const low: i64 = TEMPORAL_MIN_CALENDAR_FIELD
2631
+ if (years <= low || years >= c || months <= low || months >= c || weeks <= low || weeks >= c) {
2305
2632
  temporalRangeError("Duration: years, months and weeks must each be below 2^32")
2306
2633
  }
2307
2634
  const m: i64 = TEMPORAL_MAX_DURATION_SECONDS
@@ -2312,7 +2639,7 @@ export class Duration {
2312
2639
  hours > 2501999792983 ||
2313
2640
  minutes < -150119987579016 ||
2314
2641
  minutes > 150119987579016 ||
2315
- seconds < -m ||
2642
+ seconds < TEMPORAL_MIN_DURATION_SECONDS ||
2316
2643
  seconds > m
2317
2644
  ) {
2318
2645
  temporalRangeError("Duration: the time fields come to 2^53 seconds or more")
@@ -2320,6 +2647,15 @@ export class Duration {
2320
2647
  if (temporalWholeSeconds(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) > m) {
2321
2648
  temporalRangeError("Duration: the time fields come to 2^53 seconds or more")
2322
2649
  }
2650
+ // The least `i64` is under 2^53 seconds as microseconds or nanoseconds, but
2651
+ // its negation does not fit, so `negated` and `abs` could not answer it. It
2652
+ // is the one negative value whose wrapping negation is negative too.
2653
+ if (
2654
+ (microseconds < 0 && temporalNegField(microseconds) < 0) ||
2655
+ (nanoseconds < 0 && temporalNegField(nanoseconds) < 0)
2656
+ ) {
2657
+ temporalRangeError("Duration: microseconds and nanoseconds must be above the least i64")
2658
+ }
2323
2659
  this.years = years
2324
2660
  this.months = months
2325
2661
  this.weeks = weeks
@@ -2342,24 +2678,26 @@ export class Duration {
2342
2678
  * @returns the ISO 8601 form
2343
2679
  */
2344
2680
  toString(): string {
2345
- const k: i64 = toI64(this.sign < 0 ? -1 : 1)
2681
+ // Every field shares the sign and none is the least `i64`, so each
2682
+ // magnitude below is exact.
2683
+ const k: boolean = this.sign < 0
2346
2684
  const out: u8[] = new Array<u8>(TEMPORAL_TEXT_MAX)
2347
2685
  let i: i32 = 0
2348
- if (this.sign < 0) {
2686
+ if (k) {
2349
2687
  i = temporalPutByte(out, i, 45)
2350
2688
  }
2351
2689
  i = temporalPutByte(out, i, 80)
2352
2690
  if (this.years !== 0) {
2353
- i = temporalPutField(out, i, this.years * k, 89)
2691
+ i = temporalPutField(out, i, temporalMagnitude(this.years, k), 89)
2354
2692
  }
2355
2693
  if (this.months !== 0) {
2356
- i = temporalPutField(out, i, this.months * k, 77)
2694
+ i = temporalPutField(out, i, temporalMagnitude(this.months, k), 77)
2357
2695
  }
2358
2696
  if (this.weeks !== 0) {
2359
- i = temporalPutField(out, i, this.weeks * k, 87)
2697
+ i = temporalPutField(out, i, temporalMagnitude(this.weeks, k), 87)
2360
2698
  }
2361
2699
  if (this.days !== 0) {
2362
- i = temporalPutField(out, i, this.days * k, 68)
2700
+ i = temporalPutField(out, i, temporalMagnitude(this.days, k), 68)
2363
2701
  }
2364
2702
  const zeroAbove: boolean =
2365
2703
  this.years === 0 &&
@@ -2371,32 +2709,34 @@ export class Duration {
2371
2709
  // The seconds and their fractions are one decimal number, balanced. Every
2372
2710
  // field times `k` is not negative, so each division here truncates as a
2373
2711
  // floor would.
2374
- const ms: i64 = this.milliseconds * k
2375
- const us: i64 = this.microseconds * k
2376
- const ns: i64 = this.nanoseconds * k
2377
- let fraction: i64 = (ms % 1000) * 1000000 + (us % 1000000) * 1000 + (ns % TEMPORAL_NS_PER_SECOND)
2378
- const wholeSeconds: i64 =
2379
- this.seconds * k +
2380
- toI64(ms / 1000) +
2381
- toI64(us / 1000000) +
2382
- toI64(ns / TEMPORAL_NS_PER_SECOND) +
2383
- toI64(fraction / TEMPORAL_NS_PER_SECOND)
2384
- fraction = fraction % TEMPORAL_NS_PER_SECOND
2712
+ // The constructor bounds the sum below 2^53, so the `u64` sums are exact.
2713
+ const ms: u64 = toU64(temporalMagnitude(this.milliseconds, k))
2714
+ const us: u64 = toU64(temporalMagnitude(this.microseconds, k))
2715
+ const ns: u64 = toU64(temporalMagnitude(this.nanoseconds, k))
2716
+ let fraction: u64 = (ms % 1000) * 1000000 + (us % 1000000) * 1000 + (ns % 1000000000)
2717
+ const wholeSeconds: i64 = toI64(
2718
+ toU64(temporalMagnitude(this.seconds, k)) +
2719
+ ms / 1000 +
2720
+ us / 1000000 +
2721
+ ns / 1000000000 +
2722
+ fraction / 1000000000
2723
+ )
2724
+ fraction = fraction % 1000000000
2385
2725
  const withSeconds: boolean = wholeSeconds !== 0 || fraction !== 0 || zeroAbove
2386
2726
  if (this.hours !== 0 || this.minutes !== 0 || withSeconds) {
2387
2727
  i = temporalPutByte(out, i, 84)
2388
2728
  }
2389
2729
  if (this.hours !== 0) {
2390
- i = temporalPutField(out, i, this.hours * k, 72)
2730
+ i = temporalPutField(out, i, temporalMagnitude(this.hours, k), 72)
2391
2731
  }
2392
2732
  if (this.minutes !== 0) {
2393
- i = temporalPutField(out, i, this.minutes * k, 77)
2733
+ i = temporalPutField(out, i, temporalMagnitude(this.minutes, k), 77)
2394
2734
  }
2395
2735
  if (withSeconds) {
2396
- i = temporalPutNumber(out, i, wholeSeconds, 1)
2736
+ i = temporalPutNumber(out, i, wholeSeconds)
2397
2737
  i = temporalPutByte(out, temporalPutFraction(out, i, toI32(fraction)), 83)
2398
2738
  }
2399
- return String.fromBytes(out, 0, i)
2739
+ return temporalText(out, i)
2400
2740
  }
2401
2741
 
2402
2742
  /**
@@ -2415,16 +2755,16 @@ export class Duration {
2415
2755
  */
2416
2756
  negated(): Duration {
2417
2757
  return new Duration(
2418
- -this.years,
2419
- -this.months,
2420
- -this.weeks,
2421
- -this.days,
2422
- -this.hours,
2423
- -this.minutes,
2424
- -this.seconds,
2425
- -this.milliseconds,
2426
- -this.microseconds,
2427
- -this.nanoseconds
2758
+ temporalNegField(this.years),
2759
+ temporalNegField(this.months),
2760
+ temporalNegField(this.weeks),
2761
+ temporalNegField(this.days),
2762
+ temporalNegField(this.hours),
2763
+ temporalNegField(this.minutes),
2764
+ temporalNegField(this.seconds),
2765
+ temporalNegField(this.milliseconds),
2766
+ temporalNegField(this.microseconds),
2767
+ temporalNegField(this.nanoseconds)
2428
2768
  )
2429
2769
  }
2430
2770
 
@@ -2501,22 +2841,25 @@ const temporalWholeSeconds = (
2501
2841
  microseconds: i64,
2502
2842
  nanoseconds: i64
2503
2843
  ): i64 => {
2504
- const carry: i64 = toI64(
2505
- (toI64(milliseconds % 1000) * 1000000 +
2506
- toI64(microseconds % 1000000) * 1000 +
2507
- (nanoseconds % 1000000000)) /
2508
- 1000000000
2844
+ // With the fields so bounded every term below is under 2^54 in magnitude, so
2845
+ // the sums, done in wrapping `u64` arithmetic on the two's-complement bits,
2846
+ // are the exact signed sums.
2847
+ const remainders: i64 = toI64(
2848
+ toU64(milliseconds % 1000) * 1000000 +
2849
+ toU64(microseconds % 1000000) * 1000 +
2850
+ toU64(nanoseconds % 1000000000)
2851
+ )
2852
+ const whole: i64 = toI64(
2853
+ toU64(days) * 86400 +
2854
+ toU64(hours) * 3600 +
2855
+ toU64(minutes) * 60 +
2856
+ toU64(seconds) +
2857
+ toU64(milliseconds / 1000) +
2858
+ toU64(microseconds / 1000000) +
2859
+ toU64(nanoseconds / 1000000000) +
2860
+ toU64(remainders / 1000000000)
2509
2861
  )
2510
- const whole: i64 =
2511
- days * TEMPORAL_SECONDS_PER_DAY +
2512
- hours * 3600 +
2513
- minutes * 60 +
2514
- seconds +
2515
- toI64(milliseconds / 1000) +
2516
- toI64(microseconds / 1000000) +
2517
- toI64(nanoseconds / 1000000000) +
2518
- carry
2519
- return whole < 0 ? -whole : whole
2862
+ return whole < 0 ? toI64(0 - toU64(whole)) : whole
2520
2863
  }
2521
2864
 
2522
2865
  /**
@@ -2525,8 +2868,9 @@ const temporalWholeSeconds = (
2525
2868
  * where the constructor would panic:
2526
2869
  * two non-zero fields with different signs, `years`, `months` or `weeks` at
2527
2870
  * 2^32 or past, or the rest coming to 2^53 seconds or more (Temporal's
2528
- * IsValidDuration). Every bound is tested on both sides, so the least `i64`,
2529
- * whose magnitude does not fit, is refused too.
2871
+ * IsValidDuration). Every bound is tested on both sides. The least `i64` as
2872
+ * microseconds or nanoseconds is within them; the constructor refuses it, and
2873
+ * `durationFromOrNull` never reads it, as every field it reads is below 10^16.
2530
2874
  */
2531
2875
  const temporalDurationProblem = (
2532
2876
  years: i64,
@@ -2566,7 +2910,8 @@ const temporalDurationProblem = (
2566
2910
  return "the fields have mixed signs"
2567
2911
  }
2568
2912
  const c: i64 = TEMPORAL_MAX_CALENDAR_FIELD
2569
- if (years <= -c || years >= c || months <= -c || months >= c || weeks <= -c || weeks >= c) {
2913
+ const low: i64 = TEMPORAL_MIN_CALENDAR_FIELD
2914
+ if (years <= low || years >= c || months <= low || months >= c || weeks <= low || weeks >= c) {
2570
2915
  return "years, months and weeks must each be below 2^32"
2571
2916
  }
2572
2917
  // Each field alone within the 2^53-second bound keeps the sum inside an i64.
@@ -2578,7 +2923,7 @@ const temporalDurationProblem = (
2578
2923
  hours > 2501999792983 ||
2579
2924
  minutes < -150119987579016 ||
2580
2925
  minutes > 150119987579016 ||
2581
- seconds < -m ||
2926
+ seconds < TEMPORAL_MIN_DURATION_SECONDS ||
2582
2927
  seconds > m
2583
2928
  ) {
2584
2929
  return "the time fields come to 2^53 seconds or more"
@@ -2671,7 +3016,7 @@ export const durationFromOrNull = (text: string): Duration | null => {
2671
3016
  return null
2672
3017
  }
2673
3018
  inTime = true
2674
- r.at = r.at + 1
3019
+ r.step()
2675
3020
  if (r.done()) {
2676
3021
  return null
2677
3022
  }
@@ -2680,15 +3025,16 @@ export const durationFromOrNull = (text: string): Duration | null => {
2680
3025
  if (fractionSeen || !r.digitAt(toI32(0))) {
2681
3026
  return null
2682
3027
  }
2683
- let n: i64 = 0
3028
+ // At most 16 digits, so the `u64` value never wraps.
3029
+ let n: u64 = 0
2684
3030
  let count: i32 = 0
2685
3031
  while (r.digitAt(toI32(0))) {
2686
- if (count === 16) {
3032
+ if (count >= 16) {
2687
3033
  return null
2688
3034
  }
2689
- n = n * 10 + toI64(r.peek(toI32(0)) - 48)
3035
+ n = n * 10 + toU64(r.peek(toI32(0))) - 48
2690
3036
  count = count + 1
2691
- r.at = r.at + 1
3037
+ r.step()
2692
3038
  }
2693
3039
  if (count > longest) {
2694
3040
  longest = count
@@ -2697,74 +3043,82 @@ export const durationFromOrNull = (text: string): Duration | null => {
2697
3043
  const fraction: i32 = r.fractionDigits()
2698
3044
  const sawFraction: boolean = r.at !== beforeFraction
2699
3045
  const unit: i32 = r.peek(toI32(0)) | 32 // lowercased
2700
- r.at = r.at + 1
3046
+ r.step()
2701
3047
  const slot: i32 = temporalDurationSlot(unit, inTime)
2702
3048
  if (slot < 0 || slot >= toI32(values.length) || slot <= rank || !r.ok) {
2703
3049
  return null
2704
3050
  }
2705
3051
  rank = slot
2706
3052
  any = true
2707
- values[slot] = n
3053
+ values[slot] = toI64(n)
2708
3054
  if (sawFraction) {
2709
3055
  if (!inTime) {
2710
3056
  return null
2711
3057
  }
2712
3058
  fractionSeen = true
2713
- // The fraction of an hour, a minute or a second, spread over the smaller fields.
2714
- let ns: i64 = toI64(fraction)
3059
+ // The fraction of an hour, a minute or a second, spread over the smaller
3060
+ // fields. It is below 10^9 nanoseconds of the unit, so below an hour's
3061
+ // nanoseconds, and the `u64` product never wraps.
3062
+ let ns: u64 = toU64(fraction)
2715
3063
  if (slot === 4) {
2716
3064
  ns = ns * 3600
2717
3065
  } else if (slot === 5) {
2718
3066
  ns = ns * 60
2719
3067
  }
2720
3068
  if (slot === 4) {
2721
- values[5] = temporalTruncDiv(ns, 60 * TEMPORAL_NS_PER_SECOND)
2722
- ns = ns % (60 * TEMPORAL_NS_PER_SECOND)
3069
+ const minutes: u64 = ns / 1000000000 / 60
3070
+ values[5] = toI64(minutes)
3071
+ ns = ns - minutes * 60000000000
2723
3072
  }
2724
3073
  if (slot <= 5) {
2725
- values[6] = temporalTruncDiv(ns, TEMPORAL_NS_PER_SECOND)
2726
- ns = ns % TEMPORAL_NS_PER_SECOND
3074
+ values[6] = toI64(ns / 1000000000)
3075
+ ns = ns % 1000000000
2727
3076
  }
2728
- values[7] = temporalTruncDiv(ns, 1000000)
2729
- values[8] = temporalTruncDiv(ns, 1000) % 1000
2730
- values[9] = ns % 1000
3077
+ values[7] = toI64(ns / 1000000)
3078
+ values[8] = toI64((ns / 1000) % 1000)
3079
+ values[9] = toI64(ns % 1000)
2731
3080
  }
2732
3081
  }
2733
3082
  if (!any || !r.ok) {
2734
3083
  return null
2735
3084
  }
2736
- const k: i64 = toI64(negative ? -1 : 1)
3085
+ if (negative) {
3086
+ // Every value is below 10^16, so the wrapping negation is exact.
3087
+ for (let i: i32 = 0; i < toI32(values.length); i++) {
3088
+ values[i] = temporalNegField(values[i])
3089
+ }
3090
+ }
2737
3091
  // Fields of nine digits or fewer cannot reach any of the constructor's
2738
3092
  // bounds, so only a longer one is checked here first.
2739
3093
  const problem: string =
2740
3094
  longest <= 9
2741
3095
  ? ""
2742
3096
  : temporalDurationProblem(
2743
- values[0] * k,
2744
- values[1] * k,
2745
- values[2] * k,
2746
- values[3] * k,
2747
- values[4] * k,
2748
- values[5] * k,
2749
- values[6] * k,
2750
- values[7] * k,
2751
- values[8] * k,
2752
- values[9] * k
3097
+ values[0],
3098
+ values[1],
3099
+ values[2],
3100
+ values[3],
3101
+ values[4],
3102
+ values[5],
3103
+ values[6],
3104
+ values[7],
3105
+ values[8],
3106
+ values[9]
2753
3107
  )
2754
3108
  if (problem.length > 0) {
2755
3109
  return null
2756
3110
  }
2757
3111
  return new Duration(
2758
- values[0] * k,
2759
- values[1] * k,
2760
- values[2] * k,
2761
- values[3] * k,
2762
- values[4] * k,
2763
- values[5] * k,
2764
- values[6] * k,
2765
- values[7] * k,
2766
- values[8] * k,
2767
- values[9] * k
3112
+ values[0],
3113
+ values[1],
3114
+ values[2],
3115
+ values[3],
3116
+ values[4],
3117
+ values[5],
3118
+ values[6],
3119
+ values[7],
3120
+ values[8],
3121
+ values[9]
2768
3122
  )
2769
3123
  }
2770
3124
 
@@ -2774,13 +3128,25 @@ export const durationFromOrNull = (text: string): Duration | null => {
2774
3128
  * character. `unit` is already lowercased.
2775
3129
  */
2776
3130
  const temporalDurationSlot = (unit: i32, inTime: boolean): i32 => {
2777
- const designators: string = inTime ? "hms" : "ymwd"
2778
- for (let i: i32 = 0; i < toI32(designators.length); i++) {
2779
- if (toI32(designators.charCodeAt(i)) === unit) {
2780
- return inTime ? i + 4 : i
3131
+ if (inTime) {
3132
+ if (unit === 104) {
3133
+ return 4
3134
+ }
3135
+ if (unit === 109) {
3136
+ return 5
2781
3137
  }
3138
+ return unit === 115 ? 6 : -1
3139
+ }
3140
+ if (unit === 121) {
3141
+ return 0
2782
3142
  }
2783
- return -1
3143
+ if (unit === 109) {
3144
+ return 1
3145
+ }
3146
+ if (unit === 119) {
3147
+ return 2
3148
+ }
3149
+ return unit === 100 ? 3 : -1
2784
3150
  }
2785
3151
 
2786
3152
  /**
@@ -2845,7 +3211,7 @@ export class Instant {
2845
3211
  let seconds: i64 = epochSeconds
2846
3212
  let nanos: i64 = nanoseconds
2847
3213
  if (nanos < 0 || nanos >= TEMPORAL_NS_PER_SECOND) {
2848
- seconds = seconds + temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND)
3214
+ seconds = temporalAdd(seconds, temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND))
2849
3215
  nanos = temporalFloorMod(nanos, TEMPORAL_NS_PER_SECOND)
2850
3216
  }
2851
3217
  if (!temporalInstantInRange(seconds, nanos)) {
@@ -2853,7 +3219,8 @@ export class Instant {
2853
3219
  }
2854
3220
  this.epochSeconds = seconds
2855
3221
  this.nanosecondOfSecond = toI32(nanos)
2856
- this.epochMilliseconds = toF64(seconds * 1000 + toI64(nanos / 1000000))
3222
+ // In range, `seconds` is within ±8.64 × 10^12, so the wrapping sum is exact.
3223
+ this.epochMilliseconds = toF64(toI64(toU64(seconds) * 1000 + toU64(nanos / 1000000)))
2857
3224
  }
2858
3225
 
2859
3226
  /**
@@ -2868,7 +3235,8 @@ export class Instant {
2868
3235
  const civil: i64 = temporalCivilOfEpochDay(day)
2869
3236
  const out: u8[] = new Array<u8>(TEMPORAL_TEXT_MAX)
2870
3237
  const year: i32 = temporalCivilYear(civil)
2871
- const nanoOfDay: i64 = secondOfDay * TEMPORAL_NS_PER_SECOND + toI64(this.nanosecondOfSecond)
3238
+ // `secondOfDay` is below a day, so the `u64` sum never wraps.
3239
+ const nanoOfDay: i64 = toI64(toU64(secondOfDay) * 1000000000 + toU64(this.nanosecondOfSecond))
2872
3240
  let i: i32 = 0
2873
3241
  if (year >= 0 && year <= 9999) {
2874
3242
  const secs: i32 = toI32(secondOfDay)
@@ -2881,14 +3249,14 @@ export class Instant {
2881
3249
  temporalCivilDay(civil),
2882
3250
  toI32(minutes / 60),
2883
3251
  minutes % 60,
2884
- secs - minutes * 60
3252
+ toI32(toU32(secs) % 60)
2885
3253
  )
2886
3254
  i = temporalPutFraction(out, i, this.nanosecondOfSecond)
2887
3255
  } else {
2888
3256
  i = temporalPutDate(out, 0, year, temporalCivilMonth(civil), temporalCivilDay(civil))
2889
3257
  i = temporalPutNanoOfDay(out, temporalPutByte(out, i, 84), nanoOfDay)
2890
3258
  }
2891
- return String.fromBytes(out, 0, temporalPutByte(out, i, 90))
3259
+ return temporalText(out, temporalPutByte(out, i, 90))
2892
3260
  }
2893
3261
 
2894
3262
  /**
@@ -2923,7 +3291,10 @@ export class Instant {
2923
3291
  temporalRangeError("Instant: a duration with days or larger units cannot be added to an instant")
2924
3292
  }
2925
3293
  const span: TemporalSpan = temporalSpanOfDuration(duration, false)
2926
- return new Instant(this.epochSeconds + span.seconds, toI64(this.nanosecondOfSecond) + toI64(span.nanos))
3294
+ return new Instant(
3295
+ temporalAdd(this.epochSeconds, span.seconds),
3296
+ toI64(this.nanosecondOfSecond) + toI64(span.nanos)
3297
+ )
2927
3298
  }
2928
3299
 
2929
3300
  /**
@@ -2960,7 +3331,10 @@ export class Instant {
2960
3331
 
2961
3332
  /** The span from `a` to `b`. */
2962
3333
  const temporalInstantSpan = (a: Instant, b: Instant): TemporalSpan =>
2963
- new TemporalSpan(b.epochSeconds - a.epochSeconds, toI64(b.nanosecondOfSecond) - toI64(a.nanosecondOfSecond))
3334
+ new TemporalSpan(
3335
+ temporalSub(b.epochSeconds, a.epochSeconds),
3336
+ toI64(b.nanosecondOfSecond) - toI64(a.nanosecondOfSecond)
3337
+ )
2964
3338
 
2965
3339
  /**
2966
3340
  * `Temporal.Instant.fromEpochMilliseconds(ms)`: the instant `ms` milliseconds
@@ -2975,7 +3349,7 @@ export const instantFromEpochMilliseconds = (ms: f64): Instant => {
2975
3349
  temporalRangeError("Instant: epoch milliseconds must be a whole number within ±8.64e15")
2976
3350
  }
2977
3351
  const whole: i64 = toI64(ms)
2978
- return new Instant(temporalFloorDiv(whole, 1000), temporalFloorMod(whole, 1000) * 1000000)
3352
+ return new Instant(temporalFloorDiv(whole, 1000), toI64(toU64(temporalFloorMod(whole, 1000)) * 1000000))
2979
3353
  }
2980
3354
 
2981
3355
  /**
@@ -3024,35 +3398,38 @@ export const instantFromOrNull = (text: string): Instant | null => {
3024
3398
  ) {
3025
3399
  if (minutes >= 0 && minutes <= 59) {
3026
3400
  timeEnd = length - 6
3027
- offsetSeconds = toI64(hours * 3600 + minutes * 60) * (sign === 43 ? 1 : -1)
3401
+ const offset: u64 = toU64(hours) * 3600 + toU64(minutes) * 60
3402
+ offsetSeconds = sign === 43 ? toI64(offset) : toI64(0 - offset)
3028
3403
  }
3029
3404
  }
3030
3405
  }
3031
3406
  if (timeEnd >= 16 && temporalIsTimeDesignator(temporalCharAt(text, 10))) {
3032
3407
  const civil: i64 = temporalFastDate(text)
3033
- const nanoOfDay: i64 = civil < 0 ? -1 : temporalFastTime(text, 11, timeEnd)
3408
+ const nanoOfDay: i64 = civil < 0 ? -1 : temporalFastTime(text, timeEnd)
3034
3409
  if (nanoOfDay >= 0) {
3035
3410
  const day: i64 = temporalEpochDay(
3036
- toI64(temporalCivilYear(civil)),
3411
+ temporalCivilYear(civil),
3037
3412
  temporalCivilMonth(civil),
3038
3413
  temporalCivilDay(civil)
3039
3414
  )
3415
+ // A four-digit year keeps `day` within ±4 × 10^6 and the offset is below a
3416
+ // day, so the wrapping sum is the exact one.
3040
3417
  return new Instant(
3041
- day * TEMPORAL_SECONDS_PER_DAY + toI64(nanoOfDay / TEMPORAL_NS_PER_SECOND) - offsetSeconds,
3418
+ toI64(toU64(day) * 86400 + toU64(nanoOfDay / TEMPORAL_NS_PER_SECOND) - toU64(offsetSeconds)),
3042
3419
  nanoOfDay % TEMPORAL_NS_PER_SECOND
3043
3420
  )
3044
3421
  }
3045
3422
  }
3046
3423
  const r: TemporalReader = temporalReadDateTime(text)
3047
- if (!r.ok || !r.hasTime || (!r.utc && !r.hasOffset)) {
3424
+ if (!r.ok || !r.hasTime || (!r.utc && !r.hasOffset) || !temporalYearInRange(r.year)) {
3048
3425
  return null
3049
3426
  }
3050
- const day: i64 = temporalEpochDay(toI64(r.year), r.month, r.day)
3051
- const seconds: i64 =
3052
- day * TEMPORAL_SECONDS_PER_DAY + toI64(r.hour) * 3600 + toI64(r.minute) * 60 + toI64(r.second)
3053
- // The offset is below a day, so its nanoseconds stay below 2^53.
3054
- const nanos: i64 = toI64(r.fraction) - r.offsetNanos
3055
- const exactSeconds: i64 = seconds + temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND)
3427
+ const day: i64 = temporalEpochDay(r.year, r.month, r.day)
3428
+ // The years in range keep `day` within ±4 × 10^8 and the offset is
3429
+ // below a day, so these wrapping sums are the exact ones.
3430
+ const seconds: u64 = toU64(day) * 86400 + toU64(r.hour) * 3600 + toU64(r.minute) * 60 + toU64(r.second)
3431
+ const nanos: i64 = toI64(toU64(r.fraction) - toU64(r.offsetNanos))
3432
+ const exactSeconds: i64 = toI64(seconds + toU64(temporalFloorDiv(nanos, TEMPORAL_NS_PER_SECOND)))
3056
3433
  const exactNanos: i64 = temporalFloorMod(nanos, TEMPORAL_NS_PER_SECOND)
3057
3434
  if (!temporalInstantInRange(exactSeconds, exactNanos)) {
3058
3435
  return null
@@ -3062,8 +3439,8 @@ export const instantFromOrNull = (text: string): Instant | null => {
3062
3439
 
3063
3440
  /** Whether `seconds` and `nanos` (in `[0, 10^9)`) past the epoch are within Temporal's ±10^8 days. */
3064
3441
  const temporalInstantInRange = (seconds: i64, nanos: i64): boolean => {
3065
- const limit: i64 = TEMPORAL_MAX_EPOCH_DAY * TEMPORAL_SECONDS_PER_DAY
3066
- return seconds >= -limit && seconds <= limit && !(seconds === limit && nanos > 0)
3442
+ const limit: i64 = TEMPORAL_MAX_EPOCH_SECOND
3443
+ return seconds >= TEMPORAL_MIN_EPOCH_SECOND && seconds <= limit && !(seconds === limit && nanos > 0)
3067
3444
  }
3068
3445
 
3069
3446
  /**