metano-runtime 3.0.2 → 3.1.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.
Files changed (131) hide show
  1. package/dist/system/char-members.d.ts +23 -0
  2. package/dist/system/char-members.js +46 -0
  3. package/dist/system/collections/hash-core.d.ts +5 -0
  4. package/dist/system/collections/hash-core.js +24 -0
  5. package/dist/system/collections/helpers.d.ts +16 -3
  6. package/dist/system/collections/helpers.js +28 -2
  7. package/dist/system/collections/immutable-list-builder-core.d.ts +7 -2
  8. package/dist/system/collections/immutable-list-builder-core.js +11 -0
  9. package/dist/system/collections/immutable-list-core.d.ts +8 -0
  10. package/dist/system/collections/immutable-list-core.js +19 -1
  11. package/dist/system/collections/immutable-storage.d.ts +2 -0
  12. package/dist/system/collections/immutable-storage.js +6 -1
  13. package/dist/system/collections/interfaces.d.ts +13 -0
  14. package/dist/system/collections/list.d.ts +3 -0
  15. package/dist/system/collections/list.js +7 -0
  16. package/dist/system/collections/read-only-list.d.ts +11 -0
  17. package/dist/system/collections/read-only-list.js +26 -1
  18. package/dist/system/collections/sorted-list.d.ts +5 -0
  19. package/dist/system/collections/sorted-list.js +12 -1
  20. package/dist/system/decimal-parsing.d.ts +12 -0
  21. package/dist/system/decimal-parsing.js +86 -0
  22. package/dist/system/exceptions/index.d.ts +1 -0
  23. package/dist/system/exceptions/index.js +1 -0
  24. package/dist/system/exceptions/throw-error.d.ts +7 -0
  25. package/dist/system/exceptions/throw-error.js +9 -0
  26. package/dist/system/int64.d.ts +6 -0
  27. package/dist/system/int64.js +18 -9
  28. package/dist/system/integer-division.d.ts +12 -4
  29. package/dist/system/integer-division.js +19 -2
  30. package/dist/system/json/json-serializer.d.ts +12 -1
  31. package/dist/system/json/json-serializer.js +28 -0
  32. package/dist/system/json/json-text-writer.d.ts +17 -0
  33. package/dist/system/json/json-text-writer.js +175 -0
  34. package/dist/system/json/number-from-string.js +20 -6
  35. package/dist/system/json/numeric-converters.js +41 -0
  36. package/dist/system/linq/grouping.d.ts +12 -0
  37. package/dist/system/linq/grouping.js +42 -0
  38. package/dist/system/linq/index.d.ts +4 -3
  39. package/dist/system/linq/index.js +3 -2
  40. package/dist/system/linq/linq.js +20 -1
  41. package/dist/system/linq/lookup.d.ts +17 -0
  42. package/dist/system/linq/lookup.js +20 -0
  43. package/dist/system/linq/operators.d.ts +12 -4
  44. package/dist/system/linq/operators.js +61 -15
  45. package/dist/system/linq/terminals.d.ts +29 -2
  46. package/dist/system/linq/terminals.js +71 -3
  47. package/dist/system/linq/types.d.ts +27 -4
  48. package/dist/system/math.d.ts +7 -0
  49. package/dist/system/math.js +14 -0
  50. package/dist/system/number-parsing.d.ts +16 -4
  51. package/dist/system/number-parsing.js +21 -4
  52. package/dist-unchecked/system/char-members.d.ts +23 -0
  53. package/dist-unchecked/system/char-members.js +46 -0
  54. package/dist-unchecked/system/collections/hash-core.d.ts +5 -0
  55. package/dist-unchecked/system/collections/hash-core.js +24 -0
  56. package/dist-unchecked/system/collections/helpers.d.ts +16 -3
  57. package/dist-unchecked/system/collections/helpers.js +28 -2
  58. package/dist-unchecked/system/collections/immutable-list-builder-core.d.ts +7 -2
  59. package/dist-unchecked/system/collections/immutable-list-builder-core.js +11 -0
  60. package/dist-unchecked/system/collections/immutable-list-core.d.ts +8 -0
  61. package/dist-unchecked/system/collections/immutable-list-core.js +19 -1
  62. package/dist-unchecked/system/collections/immutable-storage.d.ts +2 -0
  63. package/dist-unchecked/system/collections/immutable-storage.js +6 -1
  64. package/dist-unchecked/system/collections/interfaces.d.ts +13 -0
  65. package/dist-unchecked/system/collections/list.d.ts +3 -0
  66. package/dist-unchecked/system/collections/list.js +7 -0
  67. package/dist-unchecked/system/collections/read-only-list.d.ts +11 -0
  68. package/dist-unchecked/system/collections/read-only-list.js +26 -1
  69. package/dist-unchecked/system/collections/sorted-list.d.ts +5 -0
  70. package/dist-unchecked/system/collections/sorted-list.js +12 -1
  71. package/dist-unchecked/system/decimal-parsing.d.ts +12 -0
  72. package/dist-unchecked/system/decimal-parsing.js +86 -0
  73. package/dist-unchecked/system/exceptions/index.d.ts +1 -0
  74. package/dist-unchecked/system/exceptions/index.js +1 -0
  75. package/dist-unchecked/system/exceptions/throw-error.d.ts +7 -0
  76. package/dist-unchecked/system/exceptions/throw-error.js +9 -0
  77. package/dist-unchecked/system/int64.d.ts +6 -0
  78. package/dist-unchecked/system/int64.js +18 -9
  79. package/dist-unchecked/system/integer-division.d.ts +12 -4
  80. package/dist-unchecked/system/integer-division.js +19 -2
  81. package/dist-unchecked/system/json/json-serializer.d.ts +12 -1
  82. package/dist-unchecked/system/json/json-serializer.js +28 -0
  83. package/dist-unchecked/system/json/json-text-writer.d.ts +17 -0
  84. package/dist-unchecked/system/json/json-text-writer.js +175 -0
  85. package/dist-unchecked/system/json/number-from-string.js +20 -6
  86. package/dist-unchecked/system/json/numeric-converters.js +41 -0
  87. package/dist-unchecked/system/linq/grouping.d.ts +12 -0
  88. package/dist-unchecked/system/linq/grouping.js +42 -0
  89. package/dist-unchecked/system/linq/index.d.ts +4 -3
  90. package/dist-unchecked/system/linq/index.js +3 -2
  91. package/dist-unchecked/system/linq/linq.js +20 -1
  92. package/dist-unchecked/system/linq/lookup.d.ts +17 -0
  93. package/dist-unchecked/system/linq/lookup.js +20 -0
  94. package/dist-unchecked/system/linq/operators.d.ts +12 -4
  95. package/dist-unchecked/system/linq/operators.js +61 -15
  96. package/dist-unchecked/system/linq/terminals.d.ts +29 -2
  97. package/dist-unchecked/system/linq/terminals.js +71 -3
  98. package/dist-unchecked/system/linq/types.d.ts +27 -4
  99. package/dist-unchecked/system/math.d.ts +7 -0
  100. package/dist-unchecked/system/math.js +14 -0
  101. package/dist-unchecked/system/number-parsing.d.ts +16 -4
  102. package/dist-unchecked/system/number-parsing.js +21 -4
  103. package/package.json +1 -1
  104. package/src/system/char-members.ts +57 -0
  105. package/src/system/collections/hash-core.ts +31 -0
  106. package/src/system/collections/helpers.ts +39 -4
  107. package/src/system/collections/immutable-list-builder-core.ts +16 -2
  108. package/src/system/collections/immutable-list-core.ts +23 -1
  109. package/src/system/collections/immutable-storage.ts +8 -1
  110. package/src/system/collections/interfaces.ts +16 -0
  111. package/src/system/collections/list.ts +9 -0
  112. package/src/system/collections/read-only-list.ts +35 -1
  113. package/src/system/collections/sorted-list.ts +15 -1
  114. package/src/system/decimal-parsing.ts +109 -0
  115. package/src/system/exceptions/index.ts +1 -0
  116. package/src/system/exceptions/throw-error.ts +9 -0
  117. package/src/system/int64.ts +27 -10
  118. package/src/system/integer-division.ts +43 -6
  119. package/src/system/json/json-serializer.ts +41 -0
  120. package/src/system/json/json-text-writer.ts +224 -0
  121. package/src/system/json/number-from-string.ts +26 -6
  122. package/src/system/json/numeric-converters.ts +55 -0
  123. package/src/system/linq/grouping.ts +77 -0
  124. package/src/system/linq/index.ts +8 -0
  125. package/src/system/linq/linq.ts +23 -1
  126. package/src/system/linq/lookup.ts +34 -0
  127. package/src/system/linq/operators.ts +78 -15
  128. package/src/system/linq/terminals.ts +85 -3
  129. package/src/system/linq/types.ts +32 -0
  130. package/src/system/math.ts +19 -0
  131. package/src/system/number-parsing.ts +24 -4
