metano-runtime 3.1.0 → 3.3.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 (73) hide show
  1. package/dist/system/comparable-compare-to.d.ts +12 -0
  2. package/dist/system/comparable-compare-to.js +20 -0
  3. package/dist/system/disposable.d.ts +15 -0
  4. package/dist/system/disposable.js +15 -0
  5. package/dist/system/hash-code.d.ts +2 -1
  6. package/dist/system/hash-code.js +5 -2
  7. package/dist/system/index.d.ts +4 -0
  8. package/dist/system/index.js +4 -0
  9. package/dist/system/int64-math.js +2 -1
  10. package/dist/system/json/index.d.ts +1 -1
  11. package/dist/system/json/json-serializer.js +3 -2
  12. package/dist/system/json/json-text-writer.d.ts +10 -3
  13. package/dist/system/json/json-text-writer.js +48 -16
  14. package/dist/system/json/ordinal-ignore-case.d.ts +2 -0
  15. package/dist/system/json/ordinal-ignore-case.js +1 -1
  16. package/dist/system/json/serializer-context.d.ts +13 -7
  17. package/dist/system/json/serializer-context.js +23 -11
  18. package/dist/system/json/types.d.ts +20 -0
  19. package/dist/system/math.d.ts +20 -0
  20. package/dist/system/math.js +31 -0
  21. package/dist/system/min-max.d.ts +6 -0
  22. package/dist/system/min-max.js +10 -0
  23. package/dist/system/string-comparison.d.ts +56 -0
  24. package/dist/system/string-comparison.js +225 -0
  25. package/dist/system/string-hash-code.d.ts +14 -0
  26. package/dist/system/string-hash-code.js +37 -0
  27. package/dist/system/string-members.d.ts +5 -4
  28. package/dist/system/string-members.js +12 -11
  29. package/dist-unchecked/system/comparable-compare-to.d.ts +12 -0
  30. package/dist-unchecked/system/comparable-compare-to.js +20 -0
  31. package/dist-unchecked/system/disposable.d.ts +15 -0
  32. package/dist-unchecked/system/disposable.js +15 -0
  33. package/dist-unchecked/system/hash-code.d.ts +2 -1
  34. package/dist-unchecked/system/hash-code.js +5 -2
  35. package/dist-unchecked/system/index.d.ts +4 -0
  36. package/dist-unchecked/system/index.js +4 -0
  37. package/dist-unchecked/system/int64-math.js +2 -1
  38. package/dist-unchecked/system/json/index.d.ts +1 -1
  39. package/dist-unchecked/system/json/json-serializer.js +3 -2
  40. package/dist-unchecked/system/json/json-text-writer.d.ts +10 -3
  41. package/dist-unchecked/system/json/json-text-writer.js +48 -16
  42. package/dist-unchecked/system/json/ordinal-ignore-case.d.ts +2 -0
  43. package/dist-unchecked/system/json/ordinal-ignore-case.js +1 -1
  44. package/dist-unchecked/system/json/serializer-context.d.ts +13 -7
  45. package/dist-unchecked/system/json/serializer-context.js +23 -11
  46. package/dist-unchecked/system/json/types.d.ts +20 -0
  47. package/dist-unchecked/system/math.d.ts +20 -0
  48. package/dist-unchecked/system/math.js +31 -0
  49. package/dist-unchecked/system/min-max.d.ts +6 -0
  50. package/dist-unchecked/system/min-max.js +10 -0
  51. package/dist-unchecked/system/string-comparison.d.ts +56 -0
  52. package/dist-unchecked/system/string-comparison.js +225 -0
  53. package/dist-unchecked/system/string-hash-code.d.ts +14 -0
  54. package/dist-unchecked/system/string-hash-code.js +37 -0
  55. package/dist-unchecked/system/string-members.d.ts +5 -4
  56. package/dist-unchecked/system/string-members.js +12 -11
  57. package/package.json +1 -1
  58. package/src/system/comparable-compare-to.ts +23 -0
  59. package/src/system/disposable.ts +27 -0
  60. package/src/system/hash-code.ts +7 -2
  61. package/src/system/index.ts +4 -0
  62. package/src/system/int64-math.ts +2 -1
  63. package/src/system/json/index.ts +1 -0
  64. package/src/system/json/json-serializer.ts +3 -2
  65. package/src/system/json/json-text-writer.ts +74 -16
  66. package/src/system/json/ordinal-ignore-case.ts +1 -1
  67. package/src/system/json/serializer-context.ts +28 -11
  68. package/src/system/json/types.ts +21 -0
  69. package/src/system/math.ts +44 -0
  70. package/src/system/min-max.ts +11 -0
  71. package/src/system/string-comparison.ts +299 -0
  72. package/src/system/string-hash-code.ts +44 -0
  73. package/src/system/string-members.ts +12 -11
@@ -0,0 +1,225 @@
1
+ /**
2
+ * C#'s `string.Equals` and `string.Compare` with a `StringComparison` (#769), and the
3
+ * overloads that imply one (`Compare(a, b)` and `CompareTo` are culture-sensitive,
4
+ * `CompareOrdinal` is ordinal).
5
+ *
6
+ * - `Ordinal` compares UTF-16 code units.
7
+ * - `OrdinalIgnoreCase` compares the ordinal uppercase of each code point
8
+ * (`ordinalUppercaseOf`: .NET's invariant simple case mapping, so `ß` never equals
9
+ * `SS` and `ı` never equals `I`), not a whole-string `toLowerCase()`.
10
+ * - The culture members compare with `Intl.Collator`: `CurrentCulture` with the
11
+ * engine's default locale, `InvariantCulture` with the root locale, at `variant`
12
+ * sensitivity. The ignore-case members ignore case only, as .NET does on ICU: the
13
+ * strings first compare at `accent` sensitivity (which also ignores width and kana),
14
+ * and strings equal there are told apart by width and kana alone
15
+ * (`caseInsensitiveKey`), so `"A"` never equals `"a"` while `"A"` equals `"a"`,
16
+ * `ß` equals `ẞ` and `ff` equals `FF`. Measured against .NET 10 on ICU, five exotic
17
+ * pairs still differ (known gaps): `İ` / `i̇` and `ガ` / `ガ` and U+FFE8 / `│` (.NET
18
+ * equal), and small against full-size kana (`ア` / `ァ`, `ア` / `ァ`: the sign).
19
+ *
20
+ * The instance forms (`a.Equals(b, comparison)`, `a.Equals(b)`, `a.CompareTo(b)`) throw
21
+ * `NullReferenceException` for a `null` receiver, as .NET does; `CompareTo(object)`
22
+ * throws `ArgumentException` for an argument that is not a string.
23
+ *
24
+ * `null` equals only `null` and sorts before every string, as in .NET. A `Compare`
25
+ * result has .NET's sign; .NET leaves the magnitude unspecified, so the ordinal forms
26
+ * return the difference of the first code units that differ, or of the lengths.
27
+ */
28
+ import { ArgumentException } from "./exceptions/argument-exception.js";
29
+ import { NullReferenceException } from "./exceptions/null-reference-exception.js";
30
+ import { ordinalUppercaseOf } from "./json/ordinal-ignore-case.js";
31
+ import { StringComparison } from "./string-members.js";
32
+ const UNSUPPORTED_COMPARISON_MESSAGE = "The string comparison type passed in is currently not supported.";
33
+ const NOT_A_STRING_MESSAGE = "Object must be of type String.";
34
+ const FIRST_SUPPLEMENTARY_CODE_POINT = 0x10000;
35
+ /* Built on first use, one per culture member, so importing the module runs no code. */
36
+ const cultureCollators = [];
37
+ /** The collator for a culture member (`CurrentCulture` to `InvariantCultureIgnoreCase`). */
38
+ function collatorFor(comparison) {
39
+ const isInvariant = comparison >= StringComparison.InvariantCulture;
40
+ const ignoresCase = comparison % 2 === 1;
41
+ return (cultureCollators[comparison] ??= new Intl.Collator(isInvariant ? "und" : undefined, {
42
+ sensitivity: ignoresCase ? "accent" : "variant",
43
+ }));
44
+ }
45
+ /** @throws ArgumentException when `comparison` is not a `StringComparison` member. */
46
+ function requireComparison(comparison) {
47
+ const isMember = Number.isInteger(comparison) &&
48
+ comparison >= StringComparison.CurrentCulture &&
49
+ comparison <= StringComparison.OrdinalIgnoreCase;
50
+ if (!isMember) {
51
+ throw new ArgumentException(UNSUPPORTED_COMPARISON_MESSAGE, "comparisonType");
52
+ }
53
+ }
54
+ /** The ordinal uppercase code point of the code point at `index` in `value`. */
55
+ function foldedCodePointAt(value, index) {
56
+ const unit = value.charCodeAt(index);
57
+ if (unit < 0x80) {
58
+ return unit >= 0x61 && unit <= 0x7a ? unit - 0x20 : unit;
59
+ }
60
+ const codePoint = value.codePointAt(index);
61
+ return ordinalUppercaseOf(String.fromCodePoint(codePoint)).codePointAt(0);
62
+ }
63
+ function compareOrdinal(left, right) {
64
+ const length = Math.min(left.length, right.length);
65
+ for (let index = 0; index < length; index++) {
66
+ const difference = left.charCodeAt(index) - right.charCodeAt(index);
67
+ if (difference !== 0) {
68
+ return difference;
69
+ }
70
+ }
71
+ return left.length - right.length;
72
+ }
73
+ /**
74
+ * Walks both strings code point by code point; a supplementary code point orders by its
75
+ * value (above every BMP one), as .NET's case-insensitive comparison does.
76
+ */
77
+ function compareOrdinalIgnoreCase(left, right) {
78
+ let leftIndex = 0;
79
+ let rightIndex = 0;
80
+ while (leftIndex < left.length && rightIndex < right.length) {
81
+ const leftFolded = foldedCodePointAt(left, leftIndex);
82
+ const rightFolded = foldedCodePointAt(right, rightIndex);
83
+ if (leftFolded !== rightFolded) {
84
+ const isSupplementary = leftFolded >= FIRST_SUPPLEMENTARY_CODE_POINT ||
85
+ rightFolded >= FIRST_SUPPLEMENTARY_CODE_POINT;
86
+ return isSupplementary ? Math.sign(leftFolded - rightFolded) : leftFolded - rightFolded;
87
+ }
88
+ leftIndex += left.codePointAt(leftIndex) >= FIRST_SUPPLEMENTARY_CODE_POINT ? 2 : 1;
89
+ rightIndex +=
90
+ right.codePointAt(rightIndex) >= FIRST_SUPPLEMENTARY_CODE_POINT ? 2 : 1;
91
+ }
92
+ return left.length - leftIndex - (right.length - rightIndex);
93
+ }
94
+ /** Two non-null strings under `comparison`, already checked. */
95
+ function compareWith(left, right, comparison) {
96
+ switch (comparison) {
97
+ case StringComparison.Ordinal:
98
+ return compareOrdinal(left, right);
99
+ case StringComparison.OrdinalIgnoreCase:
100
+ return compareOrdinalIgnoreCase(left, right);
101
+ case StringComparison.CurrentCultureIgnoreCase:
102
+ case StringComparison.InvariantCultureIgnoreCase:
103
+ return compareCultureIgnoringCase(left, right, comparison);
104
+ default:
105
+ return collatorFor(comparison).compare(left, right);
106
+ }
107
+ }
108
+ /**
109
+ * .NET's culture `IgnoreCase` on ICU ignores case but not width (`A` / `a`, `カ` / `カ`)
110
+ * or kana type (`あ` / `ア`), which `accent` sensitivity ignores too. Strings that differ
111
+ * at `accent` sensitivity keep that order; strings equal there compare their
112
+ * case-insensitive keys at `variant` sensitivity, where only width and kana remain.
113
+ */
114
+ function compareCultureIgnoringCase(left, right, comparison) {
115
+ const primary = collatorFor(comparison).compare(left, right);
116
+ if (primary !== 0) {
117
+ return primary;
118
+ }
119
+ const caseSensitive = (comparison - 1);
120
+ return collatorFor(caseSensitive).compare(caseInsensitiveKey(left), caseInsensitiveKey(right));
121
+ }
122
+ /**
123
+ * `value` with every difference .NET's culture `IgnoreCase` ignores removed: each code
124
+ * point outside the halfwidth and fullwidth forms is replaced by its compatibility
125
+ * decomposition (`ff` → `ff`, `①` → `1`, U+3000 → space) in a single case (simple
126
+ * uppercase, then simple lowercase: `ς` and `Σ` → `σ`, `ẞ` → `ß`). A width form keeps
127
+ * its width and only folds its case (`A` → `a`).
128
+ */
129
+ function caseInsensitiveKey(value) {
130
+ let key = "";
131
+ for (const character of value) {
132
+ if (isWidthForm(character.codePointAt(0))) {
133
+ key += singleCase(character);
134
+ continue;
135
+ }
136
+ for (const part of character.normalize("NFKC")) {
137
+ key += singleCase(part);
138
+ }
139
+ }
140
+ return key;
141
+ }
142
+ /** The Halfwidth and Fullwidth Forms block. */
143
+ function isWidthForm(codePoint) {
144
+ return codePoint >= 0xff00 && codePoint <= 0xffef;
145
+ }
146
+ function singleCase(character) {
147
+ const upper = simpleMapping(character, character.toUpperCase());
148
+ return simpleMapping(upper, upper.toLowerCase());
149
+ }
150
+ /** `mapped` when it is one code point (the simple mapping), else `character`. */
151
+ function simpleMapping(character, mapped) {
152
+ return mapped.length === character.length || [...mapped].length === 1 ? mapped : character;
153
+ }
154
+ /**
155
+ * C#'s `string.Equals(a, b, comparison)` and `a.Equals(b, comparison)`.
156
+ *
157
+ * @throws ArgumentException when `comparison` is not a `StringComparison` member.
158
+ */
159
+ export function stringEquals(left, right, comparison) {
160
+ requireComparison(comparison);
161
+ if (left === right) {
162
+ return true;
163
+ }
164
+ if (left === null || right === null || comparison === StringComparison.Ordinal) {
165
+ return false;
166
+ }
167
+ if (comparison === StringComparison.OrdinalIgnoreCase && left.length !== right.length) {
168
+ return false;
169
+ }
170
+ return compareWith(left, right, comparison) === 0;
171
+ }
172
+ /**
173
+ * C#'s `string.Compare(a, b, comparison)` and the overloads that imply a comparison:
174
+ * `Compare(a, b)`, `Compare(a, b, ignoreCase)`, `CompareOrdinal(a, b)`, `a.CompareTo(b)`.
175
+ *
176
+ * @throws ArgumentException when `comparison` is not a `StringComparison` member.
177
+ */
178
+ export function stringCompare(left, right, comparison) {
179
+ requireComparison(comparison);
180
+ if (left === right) {
181
+ return 0;
182
+ }
183
+ if (left === null) {
184
+ return -1;
185
+ }
186
+ if (right === null) {
187
+ return 1;
188
+ }
189
+ return compareWith(left, right, comparison);
190
+ }
191
+ /** @throws NullReferenceException when the receiver of an instance call is `null`. */
192
+ function requireReceiver(value) {
193
+ if (value == null) {
194
+ throw new NullReferenceException();
195
+ }
196
+ return value;
197
+ }
198
+ /**
199
+ * C#'s `a.Equals(b, comparison)` and `a.Equals(b)` (ordinal).
200
+ *
201
+ * @throws NullReferenceException when `value` is `null`.
202
+ * @throws ArgumentException when `comparison` is not a `StringComparison` member.
203
+ */
204
+ export function stringInstanceEquals(value, other, comparison) {
205
+ const receiver = requireReceiver(value);
206
+ if (other === null || other === undefined || typeof other === "string") {
207
+ return stringEquals(receiver, other ?? null, comparison);
208
+ }
209
+ requireComparison(comparison);
210
+ return false;
211
+ }
212
+ /**
213
+ * C#'s `a.CompareTo(b)` for a `string` or `object` argument: a culture-sensitive
214
+ * comparison; `null` sorts first.
215
+ *
216
+ * @throws NullReferenceException when `value` is `null`.
217
+ * @throws ArgumentException when `other` is neither `null` nor a string.
218
+ */
219
+ export function stringCompareTo(value, other) {
220
+ const receiver = requireReceiver(value);
221
+ if (other !== null && other !== undefined && typeof other !== "string") {
222
+ throw new ArgumentException(NOT_A_STRING_MESSAGE);
223
+ }
224
+ return stringCompare(receiver, other ?? null, StringComparison.CurrentCulture);
225
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * C#'s `value.GetHashCode(comparison)` (#769): the hash `StringComparer.Ordinal` or
3
+ * `StringComparer.OrdinalIgnoreCase` gives, so strings equal under the comparison hash
4
+ * alike. JavaScript has no culture sort key, so a culture-sensitive comparison throws
5
+ * `NotSupportedException` instead of returning a hash that disagrees with
6
+ * `string.Equals(a, b, comparison)`.
7
+ */
8
+ import { StringComparison } from "./string-members.ts";
9
+ /**
10
+ * @throws NullReferenceException when `value` is `null`.
11
+ * @throws ArgumentException when `comparison` is not a `StringComparison` member.
12
+ * @throws NotSupportedException for a culture-sensitive comparison.
13
+ */
14
+ export declare function stringHashCode(value: string | null, comparison: StringComparison): number;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * C#'s `value.GetHashCode(comparison)` (#769): the hash `StringComparer.Ordinal` or
3
+ * `StringComparer.OrdinalIgnoreCase` gives, so strings equal under the comparison hash
4
+ * alike. JavaScript has no culture sort key, so a culture-sensitive comparison throws
5
+ * `NotSupportedException` instead of returning a hash that disagrees with
6
+ * `string.Equals(a, b, comparison)`.
7
+ */
8
+ import { StringComparer } from "./collections/string-comparer.js";
9
+ import { ArgumentException } from "./exceptions/argument-exception.js";
10
+ import { NotSupportedException } from "./exceptions/not-supported-exception.js";
11
+ import { NullReferenceException } from "./exceptions/null-reference-exception.js";
12
+ import { StringComparison } from "./string-members.js";
13
+ const UNSUPPORTED_COMPARISON_MESSAGE = "The string comparison type passed in is currently not supported.";
14
+ const CULTURE_HASH_MESSAGE = "GetHashCode with a culture-sensitive StringComparison is not supported in JavaScript.";
15
+ /**
16
+ * @throws NullReferenceException when `value` is `null`.
17
+ * @throws ArgumentException when `comparison` is not a `StringComparison` member.
18
+ * @throws NotSupportedException for a culture-sensitive comparison.
19
+ */
20
+ export function stringHashCode(value, comparison) {
21
+ if (value == null) {
22
+ throw new NullReferenceException();
23
+ }
24
+ switch (comparison) {
25
+ case StringComparison.Ordinal:
26
+ return StringComparer.ordinal.getHashCode(value);
27
+ case StringComparison.OrdinalIgnoreCase:
28
+ return StringComparer.ordinalIgnoreCase.getHashCode(value);
29
+ case StringComparison.CurrentCulture:
30
+ case StringComparison.CurrentCultureIgnoreCase:
31
+ case StringComparison.InvariantCulture:
32
+ case StringComparison.InvariantCultureIgnoreCase:
33
+ throw new NotSupportedException(CULTURE_HASH_MESSAGE);
34
+ default:
35
+ throw new ArgumentException(UNSUPPORTED_COMPARISON_MESSAGE, "comparisonType");
36
+ }
37
+ }
@@ -8,10 +8,11 @@
8
8
  * JavaScript clamps or swaps. The compiler maps each member here declaratively
9
9
  * (`Metano/Runtime/Strings.cs`); every helper reads its arguments once.
10
10
  *
11
- * Comparisons are ordinal. The culture-sensitive `StringComparison` members behave as
12
- * their ordinal counterparts (JavaScript has no culture-aware comparison), and a
13
- * case-insensitive comparison folds each UTF-16 code unit by its invariant upper-case
14
- * form, as `OrdinalIgnoreCase` does.
11
+ * Searches are ordinal. The culture-sensitive `StringComparison` members behave as
12
+ * their ordinal counterparts (JavaScript has no culture-aware substring search), and a
13
+ * case-insensitive search folds each code point by its ordinal uppercase, as
14
+ * `OrdinalIgnoreCase` does (`ordinalUppercaseOf`, shared with `StringComparer`).
15
+ * `Equals` and `Compare` with a comparison live in `string-comparison.ts`.
15
16
  */
16
17
  /**
17
18
  * Mirror of `System.StringComparison`. The numeric values match the .NET enum, so a
@@ -8,14 +8,16 @@
8
8
  * JavaScript clamps or swaps. The compiler maps each member here declaratively
9
9
  * (`Metano/Runtime/Strings.cs`); every helper reads its arguments once.
10
10
  *
11
- * Comparisons are ordinal. The culture-sensitive `StringComparison` members behave as
12
- * their ordinal counterparts (JavaScript has no culture-aware comparison), and a
13
- * case-insensitive comparison folds each UTF-16 code unit by its invariant upper-case
14
- * form, as `OrdinalIgnoreCase` does.
11
+ * Searches are ordinal. The culture-sensitive `StringComparison` members behave as
12
+ * their ordinal counterparts (JavaScript has no culture-aware substring search), and a
13
+ * case-insensitive search folds each code point by its ordinal uppercase, as
14
+ * `OrdinalIgnoreCase` does (`ordinalUppercaseOf`, shared with `StringComparer`).
15
+ * `Equals` and `Compare` with a comparison live in `string-comparison.ts`.
15
16
  */
16
17
  import { ArgumentException } from "./exceptions/argument-exception.js";
17
18
  import { ArgumentNullException } from "./exceptions/argument-null-exception.js";
18
19
  import { ArgumentOutOfRangeException } from "./exceptions/argument-out-of-range-exception.js";
20
+ import { ordinalUppercaseOf } from "./json/ordinal-ignore-case.js";
19
21
  import { isDotNetWhiteSpace } from "./strings.js";
20
22
  /**
21
23
  * Mirror of `System.StringComparison`. The numeric values match the .NET enum, so a
@@ -49,16 +51,15 @@ function ignoresCase(comparison) {
49
51
  comparison === StringComparison.OrdinalIgnoreCase);
50
52
  }
51
53
  /**
52
- * `value` with each UTF-16 code unit replaced by its invariant upper-case form when that
53
- * form is a single unit, so the result has the length of `value` and an index into one
54
- * is an index into the other.
54
+ * `value` with each code point replaced by its ordinal uppercase when that has the same
55
+ * UTF-16 length, so the result has the length of `value` and an index into one is an
56
+ * index into the other.
55
57
  */
56
58
  function foldCase(value) {
57
59
  let folded = "";
58
- for (let index = 0; index < value.length; index++) {
59
- const unit = value[index];
60
- const upper = unit.toUpperCase();
61
- folded += upper.length === 1 ? upper : unit;
60
+ for (const character of value) {
61
+ const upper = ordinalUppercaseOf(character);
62
+ folded += upper.length === character.length ? upper : character;
62
63
  }
63
64
  return folded;
64
65
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * C#'s `IComparable<T>.CompareTo` / `IComparable.CompareTo` called through the interface
3
+ * or a type parameter (`((IComparable<string>)s).CompareTo(t)`, `a.CompareTo(b)` with
4
+ * `T : IComparable<T>`): the receiver may be a string or a number, which have no
5
+ * `compareTo` method in JavaScript (#769). A string compares culture-sensitively, as
6
+ * `string.CompareTo` does; any other value goes through `Comparer<T>.Default`'s order
7
+ * (`defaultCompare`), which calls the receiver's own `compareTo` for an object. A `null`
8
+ * `other` answers `1` without calling it, as the `IComparable` contract requires: a user
9
+ * `CompareTo(null)` that returns anything else is not reproduced.
10
+ */
11
+ /** @throws NullReferenceException when `value` is `null`. */
12
+ export declare function comparableCompareTo(value: unknown, other: unknown): number;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * C#'s `IComparable<T>.CompareTo` / `IComparable.CompareTo` called through the interface
3
+ * or a type parameter (`((IComparable<string>)s).CompareTo(t)`, `a.CompareTo(b)` with
4
+ * `T : IComparable<T>`): the receiver may be a string or a number, which have no
5
+ * `compareTo` method in JavaScript (#769). A string compares culture-sensitively, as
6
+ * `string.CompareTo` does; any other value goes through `Comparer<T>.Default`'s order
7
+ * (`defaultCompare`), which calls the receiver's own `compareTo` for an object. A `null`
8
+ * `other` answers `1` without calling it, as the `IComparable` contract requires: a user
9
+ * `CompareTo(null)` that returns anything else is not reproduced.
10
+ */
11
+ import { defaultCompare } from "./collections/default-comparer.js";
12
+ import { NullReferenceException } from "./exceptions/null-reference-exception.js";
13
+ import { stringCompareTo } from "./string-comparison.js";
14
+ /** @throws NullReferenceException when `value` is `null`. */
15
+ export function comparableCompareTo(value, other) {
16
+ if (value === null || value === undefined) {
17
+ throw new NullReferenceException();
18
+ }
19
+ return typeof value === "string" ? stringCompareTo(value, other) : defaultCompare(value, other);
20
+ }
@@ -0,0 +1,15 @@
1
+ import type { InterfaceType } from "./reflection/runtime-type.ts";
2
+ /**
3
+ * C# `System.IDisposable` (spec FR-111): `Dispose()` lowers to `dispose()`, and a C# `using`
4
+ * lowers to `try`/`finally` around the resource. There is no `Symbol.dispose` alias: stable
5
+ * Safari has none, and `using` disposal wraps errors in `SuppressedError`, unlike .NET.
6
+ */
7
+ export interface IDisposable {
8
+ dispose(): void;
9
+ }
10
+ /**
11
+ * The descriptor of {@link IDisposable}. The test is nominal, as in .NET: a value is
12
+ * `IDisposable` only when its class descriptor lists the interface, never because it has a
13
+ * `dispose` method.
14
+ */
15
+ export declare const IDisposable$runtimeType: InterfaceType<IDisposable>;
@@ -0,0 +1,15 @@
1
+ import { implementsInterface } from "./reflection/implements-interface.js";
2
+ /**
3
+ * The descriptor of {@link IDisposable}. The test is nominal, as in .NET: a value is
4
+ * `IDisposable` only when its class descriptor lists the interface, never because it has a
5
+ * `dispose` method.
6
+ */
7
+ export const IDisposable$runtimeType = {
8
+ kind: "interface",
9
+ name: "IDisposable",
10
+ fullName: "System.IDisposable",
11
+ namespace: "System",
12
+ baseInterfaces: [],
13
+ plainImplementers: [],
14
+ test: (value) => implementsInterface(value, IDisposable$runtimeType),
15
+ };
@@ -21,7 +21,8 @@ export declare class HashCode {
21
21
  constructor();
22
22
  add(value: unknown): void;
23
23
  toHashCode(): number;
24
- static combine(v1: unknown): number;
24
+ /** `HashCode.Combine(v1 … v8)` (#749): the same accumulation as {@link add} per value. */
25
+ static combine(...values: unknown[]): number;
25
26
  static combine2(v1: unknown, v2: unknown): number;
26
27
  static combine3(v1: unknown, v2: unknown, v3: unknown): number;
27
28
  static combine4(v1: unknown, v2: unknown, v3: unknown, v4: unknown): number;
@@ -150,9 +150,12 @@ export class HashCode {
150
150
  return hash;
151
151
  }
152
152
  // ─── Static combine helpers ───────────────────────────────
153
- static combine(v1) {
153
+ /** `HashCode.Combine(v1 … v8)` (#749): the same accumulation as {@link add} per value. */
154
+ static combine(...values) {
154
155
  const hc = new HashCode();
155
- hc.add(v1);
156
+ for (const value of values) {
157
+ hc.add(value);
158
+ }
156
159
  return hc.toHashCode();
157
160
  }
158
161
  static combine2(v1, v2) {
@@ -28,6 +28,9 @@ export * from "./math.ts";
28
28
  export * from "./number-parsing.ts";
29
29
  export * from "./strings.ts";
30
30
  export * from "./string-members.ts";
31
+ export * from "./string-comparison.ts";
32
+ export * from "./string-hash-code.ts";
33
+ export * from "./comparable-compare-to.ts";
31
34
  export * from "./decimal-parsing.ts";
32
35
  export * from "./array-length.ts";
33
36
  export * from "./argument-guards.ts";
@@ -38,3 +41,4 @@ export * from "./char-members.ts";
38
41
  export * from "./string-builder.ts";
39
42
  export * from "./lazy.ts";
40
43
  export * from "./task-completion-source.ts";
44
+ export * from "./disposable.ts";
@@ -28,6 +28,9 @@ export * from "./math.js";
28
28
  export * from "./number-parsing.js";
29
29
  export * from "./strings.js";
30
30
  export * from "./string-members.js";
31
+ export * from "./string-comparison.js";
32
+ export * from "./string-hash-code.js";
33
+ export * from "./comparable-compare-to.js";
31
34
  export * from "./decimal-parsing.js";
32
35
  export * from "./array-length.js";
33
36
  export * from "./argument-guards.js";
@@ -38,3 +41,4 @@ export * from "./char-members.js";
38
41
  export * from "./string-builder.js";
39
42
  export * from "./lazy.js";
40
43
  export * from "./task-completion-source.js";
44
+ export * from "./disposable.js";
@@ -6,6 +6,7 @@
6
6
  * every 64-bit overload here.
7
7
  */
8
8
  import { ArgumentException, OverflowException } from "./exceptions/index.js";
9
+ import { throwMinGreaterThanMax } from "./min-max.js";
9
10
  import { divInt64, divUInt64, INT64_MIN, remInt64, remUInt64 } from "./int64.js";
10
11
  /** .NET's message for `Math.Abs(long.MinValue)`. */
11
12
  const NEGATE_MIN_VALUE_MESSAGE = "Negating the minimum value of a twos complement number is invalid.";
@@ -103,7 +104,7 @@ export function compareInt64(left, right) {
103
104
  }
104
105
  function clamp(value, min, max) {
105
106
  if (min > max) {
106
- throw new ArgumentException(`'${min}' cannot be greater than ${max}.`);
107
+ throwMinGreaterThanMax(min, max);
107
108
  }
108
109
  return maxInt64(min, minInt64(value, max));
109
110
  }
@@ -1,4 +1,4 @@
1
- export type { TypeDescriptor, PrimitiveDescriptor, Int64Descriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, BytesDescriptor, ArrayDescriptor, KeyedCollectionDescriptor, SequenceCollectionDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, TypeDiscriminator, UnknownDerivedTypeHandling, DerivedTypeSpec, PolymorphismSpec, JsonReadOptions, NumberTypeName, JsonConverter, SerializerContextOptions, } from "./types.ts";
1
+ export type { TypeDescriptor, PrimitiveDescriptor, Int64Descriptor, RefDescriptor, TemporalDescriptor, DecimalDescriptor, BytesDescriptor, ArrayDescriptor, KeyedCollectionDescriptor, SequenceCollectionDescriptor, BrandedDescriptor, EnumDescriptor, NumericEnumDescriptor, NullableDescriptor, PropertySpec, TypeSpec, ValueSpec, JsonTypeInfo, TypeDiscriminator, UnknownDerivedTypeHandling, DerivedTypeSpec, PolymorphismSpec, JsonReadOptions, JsonWriteOptions, NumberTypeName, JsonConverter, SerializerContextOptions, } from "./types.ts";
2
2
  export { SerializerContext } from "./serializer-context.ts";
3
3
  export { JsonSerializer, BoundSerializer } from "./json-serializer.ts";
4
4
  export { PropertyNamingPolicy } from "./property-naming-policy.ts";
@@ -60,11 +60,12 @@ function deserializeTextWithInfo(text, spec, converters) {
60
60
  /**
61
61
  * Writes JSON text as System.Text.Json's `Serialize(value, JsonTypeInfo<T>)`
62
62
  * does (#741): the tree `serialize` builds, written by `writeJsonText`
63
- * (STJ's escaping and number text, not `JSON.stringify`'s).
63
+ * (STJ's escaping and number text, not `JSON.stringify`'s), laid out as the spec's
64
+ * `writeOptions` say (`WriteIndented` and friends, #752).
64
65
  */
65
66
  function serializeTextWithInfo(value, spec, converters) {
66
67
  throwIfNull(spec, "jsonTypeInfo");
67
- return writeJsonText(serializeWithInfo(value, spec, converters));
68
+ return writeJsonText(serializeWithInfo(value, spec, converters), spec.writeOptions);
68
69
  }
69
70
  /**
70
71
  * A bound serializer that uses a SerializerContext to resolve custom converters
@@ -3,7 +3,10 @@
3
3
  * System.Text.Json's `JsonSerializer.Serialize(value, JsonTypeInfo<T>)`
4
4
  * writes with its default options (#741, measured on .NET 10):
5
5
  *
6
- * - no whitespace;
6
+ * - no whitespace, unless the context writes indented text (#752): `writeIndented` puts each
7
+ * array element and each property on its own line, indented by `indentSize` copies of
8
+ * `indentCharacter` per level (a space and 2 by default), with `newLine` (`"\n"` by default)
9
+ * between lines, `": "` after a property name, and `[]` / `{}` for an empty container;
7
10
  * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
8
11
  * `\r` and `\t` keep their short escapes; every other control character,
9
12
  * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
@@ -13,5 +16,9 @@
13
16
  * a `JSON.rawJSON` leaf (an exact `decimal` / 64-bit integer) as its text;
14
17
  * NaN and the infinities throw `ArgumentException`, as STJ throws for them.
15
18
  */
16
- /** The JSON text of `tree`, as System.Text.Json writes it. */
17
- export declare function writeJsonText(tree: unknown): string;
19
+ import type { JsonWriteOptions } from "./types.ts";
20
+ /**
21
+ * The JSON text of `tree`, as System.Text.Json writes it: compact, or laid out as
22
+ * `options` say (the context's `WriteIndented` family, #752).
23
+ */
24
+ export declare function writeJsonText(tree: unknown, options?: JsonWriteOptions): string;
@@ -3,7 +3,10 @@
3
3
  * System.Text.Json's `JsonSerializer.Serialize(value, JsonTypeInfo<T>)`
4
4
  * writes with its default options (#741, measured on .NET 10):
5
5
  *
6
- * - no whitespace;
6
+ * - no whitespace, unless the context writes indented text (#752): `writeIndented` puts each
7
+ * array element and each property on its own line, indented by `indentSize` copies of
8
+ * `indentCharacter` per level (a space and 2 by default), with `newLine` (`"\n"` by default)
9
+ * between lines, `": "` after a property name, and `[]` / `{}` for an empty container;
7
10
  * - strings escaped by `JavaScriptEncoder.Default`: `\\`, `\b`, `\f`, `\n`,
8
11
  * `\r` and `\t` keep their short escapes; every other control character,
9
12
  * `"`, `&`, `'`, `+`, `<`, `>`, `` ` `` and every character outside
@@ -21,13 +24,31 @@ const NON_FINITE_NUMBER_MESSAGE = ".NET number values such as positive and negat
21
24
  "To make it work when using 'JsonSerializer', consider specifying " +
22
25
  "'JsonNumberHandling.AllowNamedFloatingPointLiterals' " +
23
26
  "(see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling).";
24
- /** The JSON text of `tree`, as System.Text.Json writes it. */
25
- export function writeJsonText(tree) {
27
+ const COMPACT = {
28
+ lineStart: () => "",
29
+ lineEnd: () => "",
30
+ afterColon: "",
31
+ };
32
+ function indentedLayout(options) {
33
+ const unit = (options.indentCharacter ?? " ").repeat(options.indentSize ?? 2);
34
+ const newLine = options.newLine ?? "\n";
35
+ return {
36
+ lineStart: (depth) => newLine + unit.repeat(depth),
37
+ lineEnd: (depth) => newLine + unit.repeat(depth - 1),
38
+ afterColon: " ",
39
+ };
40
+ }
41
+ /**
42
+ * The JSON text of `tree`, as System.Text.Json writes it: compact, or laid out as
43
+ * `options` say (the context's `WriteIndented` family, #752).
44
+ */
45
+ export function writeJsonText(tree, options) {
26
46
  const parts = [];
27
- writeValue(tree, parts);
47
+ const layout = options?.writeIndented ? indentedLayout(options) : COMPACT;
48
+ writeValue(tree, parts, layout, 0);
28
49
  return parts.join("");
29
50
  }
30
- function writeValue(value, parts) {
51
+ function writeValue(value, parts, layout, depth) {
31
52
  if (value == null) {
32
53
  parts.push("null");
33
54
  return;
@@ -44,9 +65,9 @@ function writeValue(value, parts) {
44
65
  parts.push(String(value));
45
66
  return;
46
67
  }
47
- writeObject(value, parts);
68
+ writeObject(value, parts, layout, depth);
48
69
  }
49
- function writeObject(value, parts) {
70
+ function writeObject(value, parts, layout, depth) {
50
71
  const rawText = rawJsonTextOf(value);
51
72
  if (rawText !== undefined) {
52
73
  parts.push(rawText);
@@ -54,27 +75,35 @@ function writeObject(value, parts) {
54
75
  }
55
76
  const toJson = value.toJSON;
56
77
  if (typeof toJson === "function") {
57
- writeValue(toJson.call(value), parts);
78
+ writeValue(toJson.call(value), parts, layout, depth);
58
79
  return;
59
80
  }
60
81
  if (Array.isArray(value)) {
61
- writeArray(value, parts);
82
+ writeArray(value, parts, layout, depth + 1);
62
83
  return;
63
84
  }
64
- writeProperties(value, parts);
85
+ writeProperties(value, parts, layout, depth + 1);
65
86
  }
66
- function writeArray(items, parts) {
87
+ /** `depth` is the nesting level of the array's elements. */
88
+ function writeArray(items, parts, layout, depth) {
67
89
  parts.push("[");
68
90
  items.forEach((item, index) => {
69
91
  if (index > 0) {
70
92
  parts.push(",");
71
93
  }
72
- writeValue(item, parts);
94
+ parts.push(layout.lineStart(depth));
95
+ writeValue(item, parts, layout, depth);
73
96
  });
97
+ if (items.length > 0) {
98
+ parts.push(layout.lineEnd(depth));
99
+ }
74
100
  parts.push("]");
75
101
  }
76
- /** An object's own enumerable properties; an `undefined` one is skipped, as `JSON.stringify` skips it. */
77
- function writeProperties(object, parts) {
102
+ /**
103
+ * An object's own enumerable properties; an `undefined` one is skipped, as `JSON.stringify`
104
+ * skips it. `depth` is the nesting level of the properties.
105
+ */
106
+ function writeProperties(object, parts, layout, depth) {
78
107
  let first = true;
79
108
  parts.push("{");
80
109
  for (const key of Object.keys(object)) {
@@ -86,8 +115,11 @@ function writeProperties(object, parts) {
86
115
  parts.push(",");
87
116
  }
88
117
  first = false;
89
- parts.push(quoted(key), ":");
90
- writeValue(member, parts);
118
+ parts.push(layout.lineStart(depth), quoted(key), ":", layout.afterColon);
119
+ writeValue(member, parts, layout, depth);
120
+ }
121
+ if (!first) {
122
+ parts.push(layout.lineEnd(depth));
91
123
  }
92
124
  parts.push("}");
93
125
  }