@@ -1,5 +1,5 @@
1
1
  import { type ComparisonArgument, elementEquals } from "./default-comparer.ts";
2
- import type { IList } from "./interfaces.ts";
2
+ import type { IList, IReadOnlyList } from "./interfaces.ts";
3
3
  import { List } from "./list.ts";
4
4
  import { throwArgumentOutOfRange } from "./throw-helpers.ts";
5
5
 
@@ -14,7 +14,7 @@ import { throwArgumentOutOfRange } from "./throw-helpers.ts";
14
14
  * check with .NET's default `ArgumentOutOfRangeException` text, not `List`'s.
15
15
  * Internal.
16
16
  */
17
- export abstract class ImmutableListBuilderCore<T> implements IList<T> {
17
+ export abstract class ImmutableListBuilderCore<T> implements IList<T>, IReadOnlyList<T> {
18
18
  declare readonly _list: List<T>;
19
19
 
20
20
  /** Defines `_list`, a copy of `source`; each subclass then defines its own fields. */
@@ -51,6 +51,10 @@ export abstract class ImmutableListBuilderCore<T> implements IList<T> {
51
51
  return this._list.count;
52
52
  }
53
53
 
54
+ get length(): number {
55
+ return this._list.count;
56
+ }
57
+
54
58
  get isReadOnly(): boolean {
55
59
  return false;
56
60
  }
@@ -192,6 +196,16 @@ export abstract class ImmutableListBuilderCore<T> implements IList<T> {
192
196
  this._list.copyTo(array, arrayIndex);
193
197
  }
194
198
 
199
+ /** Detached shallow copy (FR-055). */
200
+ toArray(): T[] {
201
+ return this._list.toArray();
202
+ }
203
+
204
+ /** Zero-copy live read-only view over the builder's backing array (FR-056). */
205
+ asReadOnlyJsArray(): readonly T[] {
206
+ return this._list.asReadOnlyJsArray();
207
+ }
208
+
195
209
  toJSON(): T[] {
196
210
  return this._list.toArray();
197
211
  }
@@ -5,7 +5,7 @@ import {
5
5
  type IEqualityComparer,
6
6
  } from "./default-comparer.ts";
7
7
  import type { IImmutableList } from "./immutable-interfaces.ts";
8
- import { ownsTip } from "./immutable-storage.ts";
8
+ import { detachTip, ownsTip } from "./immutable-storage.ts";
9
9
  import type { IReadOnlyList } from "./interfaces.ts";
10
10
  import { binarySearch } from "./sorted-array.ts";
11
11
 
@@ -43,6 +43,10 @@ export abstract class ImmutableListCore<T, Self extends ImmutableListCore<T, Sel
43
43
  return this._count;
44
44
  }
45
45
 
46
+ get length(): number {
47
+ return this._count;
48
+ }
49
+
46
50
  get isEmpty(): boolean {
47
51
  return this._count === 0;
48
52
  }
@@ -244,6 +248,24 @@ export abstract class ImmutableListCore<T, Self extends ImmutableListCore<T, Sel
244
248
  return this.visible();
245
249
  }
246
250
 
251
+ /**
252
+ * Read-only view over `_items`: zero-copy when this version owns the full array
253
+ * (detaching tip-append ownership so later `add` calls copy rather than mutating
254
+ * the view); falls back to a shallow copy when an older version shares a grown
255
+ * store (values are immutable, though array identity is not stable across calls).
256
+ */
257
+ asReadOnlyJsArray(): readonly T[] {
258
+ if (this._items.length !== this._count) {
259
+ return this.visible();
260
+ }
261
+
262
+ if (this._count > 0) {
263
+ detachTip(this._items);
264
+ }
265
+
266
+ return this._items;
267
+ }
268
+
247
269
  toJSON(): T[] {
248
270
  return this.visible();
249
271
  }
@@ -15,10 +15,17 @@
15
15
  import { defaultEqualityComparer, type IEqualityComparer } from "./default-comparer.ts";
16
16
  import { HashCore } from "./hash-core.ts";
17
17
 
18
+ let detachedTips: WeakSet<object> | undefined;
19
+
20
+ /** Marks `store` as exposed to a read-only view so later appends copy instead of mutating it. */
21
+ export function detachTip(store: object): void {
22
+ (detachedTips ??= new WeakSet()).add(store);
23
+ }
24
+
18
25
  /** W4-11's ownership rule: a version of `count` entries may append to `store` in place. */
19
26
  export function ownsTip(store: { readonly length: number }, count: number): boolean {
20
27
  // Empty versions can be canonical singletons: never mutate their backing store.
21
- return count > 0 && store.length === count;
28
+ return count > 0 && store.length === count && !detachedTips?.has(store);
22
29
  }
23
30
 
24
31
  /** `null` for the default equality comparer, so comparing comparers sees one default. */
@@ -7,7 +7,23 @@ export interface IReadOnlyCollection<T> extends Iterable<T> {
7
7
  readonly count: number;
8
8
  }
9
9
  export interface IReadOnlyList<T> extends IReadOnlyCollection<T> {
10
+ /** Mirrors `count` for JavaScript/TypeScript array ergonomics. */
11
+ readonly length: number;
12
+
10
13
  get(index: number): T; // ArgumentOutOfRangeException
14
+
15
+ /** Detached shallow copy of the list's elements (spec 011 FR-055). */
16
+ toArray(): T[];
17
+
18
+ /**
19
+ * Read-only view over the backing JS array (spec 011 FR-056): zero-copy and
20
+ * live for runtime array-backed list kinds (reflects later mutations of a
21
+ * mutable source; array identity is not stable for older immutable versions
22
+ * sharing a grown store), and a shallow snapshot copy when `ReadOnlyList`
23
+ * wraps a custom `IList` without `asReadOnlyJsArray()`. Read-only for the
24
+ * consumer.
25
+ */
26
+ asReadOnlyJsArray(): readonly T[];
11
27
  }
12
28
  export interface ICollection<T> extends Iterable<T> {
13
29
  readonly count: number;
@@ -135,6 +135,10 @@ export class List<T> implements IList<T>, IReadOnlyList<T> {
135
135
  return this._items.length;
136
136
  }
137
137
 
138
+ get length(): number {
139
+ return this._items.length;
140
+ }
141
+
138
142
  get isReadOnly(): boolean {
139
143
  return false;
140
144
  }
@@ -484,6 +488,11 @@ export class List<T> implements IList<T>, IReadOnlyList<T> {
484
488
  return this._items;
485
489
  }
486
490
 
491
+ /** The backing array itself, typed read-only (FR-056). */
492
+ asReadOnlyJsArray(): readonly T[] {
493
+ return this._items;
494
+ }
495
+
487
496
  /** The backing array itself, typed as a length-keeping view (FR-056). */
488
497
  asSpan(): Span<T> {
489
498
  return this._items;
@@ -92,6 +92,10 @@ export class ReadOnlyList<T> implements IList<T>, IReadOnlyList<T> {
92
92
  return isArraySource(source) ? source.length : source.count;
93
93
  }
94
94
 
95
+ get length(): number {
96
+ return this.count;
97
+ }
98
+
95
99
  get isReadOnly(): boolean {
96
100
  return true;
97
101
  }
@@ -175,8 +179,32 @@ export class ReadOnlyList<T> implements IList<T>, IReadOnlyList<T> {
175
179
  return throwReadOnly();
176
180
  }
177
181
 
182
+ /** Detached shallow copy of the source's elements (FR-055). */
183
+ toArray(): T[] {
184
+ const source = this._source;
185
+
186
+ return isArraySource(source) ? source.slice() : Array.from(source);
187
+ }
188
+
189
+ /**
190
+ * Read-only view over the source's backing array (spec 011 FR-056):
191
+ * zero-copy and live ONLY for runtime array-backed sources (a native array,
192
+ * a `List`, or a source exposing `asReadOnlyJsArray()`). For a custom `IList`
193
+ * source without `asReadOnlyJsArray()`, returns a **shallow snapshot copy**
194
+ * (not live; allocates a new array on each call).
195
+ */
196
+ asReadOnlyJsArray(): readonly T[] {
197
+ const source = this._source;
198
+
199
+ if (isArraySource(source)) {
200
+ return source;
201
+ }
202
+
203
+ return hasAsReadOnlyJsArray(source) ? source.asReadOnlyJsArray() : Array.from(source);
204
+ }
205
+
178
206
  toJSON(): T[] {
179
- return [...this];
207
+ return this.toArray();
180
208
  }
181
209
 
182
210
  /** .NET's ``System.Collections.ObjectModel.ReadOnlyCollection`1[T]`` text. */
@@ -208,3 +236,9 @@ export function asReadOnly<T>(
208
236
  function isArraySource<T>(source: IList<T> | readonly T[]): source is readonly T[] {
209
237
  return Array.isArray(source);
210
238
  }
239
+
240
+ function hasAsReadOnlyJsArray<T>(
241
+ source: IList<T>,
242
+ ): source is IList<T> & { asReadOnlyJsArray(): readonly T[] } {
243
+ return typeof (source as { asReadOnlyJsArray?: unknown }).asReadOnlyJsArray === "function";
244
+ }
@@ -459,6 +459,10 @@ export class SortedListView<T> implements IList<T>, IReadOnlyList<T> {
459
459
  return this._list.count;
460
460
  }
461
461
 
462
+ get length(): number {
463
+ return this._list.count;
464
+ }
465
+
462
466
  get isReadOnly(): true {
463
467
  return true;
464
468
  }
@@ -512,8 +516,18 @@ export class SortedListView<T> implements IList<T>, IReadOnlyList<T> {
512
516
  return throwSortedListNested();
513
517
  }
514
518
 
519
+ /** Detached shallow copy (FR-055). */
520
+ toArray(): T[] {
521
+ return this.items().slice();
522
+ }
523
+
524
+ /** Zero-copy live read-only view over the list's backing key/value array (FR-056). */
525
+ asReadOnlyJsArray(): readonly T[] {
526
+ return this.items();
527
+ }
528
+
515
529
  toJSON(): T[] {
516
- return [...this.items()];
530
+ return this.toArray();
517
531
  }
518
532
 
519
533
  [Symbol.iterator](): Iterator<T> {
@@ -63,6 +63,115 @@ export function parseDecimalText(text: string | null | undefined): string {
63
63
  return `${sign}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
64
64
  }
65
65
 
66
+ /** The largest scale of a `decimal`. */
67
+ const DECIMAL_SCALE_MAX = 28;
68
+
69
+ /** `1e0` … `1e28`, parsed so each is the exact double .NET's table holds. */
70
+ const DOUBLE_POWERS_OF_TEN = /* @__PURE__ */ lazyValue(() =>
71
+ Array.from({ length: DECIMAL_SCALE_MAX + 1 }, (_, power) => Number(`1e${power}`)),
72
+ );
73
+
74
+ /** A scratch view that reads the biased binary exponent of a `number`. */
75
+ const EXPONENT_VIEW = /* @__PURE__ */ lazyValue(() => new DataView(new ArrayBuffer(8)));
76
+
77
+ /**
78
+ * The digits of `(decimal)d` (`digits` 15) or `(decimal)f` (`digits` 7), for
79
+ * `new Decimal(…)`, ported from .NET's `VarDecFromR8` / `VarDecFromR4`
80
+ * (#695): the value is scaled by a power of ten to `digits` significant
81
+ * digits, the scale capped at 28, rounded half to even, and trailing zeros
82
+ * are dropped from the scale. So `(decimal)(0.1 + 0.2)` is `0.3`,
83
+ * `(decimal)1000000000000005.0` is `1000000000000000` and `(decimal)1e-30`
84
+ * is `0`. The scaling is done in double arithmetic, as .NET does.
85
+ *
86
+ * @throws OverflowException for NaN, ±Infinity and a magnitude of 2^96 or more.
87
+ */
88
+ export function decimalTextFromDouble(value: number, digits: 7 | 15): string {
89
+ const exponent = binaryExponentOf(value);
90
+
91
+ if (exponent < -94) {
92
+ return "0";
93
+ }
94
+
95
+ if (exponent > 96) {
96
+ throw new OverflowException(DECIMAL_RANGE_MESSAGE);
97
+ }
98
+
99
+ const lowest = DOUBLE_POWERS_OF_TEN()[digits - 1]!;
100
+ let power = digits - 1 - ((exponent * 19728) >> 16);
101
+ let scaled = Math.abs(value);
102
+
103
+ if (power >= 0) {
104
+ power = Math.min(power, DECIMAL_SCALE_MAX);
105
+ scaled *= DOUBLE_POWERS_OF_TEN()[power]!;
106
+ } else if (power !== -1 || scaled >= lowest * 10) {
107
+ scaled /= DOUBLE_POWERS_OF_TEN()[-power]!;
108
+ } else {
109
+ power = 0;
110
+ }
111
+
112
+ if (scaled < lowest && power < DECIMAL_SCALE_MAX) {
113
+ scaled *= 10;
114
+ power++;
115
+ }
116
+
117
+ const mantissa = roundHalfToEven(scaled);
118
+
119
+ if (mantissa === 0) {
120
+ return "0";
121
+ }
122
+
123
+ const sign = value < 0 ? "-" : "";
124
+
125
+ return power < 0
126
+ ? `${sign}${mantissa}${"0".repeat(-power)}`
127
+ : `${sign}${scaledText(String(mantissa), power, digits - 1)}`;
128
+ }
129
+
130
+ /**
131
+ * The exponent .NET reads from a binary floating-point value: the biased
132
+ * exponent of the double minus 1022, so `2^e ≤ |value| < 2^(e+1)` gives
133
+ * `e + 1`. A `float` held as a double reads the same exponent.
134
+ */
135
+ function binaryExponentOf(value: number): number {
136
+ const view = EXPONENT_VIEW();
137
+
138
+ view.setFloat64(0, value);
139
+
140
+ return ((view.getUint16(0) >> 4) & 0x7ff) - 1022;
141
+ }
142
+
143
+ /** `value` (below 2^53) rounded to an integer, a tie to the even one. */
144
+ function roundHalfToEven(value: number): number {
145
+ const floor = Math.floor(value);
146
+ const rest = value - floor;
147
+
148
+ return rest > 0.5 || (rest === 0.5 && floor % 2 === 1) ? floor + 1 : floor;
149
+ }
150
+
151
+ /**
152
+ * `digitsText` divided by `10^scale`, written out after up to `maxStrip`
153
+ * trailing zeros are dropped from the scale.
154
+ */
155
+ function scaledText(digitsText: string, scale: number, maxStrip: number): string {
156
+ let text = digitsText;
157
+ let remaining = scale;
158
+ let strippable = Math.min(scale, maxStrip);
159
+
160
+ while (strippable > 0 && text.endsWith("0")) {
161
+ text = text.slice(0, -1);
162
+ remaining--;
163
+ strippable--;
164
+ }
165
+
166
+ if (remaining === 0) {
167
+ return text;
168
+ }
169
+
170
+ const padded = text.padStart(remaining + 1, "0");
171
+
172
+ return `${padded.slice(0, -remaining)}.${padded.slice(-remaining)}`;
173
+ }
174
+
66
175
  function formatException(text: string): FormatException {
67
176
  return new FormatException(`The input string '${text}' was not in a correct format.`);
68
177
  }
@@ -24,3 +24,4 @@ export * from "./switch-expression-exception.ts";
24
24
  export * from "./named-exception.ts";
25
25
  export * from "./type-initialization-exception.ts";
26
26
  export * from "./to-exception.ts";
27
+ export * from "./throw-error.ts";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Throws `error` from an expression position: the tail of a lowered C#
3
+ * `switch` expression no arm matched, or an arm whose result is a throw
4
+ * expression (`_ => throw new X()`). Returning `never` lets the conditional
5
+ * chain keep the type of its other arms, with no closure allocated.
6
+ */
7
+ export function throwError(error: unknown): never {
8
+ throw error;
9
+ }
@@ -210,20 +210,37 @@ export function uint64FromDecimal(value: DecimalLike): bigint {
210
210
 
211
211
  /** Decimal to an integer of 32 bits or fewer: truncate exactly, then check even when unchecked. */
212
212
  export function narrowFromDecimal(value: DecimalLike, bits: 8 | 16 | 32, signed: boolean): number {
213
- const message = () => {
214
- const type =
215
- bits === 8
216
- ? signed
217
- ? "a signed byte"
218
- : "an unsigned byte"
219
- : `${signed ? "an Int" : "a UInt"}${bits}`;
220
- return `Value was either too large or too small for ${type}.`;
221
- };
222
- const integer = truncatedDecimal(value, message);
213
+ const type =
214
+ bits === 8
215
+ ? signed
216
+ ? "a signed byte"
217
+ : "an unsigned byte"
218
+ : `${signed ? "an Int" : "a UInt"}${bits}`;
223
219
  const width = BigInt(bits);
224
220
  const min = signed ? -(1n << (width - 1n)) : 0n;
225
221
  const max = signed ? (1n << (width - 1n)) - 1n : (1n << width) - 1n;
226
222
 
223
+ return truncatedDecimalInRange(value, min, max, type);
224
+ }
225
+
226
+ /**
227
+ * `(char)m`: the UTF-16 code of the truncated `decimal` (#695).
228
+ *
229
+ * @throws OverflowException("Value was either too large or too small for a character.") outside 0–65535.
230
+ */
231
+ export function charCodeFromDecimal(value: DecimalLike): number {
232
+ return truncatedDecimalInRange(value, 0n, 0xffffn, "a character");
233
+ }
234
+
235
+ function truncatedDecimalInRange(
236
+ value: DecimalLike,
237
+ min: bigint,
238
+ max: bigint,
239
+ type: string,
240
+ ): number {
241
+ const message = () => `Value was either too large or too small for ${type}.`;
242
+ const integer = truncatedDecimal(value, message);
243
+
227
244
  return Number(requireRange(integer, min, max, message));
228
245
  }
229
246
 
@@ -6,18 +6,18 @@
6
6
  */
7
7
 
8
8
  import { DivideByZeroException } from "./exceptions/divide-by-zero-exception.ts";
9
+ import { OverflowException } from "./exceptions/overflow-exception.ts";
10
+
11
+ const INT32_MIN = -2147483648;
9
12
 
10
13
  /**
11
14
  * Divides `dividend` by `divisor` and truncates the quotient toward zero, as C# does
12
15
  * for integral operands (`-7 / 2` is `-3`). A `null` (or `undefined`) operand yields
13
16
  * `null`, matching C#'s lifted `int?` division.
14
17
  *
15
- * Overflow is not modelled: `int.MinValue / -1` returns `2147483648` instead of
16
- * throwing `OverflowException`, and a `long` quotient beyond `Number.MAX_SAFE_INTEGER`
17
- * loses precision, like every other `long` value mapped to `number`.
18
- *
19
18
  * @throws DivideByZeroException, with .NET's message, when `divisor` is zero,
20
19
  * where a bare `Math.trunc(dividend / divisor)` would yield `Infinity` or `NaN`.
20
+ * @throws OverflowException for `int.MinValue / -1`, whose quotient does not fit `int`.
21
21
  */
22
22
  export function intDiv(dividend: number, divisor: number): number;
23
23
  export function intDiv(
@@ -32,10 +32,47 @@ export function intDiv(
32
32
  return null;
33
33
  }
34
34
 
35
+ requireInt32Division(dividend, divisor);
36
+
37
+ // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
38
+ return Math.trunc(dividend / divisor) + 0;
39
+ }
40
+
41
+ /**
42
+ * `a % b` over `int` or `uint` operands with a divisor that is not a constant:
43
+ * the remainder with the dividend's sign, as JavaScript's `%` computes it, but
44
+ * throwing where .NET throws instead of yielding `NaN` or `0` (#695). A `null`
45
+ * (or `undefined`) operand yields `null`, matching C#'s lifted `int?` remainder.
46
+ *
47
+ * @throws DivideByZeroException, with .NET's message, when `divisor` is zero.
48
+ * @throws OverflowException for `int.MinValue % -1`, as .NET does.
49
+ */
50
+ export function intRem(dividend: number, divisor: number): number;
51
+ export function intRem(
52
+ dividend: number | null | undefined,
53
+ divisor: number | null | undefined,
54
+ ): number | null;
55
+ export function intRem(
56
+ dividend: number | null | undefined,
57
+ divisor: number | null | undefined,
58
+ ): number | null {
59
+ if (dividend == null || divisor == null) {
60
+ return null;
61
+ }
62
+
63
+ requireInt32Division(dividend, divisor);
64
+
65
+ // `+ 0` turns the `-0` of `-4 % 2` into `0`.
66
+ return (dividend % divisor) + 0;
67
+ }
68
+
69
+ /** Throws what .NET throws for an `int` `/` or `%`: a zero divisor, or `int.MinValue` by `-1`. */
70
+ function requireInt32Division(dividend: number, divisor: number): void {
35
71
  if (divisor === 0) {
36
72
  throw new DivideByZeroException();
37
73
  }
38
74
 
39
- // C# integers have no negative zero: `+ 0` turns the `-0` of `-1 / 3` into `0`.
40
- return Math.trunc(dividend / divisor) + 0;
75
+ if (dividend === INT32_MIN && divisor === -1) {
76
+ throw new OverflowException();
77
+ }
41
78
  }
@@ -11,6 +11,8 @@ import { specNumberTextLeaves } from "./exact-number-reads.ts";
11
11
  import { mayHoldNumberTextLeaf, parseJsonText, readJsonText } from "./json-text-reader.ts";
12
12
  import { readNull } from "./null-reads.ts";
13
13
  import { isValueSpec } from "./spec-kind.ts";
14
+ import { writeJsonText } from "./json-text-writer.ts";
15
+ import { throwIfNull } from "../argument-guards.ts";
14
16
 
15
17
  /**
16
18
  * Serializes through either spec kind: an object contract walks its
@@ -74,6 +76,9 @@ function deserializeTextWithInfo<T>(
74
76
  spec: JsonTypeInfo<T>,
75
77
  converters?: readonly JsonConverter[],
76
78
  ): T | null {
79
+ throwIfNull(text, "json");
80
+ throwIfNull(spec, "jsonTypeInfo");
81
+
77
82
  const leaves = specNumberTextLeaves(spec);
78
83
  const readsExactTree = leaves !== undefined && mayHoldNumberTextLeaf(text, leaves);
79
84
 
@@ -84,6 +89,21 @@ function deserializeTextWithInfo<T>(
84
89
  return deserializeWithInfo(parseJsonText(text), spec, converters);
85
90
  }
86
91
 
92
+ /**
93
+ * Writes JSON text as System.Text.Json's `Serialize(value, JsonTypeInfo<T>)`
94
+ * does (#741): the tree `serialize` builds, written by `writeJsonText`
95
+ * (STJ's escaping and number text, not `JSON.stringify`'s).
96
+ */
97
+ function serializeTextWithInfo<T>(
98
+ value: T | null,
99
+ spec: JsonTypeInfo<T>,
100
+ converters?: readonly JsonConverter[],
101
+ ): string {
102
+ throwIfNull(spec, "jsonTypeInfo");
103
+
104
+ return writeJsonText(serializeWithInfo(value, spec, converters));
105
+ }
106
+
87
107
  /**
88
108
  * A bound serializer that uses a SerializerContext to resolve custom converters
89
109
  * and look up specs by constructor.
@@ -101,6 +121,11 @@ export class BoundSerializer {
101
121
  return serializeWithInfo(value, spec, this.context.converters);
102
122
  }
103
123
 
124
+ /** Serialize a value to JSON text, as System.Text.Json writes it. */
125
+ serializeText<T>(value: T | null, spec: JsonTypeInfo<T>): string {
126
+ return serializeTextWithInfo(value, spec, this.context.converters);
127
+ }
128
+
104
129
  /**
105
130
  * Deserialize a parsed JSON value into a typed instance; JSON `null` reads
106
131
  * as `null`, except for a struct contract (`valueType`), which throws
@@ -188,6 +213,22 @@ export class JsonSerializer {
188
213
  return serializeWithInfo(value, spec, converters);
189
214
  }
190
215
 
216
+ /**
217
+ * Serialize a value to JSON text using the given spec, as System.Text.Json's
218
+ * `Serialize(value, JsonTypeInfo<T>)` writes it: no whitespace, strings
219
+ * escaped by its default encoder (`<` is `\u003C`, `é` is `\u00E9`),
220
+ * numbers in .NET's round-trip text (`1E+20`), `decimal` and 64-bit
221
+ * integers with their exact digits, `null` as `null`. NaN and the
222
+ * infinities throw `ArgumentException`, as STJ throws for them.
223
+ */
224
+ static serializeText<T>(
225
+ value: T | null,
226
+ spec: JsonTypeInfo<T>,
227
+ converters?: readonly JsonConverter[],
228
+ ): string {
229
+ return serializeTextWithInfo(value, spec, converters);
230
+ }
231
+
191
232
  /**
192
233
  * Deserialize a parsed JSON value (`JSON.parse`'s tree) into a typed
193
234
  * instance using the given spec. `JSON.parse` has already rounded every