From 68671edf290e8880c21cc060ac587d65d470298d Mon Sep 17 00:00:00 2001 From: Jonathan Peris Date: Sun, 29 Nov 2026 15:51:33 -0300 Subject: [PATCH] Format TimeSpan with CoreLib's TimeSpanFormat from the framework's IL (#447) TimeSpan's ToString overloads and TryFormat (UTF-16 and UTF-8) are now hosted from TimeSpan's own IL through `this.` roots in upstream-types/System.Globalization.txt, so they run CoreLib's TimeSpanFormat like every other date and time formatter since #426. The compiler's remaining entry points (interpolation holes, boxed TimeSpans in composite formatting, Stopwatch.ToString) call TimeSpanFormat.FormatC/Format through UnsafeAccessors in corelib/Globalization/DateTimeFormatting.cs. Deleted: DateTimeOps' standard and custom TimeSpan formatter and its helpers, the TimeSpanTryFormat shadow members (which formatted a whole string and copied it) and the three BclValueTypes ToString mappings. New samples recorded from .NET: 1604 (every overload on negative and extreme values, custom formats with quotes and escapes, "c"/"g"/"G" under six cultures, composite and interpolation holes, TryFormat at every destination size in UTF-16 and UTF-8, invalid formats through TryFormat, Stopwatch) and 1605 (invariant globalization mode). The corelib's formatter printed the same text on both: no silent difference was found. Measured on linux-x86_64 (stripped -O2, median of 7, same host): - timespan_format_throughput (new, tools/il-first/bench): 384 to 269 ms (0.70x), 3 924 M to 2 080 M instructions; NativeAOT 258 ms and 2 511 M instructions (csharpc 1.02x of its time). - size: timespan_format_throughput 362 976 to 411 536 B (NativeAOT 1 678 960), sample 1604 +29 328, 186 +19 504, 82 -144; regex and regexoptions +4 416 (they root the boxed-TimeSpan exports through the match timeout); the other size programs unchanged. Every tests/size.sh budget still holds, none raised. --- docs/06-roadmap.md | 3 +- docs/il-first/System.Globalization.md | 3 +- docs/il-first/remaining-flips.md | 2 +- src/Csharpc/CodeGen/BclValueTypes.cs | 3 - src/Csharpc/corelib/DateTimeOps.cs | 179 +----------------- .../Globalization/DateTimeFormatting.cs | 20 +- src/Csharpc/corelib/SpanFormattableMembers.cs | 12 +- .../upstream-types/System.Globalization.txt | 4 + tests/platform-skips.txt | 3 + tests/samples/1604_timespan_format_edges.cs | 85 +++++++++ .../1604_timespan_format_edges.expected | 53 ++++++ .../samples/1605_timespan_format_invariant.cs | 26 +++ .../1605_timespan_format_invariant.env | 1 + .../1605_timespan_format_invariant.expected | 15 ++ .../bench/timespan_format_throughput.cs | 29 +++ 15 files changed, 249 insertions(+), 189 deletions(-) create mode 100644 tests/samples/1604_timespan_format_edges.cs create mode 100644 tests/samples/1604_timespan_format_edges.expected create mode 100644 tests/samples/1605_timespan_format_invariant.cs create mode 100644 tests/samples/1605_timespan_format_invariant.env create mode 100644 tests/samples/1605_timespan_format_invariant.expected create mode 100644 tools/il-first/bench/timespan_format_throughput.cs diff --git a/docs/06-roadmap.md b/docs/06-roadmap.md index 504ab9c78..28b915c84 100644 --- a/docs/06-roadmap.md +++ b/docs/06-roadmap.md @@ -549,10 +549,9 @@ before working on one (`tools/il-first/measure-aot.sh`), since earlier changes m - Crypto from the framework's IL on macOS, Windows and WASI; Linux is flipped (#449). - Windows: System.Net.Sockets from IL needs IOCP (ThreadPoolBoundHandle) in the runtime (#441). - System.Uri (System.Private.Uri behind System.Runtime) (#442). -- TimeSpan formatting through CoreLib's TimeSpanFormat instead of the corelib's formatter (#447). - Vector2/3/4, Plane and Quaternion (#451); System.Half (#410); BFloat16 and Decimal32/64/128 (#405). - System.Diagnostics.Process (it would also give #102's other-process lookups). -- Done since the tracker opened: Guid (#416); ManualResetEventSlim and SpinWait from CoreLib, Barrier from System.Threading (#414); +- Done since the tracker opened: TimeSpan formatting through CoreLib's TimeSpanFormat (#447); Guid (#416); ManualResetEventSlim and SpinWait from CoreLib, Barrier from System.Threading (#414); ArrayList and BitArray (#372). ### Stack allocation (was #476; after #457, #461) diff --git a/docs/il-first/System.Globalization.md b/docs/il-first/System.Globalization.md index 2658dcc83..35acbb0bb 100644 --- a/docs/il-first/System.Globalization.md +++ b/docs/il-first/System.Globalization.md @@ -6,4 +6,5 @@ A library or CoreLib type served from the framework's IL: its row of the per-lib | Library (switch) | Correctness (samples from IL) | Binary size, IL / shadow | Compile cpu, IL / shadow | Speed, IL / shadow (time) | Lines removed on a flip | Decision | NativeAOT on the same host, csharpc / NativeAOT (`tools/il-first/measure-aot.sh`: stripped size; compile cpu; run, median of 7; instructions) | |---|---|---|---|---|---|---|---| | Cultures and culture data (`CultureInfo`, `CultureData`, `RegionInfo`, `CultureNotFoundException`), `NumberFormatInfo`, casing (`TextInfo`), collation (`CompareInfo`, `SortKey`, `SortVersion`), `CharUnicodeInfo`, `StringInfo`/`TextElementEnumerator`, `IdnMapping`, `DateTimeFormatInfo`, every calendar (the lunisolar ones are new), and CoreLib's `DateTimeFormat`, `DateTimeParse`, `TimeSpanFormat` and `TimeSpanParse`; DateOnly's, TimeOnly's and TimeSpan's Parse/TryParse members hosted from their IL (`src/Csharpc/upstream-types/System.Globalization.txt`, #426) | 129 samples that use cultures, culture data, casing, collation, IDN, text elements, date and time formatting and parsing, number formatting, composite formatting and text writers byte-identical to real .NET at -O0 and -O2 (258 runs) and via IL (129), 12 of them on wasm32 (the others need ICU or threads); new samples 1381 (a constrained `IEquatable.Equals` on `Vector128`: an explicit diagnostic before) and 1382 (generic shifts on byte/sbyte/short/ushort: invalid IR before, from C# and from IL); `tests/slicer.sh` 10 of 10. 369/371/372/608 (the current culture flowing into threads, tasks and the thread pool) pass through the AsyncLocal contract below | a program that formats a number carries CoreLib's culture initialization (culture data over ICU, its locale tables, the culture caches): linux-x86_64 numbers 156 672 B budget to 236 328 B measured, collections 255 944, async 270 528, linq 341 288 (budgets raised with these numbers; hello, exceptions, typeinfo unchanged). `CultureInfo.GetFormat`'s DateTimeFormatInfo case through the runtime trigger and composite formatting without a type switch took about 470 KB of that back. The throughput program 230 216 to 265 648 B (NativeAOT 1 378 112) | throughput program 8.4 to 8.0 s (NativeAOT publish 12.9 s) | throughput program (`tools/il-first/bench/number_format_parse_throughput.cs`: int, long, double, decimal format and parse, invariant and de-DE, composite formatting), median of 7: **1 359 to 1 323 ms**; 12.48 G to 12.43 G instructions | 36 966 deleted (the 52 files of `corelib/Globalization` the slice replaces, `runtime/csrt.c`'s DateTimeFormatInfo trigger), 610 added (the ICU forwarding class, the DateTime/DateTimeOffset accessors, contract members) | **Flipped.** The ICU boundary stays the corelib's: the slicer's csharpc profile points CoreLib's 29 `Interop.Globalization` calls at `corelib/UpstreamGlobalization.cs`, which forwards each to the corelib's imports of the runtime's ICU shim (`src/runtime/globalization/pal_*.c`), and keeps `GlobalizationMode` (invariant mode compiled from the project, ICU loaded on first use, WASI always invariant), `CalendarId`, `CalendarDataType` and `TimeZoneInfoOptions` the corelib's. `Interop.CallStringMethod` (CalendarData's string helper) is hosted from IL. **Windows:** the Windows CoreLib carries the NLS back end next to ICU's; csharpc, like .NET by default, uses ICU, so the slicer folds `GlobalizationMode.UseNls` to false (the emitted IL loads the constant, the branches it rules out are not lowered, and the members and nested types only they use are not cut into the slice), and points the Win32 calls .NET still makes in ICU mode (`GetLocaleInfoEx` for the locale check, user overrides and code pages, `GetCalendarInfoEx`, `GetUserGeoID`/`GetGeoInfo`, `GetUserPreferredUILanguages`, `LCIDToLocaleName`, `MultiByteToWideChar`, and the Hijri calendar's `AddHijriDate` registry value) at the corelib's own imports (`corelib/UpstreamWindows.cs`). **WASI** (no ICU, invariant mode): linguistic comparisons with no option or IgnoreCase keep the runtime's approximation of ICU's root collation, as before the flip, through the 32-bit slice's replacement of `CompareInfo.Compare` over spans (`--wasi`, `corelib/UpstreamWasiCollation.cs`). **Security:** every buffer handed to the shim is bounded by the managed buffer it comes from: pointer arguments are CoreLib's own stackalloc or pinned buffers with their own lengths, and where a length travels next to an array or span (`GetLocales`, `GetCalendars`, `ToAscii`, `ToUnicode`) the forwarder clamps it to that array's or span's length, so a wrong length never lets native code write past it; strings go in NUL-terminated. The shim's `EnumCalendarInfo` callback is CoreLib's `[UnmanagedCallersOnly]` method (the slicer now copies that attribute). Compiler pieces it needed, all general: generic `[UnsafeAccessor]` static methods and accessors to internal types named by string; `[ShadowConstructor]` factories for internal value-type constructors (`DateTime(long, DateTimeKind, bool)`); constrained generic-math operator and `IEquatable` calls on `Vector128` (sample 1381); `m_value`, `_dateData` and `_ticks` as built-in private fields; hosted instance members of built-in value types (the slicer's `this.` host roots). | `number_format_parse_throughput`: 265 648 / 1 378 112 B; run 1 323 / 1 260 ms (1.05x; measure-aot.sh on the same host: 1 430 / 1 260 ms, 1.14x); 12.43 G / 10.54 G instructions. Number formatting itself is still the corelib's here (#426 continues with System.Number from IL) | -| Number formatting and parsing: CoreLib's `System.Number` with `NumberFormatInfo`, and the primitives' own `ToString`/`TryFormat`/`Parse`/`TryParse` (integers, `Int128`/`UInt128`, `Half`, `float`, `double`, `decimal`) hosted from their IL (`this.` roots in `src/Csharpc/upstream-types/System.Globalization.txt`, #426); `Enum.Parse` in C# over CoreLib's integer parser | 206 samples that format or parse numbers, enums, cultures and composite text byte-identical to real .NET at -O0 and -O2 (412 runs), 21 via IL (459, 642, 643 among them), 21 on wasm32; `tests/slicer.sh` 10 of 10; conformance formatting 5 of 5 and 7 of 7. New samples 1396 (constrained `ISpanFormattable`/`IUtf8SpanFormattable` calls on built-in numbers reached their boxed slot and recursed until the stack ran out; now they call the hosted member) and 1450 (`Enum.Parse` edges: NBSP trimming, overflow as `OverflowException`, names differing only by case) | the framework's formatter and parsers replace the corelib's smaller copies: linux-x86_64 numbers 236 024 to 254 088 B (+18 064), async 266 120 to 284 248, collections 255 640 to 269 608, linq 341 032 to 358 744, net 330 592 to 369 904, json 1 661 648 to 1 706 000, jsonwriter 832 112 to 861 464, regex 924 224 to 937 568, regexoptions 2 122 264 to 2 151 576; hello, exceptions, typeinfo unchanged (budgets raised with these numbers: a measured speed gain). The throughput program 269 832 to 337 968 B (NativeAOT 1 378 112) | throughput program 6.6 to 7.2 s wall (measure-aot.sh: 9.0 s cpu, 280 MB peak; NativeAOT publish 17.7 s cpu, 216 MB) | throughput program (`tools/il-first/bench/number_format_parse_throughput.cs`), median of 7 on the same host: **1 388 to 1 026 ms**; 12.53 G to 8.53 G instructions (-32 %) | 2 895 deleted, 299 added (`Number.Parsing.Culture.cs`, `NumberParsingMembers.cs` and most of `Number.Formatting.cs`, `Number.Parsing.cs`, `NumberTryFormat.cs`, `Int128Parsing.cs`; `runtime/parse.c`; the slicer's `NumberBridge` emitter) | **Flipped.** The corelib's `Number` class keeps only the compiler's entry points (concatenation, interpolation holes, boxed values, `Console.Write`), which call CoreLib's `System.Number` through `corelib/NumberUpstream.cs` (`[UnsafeAccessor]`, docs/12-corelib.md); the shortest-digits bridge is gone. Still the corelib's: `BigInteger`'s standard formats, decimal to and from double, `Math.Round(double, digits, mode)`, and TimeSpan's own formatter (remaining-flips.md). **Security:** parsing is CoreLib's span-based code, bounded by the input span's length, with overflow reported as `OverflowException` (Parse) or `false` (TryParse) and never wrapped; formatting writes through CoreLib's `ValueListBuilder`/span writers, so a `TryFormat` into a too-small destination returns false with nothing written past it (1396); NaN, infinity and sign texts come from the `NumberFormatInfo` in use. `Enum.Parse` no longer runs the C runtime's own string parser (`parse.c`, deleted): the name lookup and the integer fallback are bounds-checked C#. `decimal.GetBits`/`TryGetBits`/`new decimal(int[] or ReadOnlySpan)` stay the representation's members (`corelib/DecimalBits.cs`) and validate length and scale as .NET does. Compiler pieces it needed, general: constrained interface calls on built-in value types reach the hosted IL member; ordinal comparison variants bind only non-private members (#443). | `number_format_parse_throughput`: 338 056 / 1 378 112 B; compile cpu 9.0 / 17.7 s; run **1 025 / 1 202 ms (0.85x)**, was 1 323 / 1 260 ms (1.05x) with the corelib's formatter; **8.53 G / 10.54 G instructions**, was 12.43 G / 10.54 G | +| Number formatting and parsing: CoreLib's `System.Number` with `NumberFormatInfo`, and the primitives' own `ToString`/`TryFormat`/`Parse`/`TryParse` (integers, `Int128`/`UInt128`, `Half`, `float`, `double`, `decimal`) hosted from their IL (`this.` roots in `src/Csharpc/upstream-types/System.Globalization.txt`, #426); `Enum.Parse` in C# over CoreLib's integer parser | 206 samples that format or parse numbers, enums, cultures and composite text byte-identical to real .NET at -O0 and -O2 (412 runs), 21 via IL (459, 642, 643 among them), 21 on wasm32; `tests/slicer.sh` 10 of 10; conformance formatting 5 of 5 and 7 of 7. New samples 1396 (constrained `ISpanFormattable`/`IUtf8SpanFormattable` calls on built-in numbers reached their boxed slot and recursed until the stack ran out; now they call the hosted member) and 1450 (`Enum.Parse` edges: NBSP trimming, overflow as `OverflowException`, names differing only by case) | the framework's formatter and parsers replace the corelib's smaller copies: linux-x86_64 numbers 236 024 to 254 088 B (+18 064), async 266 120 to 284 248, collections 255 640 to 269 608, linq 341 032 to 358 744, net 330 592 to 369 904, json 1 661 648 to 1 706 000, jsonwriter 832 112 to 861 464, regex 924 224 to 937 568, regexoptions 2 122 264 to 2 151 576; hello, exceptions, typeinfo unchanged (budgets raised with these numbers: a measured speed gain). The throughput program 269 832 to 337 968 B (NativeAOT 1 378 112) | throughput program 6.6 to 7.2 s wall (measure-aot.sh: 9.0 s cpu, 280 MB peak; NativeAOT publish 17.7 s cpu, 216 MB) | throughput program (`tools/il-first/bench/number_format_parse_throughput.cs`), median of 7 on the same host: **1 388 to 1 026 ms**; 12.53 G to 8.53 G instructions (-32 %) | 2 895 deleted, 299 added (`Number.Parsing.Culture.cs`, `NumberParsingMembers.cs` and most of `Number.Formatting.cs`, `Number.Parsing.cs`, `NumberTryFormat.cs`, `Int128Parsing.cs`; `runtime/parse.c`; the slicer's `NumberBridge` emitter) | **Flipped.** The corelib's `Number` class keeps only the compiler's entry points (concatenation, interpolation holes, boxed values, `Console.Write`), which call CoreLib's `System.Number` through `corelib/NumberUpstream.cs` (`[UnsafeAccessor]`, docs/12-corelib.md); the shortest-digits bridge is gone. Still the corelib's: `BigInteger`'s standard formats, decimal to and from double, `Math.Round(double, digits, mode)`, and, until #447, TimeSpan's own formatter. **Security:** parsing is CoreLib's span-based code, bounded by the input span's length, with overflow reported as `OverflowException` (Parse) or `false` (TryParse) and never wrapped; formatting writes through CoreLib's `ValueListBuilder`/span writers, so a `TryFormat` into a too-small destination returns false with nothing written past it (1396); NaN, infinity and sign texts come from the `NumberFormatInfo` in use. `Enum.Parse` no longer runs the C runtime's own string parser (`parse.c`, deleted): the name lookup and the integer fallback are bounds-checked C#. `decimal.GetBits`/`TryGetBits`/`new decimal(int[] or ReadOnlySpan)` stay the representation's members (`corelib/DecimalBits.cs`) and validate length and scale as .NET does. Compiler pieces it needed, general: constrained interface calls on built-in value types reach the hosted IL member; ordinal comparison variants bind only non-private members (#443). | `number_format_parse_throughput`: 338 056 / 1 378 112 B; compile cpu 9.0 / 17.7 s; run **1 025 / 1 202 ms (0.85x)**, was 1 323 / 1 260 ms (1.05x) with the corelib's formatter; **8.53 G / 10.54 G instructions**, was 12.43 G / 10.54 G | +| TimeSpan formatting: TimeSpan's own `ToString()`, `ToString(string)`, `ToString(string, IFormatProvider)` and `TryFormat` (UTF-16 and UTF-8) hosted from their IL over CoreLib's `TimeSpanFormat` (`this.` roots in `src/Csharpc/upstream-types/System.Globalization.txt`, #447); the compiler's entry points (interpolation holes, boxed TimeSpans in composite formatting, `Stopwatch.ToString`) call `TimeSpanFormat.FormatC`/`Format` through `corelib/Globalization/DateTimeFormatting.cs` | the TimeSpan samples (82, 164, 186, 361, 376, 490, 509, 513, 542, 657, 864, 1224, 1252, 1545) and the two new ones byte-identical to real .NET at -O0 and -O2 (32 runs) and via IL (16); 1605 runs on wasm32 in CI (1604 needs ICU cultures); `tests/slicer.sh` 10 of 10. New samples, recorded from .NET: 1604 (every overload on negative values, `MinValue`/`MaxValue`, custom formats with quotes and escapes, "c"/"g"/"G" under six cultures, interpolation and composite holes with alignment, boxed and `ISpanFormattable` calls, `TryFormat` at every destination size in UTF-16 and UTF-8 with nothing written past the end, invalid formats through `TryFormat`, `Stopwatch`) and 1605 (invariant globalization mode: the decimal separator of "g"/"G" comes from the culture's data, not its `NumberFormat`; named cultures throw). The corelib's formatter gave the same text on all of them: no silent difference found | linux-x86_64, stripped -O2: `timespan_format_throughput` 362 976 to 411 536 B (+48 560: the framework's generic `TryFormatStandard`/`FormatCustomized` for char and byte), 1604 422 248 to 451 576, 186 346 608 to 366 112, 82 800 920 to 800 776; regex and regexoptions +4 416 each (both root the boxed-TimeSpan exports through the match timeout); hello, exceptions, typeinfo, async, collections, json, jsonwriter, linq, net, numbers, rsa unchanged; `tests/size.sh` 13 of 13 within budget, none raised | throughput program 9.4 s cpu (measure-aot.sh; NativeAOT publish 12.6 s) | `timespan_format_throughput` (`tools/il-first/bench/timespan_format_throughput.cs`: `ToString()`, "g"/"G" invariant and fr-FR, custom formats, `TryFormat` UTF-16 and UTF-8, interpolation), median of 7 on the same host: **384 to 269 ms (0.70x)**; 3 924 M to 2 080 M instructions (-47 %) | 170 deleted (`DateTimeOps`' standard and custom TimeSpan formatter and its helpers, the `TimeSpanTryFormat` shadow members, three `BclValueTypes` mappings), 33 added | **Flipped.** TimeSpan's representation and arithmetic stay the corelib's (built-in i64, `_ticks` a built-in private field). **Security:** the formatter writes through CoreLib's `ValueListBuilder` and span writers, so `TryFormat` into a too-small destination returns false with 0 written and nothing past the destination (1604 checks the two elements after it, UTF-16 and UTF-8); before, it formatted a whole string and copied it | `timespan_format_throughput`: 411 424 / 1 678 960 B; compile cpu 9.4 / 12.6 s; run **263 / 258 ms (1.02x)**; **2 080 M / 2 511 M instructions** | diff --git a/docs/il-first/remaining-flips.md b/docs/il-first/remaining-flips.md index fc1ed2339..0e4998414 100644 --- a/docs/il-first/remaining-flips.md +++ b/docs/il-first/remaining-flips.md @@ -16,7 +16,7 @@ OS boundary) and the contract layer (reflection/type system, task/async glue, in | Hashtable, ArrayList, BitArray | done: `docs/il-first/System.Collections.Hashtable.md`, `System.Collections.ArrayList.md` (SR.Format contract for every slice) | #372, #373 | | Guid | done locally: from the framework; docs/il-first/System.Guid.md | #416 | | Culture, number formatting and parsing (deletes the digits bridge) | done locally: cultures, culture data, casing, collation, `CharUnicodeInfo`, `IdnMapping`, `StringInfo`, and number formatting and parsing (`System.Number`, the primitives' ToString/TryFormat/Parse/TryParse hosted from IL; the digits bridge and `runtime/parse.c` deleted, `Enum.Parse` in C#) from the framework (docs/il-first/System.Globalization.md). BigInteger's standard formats, decimal to and from double and `Math.Round(double, digits, mode)` stay with the BigInteger and floating-point row | #426 | -| DateTime, calendars, TimeSpan parsing and formatting | done locally with culture: `DateTimeFormatInfo`, every calendar, `DateTimeFormat`, `DateTimeParse`, `TimeSpanFormat`/`TimeSpanParse`; DateOnly/TimeOnly/TimeSpan parsing hosted from IL; the corelib keeps those types' representation and their formatting members; TimeSpan's own formatter is still the corelib's (#447) | #426, #447 | +| DateTime, calendars, TimeSpan parsing and formatting | done locally with culture: `DateTimeFormatInfo`, every calendar, `DateTimeFormat`, `DateTimeParse`, `TimeSpanFormat`/`TimeSpanParse`; DateOnly/TimeOnly/TimeSpan parsing hosted from IL; the corelib keeps those types' representation and DateTime's/DateOnly's/TimeOnly's formatting members; TimeSpan's ToString/TryFormat hosted from IL over `TimeSpanFormat`, the corelib's TimeSpan formatter deleted (docs/il-first/System.Globalization.md, #447) | #426, #447 | | Text and encoding, Convert, string helpers, hashing, BigInteger, floating-point math | done locally: Ascii, Base64, CompositeFormat, StandardFormat ([System.Text.Ascii.md](System.Text.Ascii.md)) the Encoding family with Utf8 ([System.Text.Encoding.md](System.Text.Encoding.md)) Convert ([System.Convert.md](System.Convert.md)) Rune ([System.Text.Rune.md](System.Text.Rune.md)) the string and char helpers ([System.String.md](System.String.md)) BigInteger ([System.Runtime.Numerics.md](System.Runtime.Numerics.md)) and the floating-point members of float, double, Math and MathF ([System.Math.md](System.Math.md)) done; hashing is all crypto (with the crypto row); Vector2/3/4 stay shadows (#451). Follow-ups #432, #433, #434, #435, #446, #448, #450, #453 | #423 | | Tracing | done locally: EventSource, EventListener, the event counters and TraceLogging from the framework (docs/il-first/System.Diagnostics.Tracing.md: a disabled EventPipe contract, reflection over the event source, security review and measurements); follow-ups #454 (throughput vs NativeAOT), #455 (the runtime's own event sources) | #423 | | IO above the libc boundary | done locally: part 1 (streams, readers, writers) and part 2 (`File`, `Directory`, `FileInfo`/`DirectoryInfo`, `FileStream`, `Path`, `RandomAccess`, `SafeFileHandle`, enumeration over the C# libSystem.Native contract `corelib/IO/SystemNative.cs`; security review and measurements in [System.IO.md](System.IO.md)); Windows (the Windows CoreLib slice over kernel32) waits for CI; linking the pack's libSystem.Native instead stays the owner's decision ([21-ownership.md](../21-ownership.md)) | #315 | diff --git a/src/Csharpc/CodeGen/BclValueTypes.cs b/src/Csharpc/CodeGen/BclValueTypes.cs index 2849df538..4c4d184ba 100644 --- a/src/Csharpc/CodeGen/BclValueTypes.cs +++ b/src/Csharpc/CodeGen/BclValueTypes.cs @@ -610,9 +610,6 @@ BclHandler tsBinary(string fn) => (g, _, self, a, _) => g.Builder.Cast(LLVMOpcode.Trunc, g.Builder.BinOp(LLVMOpcode.AShr, s, I64(g, 32)), g.Llvm.I32)); }; } - t[$"{TS}.ToString()"] = (g, _, self, _, _) => Rt(g, "csrt_timespan_to_string", g.Llvm.Ptr, (self, g.Llvm.I64)); - t[$"{TS}.ToString(string)"] = (g, _, self, a, _) => Rt(g, "csrt_timespan_format", g.Llvm.Ptr, (self, g.Llvm.I64), (a[0], g.Llvm.Ptr)); - t[$"{TS}.ToString(string, System.IFormatProvider)"] = (g, _, self, a, _) => g.CallCoreLib("DateTimeOps", "TimeSpanFormatWith", self, a[0], a[1]); // ===== System.DateTime (i64 _dateData: ticks | Kind << 62; more members in corelib DateTimeMembers) ===== const string DT = "System.DateTime"; diff --git a/src/Csharpc/corelib/DateTimeOps.cs b/src/Csharpc/corelib/DateTimeOps.cs index 46a6d10d1..cf02b99b1 100644 --- a/src/Csharpc/corelib/DateTimeOps.cs +++ b/src/Csharpc/corelib/DateTimeOps.cs @@ -4,7 +4,8 @@ // daylight-saving occurrence of an ambiguous hour), so every entry point here that takes a DateTime // takes that whole word. The codegen (BclValueTypes.cs) still asks for the csrt_timespan_* / // csrt_datetime_* entry points, which CoreLibRuntime redirects here. Calendar math is the CLR's own -// algorithm (proleptic Gregorian, years 1..9999); formatting follows the invariant culture. The +// algorithm (proleptic Gregorian, years 1..9999); formatting is CoreLib's DateTimeFormat and TimeSpanFormat, from +// the framework's IL (#426, #447). The // clocks (UtcNow, Stopwatch) stay in C; the local time zone is libc's (TZ / tzdata, as .NET reads). #nullable disable using System; @@ -114,177 +115,14 @@ internal static long TimeSpanDivide(long ticks, double divisor) return FromDoubleTicks(Math.Round(ticks / divisor)); } - private static void AppendNumber(ref CharBuilder sb, long value, int width) - { - int digits = Number.CountDigits((ulong)value); - sb.Append('0', width - digits); - Span tmp = stackalloc char[20]; - Number.WriteDigits(tmp.Slice(0, digits), (ulong)value); - for (int i = 0; i < digits; i++) sb.Append(tmp[i]); - } - - private static void AppendFraction(ref CharBuilder sb, long fraction, int digits, bool trim) - { - Span t = stackalloc char[7]; - long v = fraction; // < 10^7 - for (int i = 6; i >= 0; i--) { t[i] = (char)('0' + (int)(v % 10)); v /= 10; } - int n = digits; - if (trim) while (n > 0 && t[n - 1] == '0') n--; - for (int i = 0; i < n; i++) sb.Append(t[i]); - } - - private static void TimeSpanStandard(ref CharBuilder sb, long ticks, char f, string decimalSeparator = ".") - { - bool negative = ticks < 0; - ulong magnitude = negative ? 0UL - (ulong)ticks : (ulong)ticks; // survives MinValue - ulong days = magnitude / TicksPerDay, rem = magnitude % TicksPerDay; - int hours = (int)(rem / TicksPerHour), minutes = (int)(rem / TicksPerMinute % 60), seconds = (int)(rem / TicksPerSecond % 60); - long fraction = (long)(rem % TicksPerSecond); - if (negative) sb.Append('-'); - if (f == 'g') - { - if (days != 0) { AppendNumber(ref sb, (long)days, 1); sb.Append(':'); } - AppendNumber(ref sb, hours, 1); sb.Append(':'); AppendNumber(ref sb, minutes, 2); sb.Append(':'); AppendNumber(ref sb, seconds, 2); - if (fraction != 0) { sb.Append(decimalSeparator); AppendFraction(ref sb, fraction, 7, true); } - } - else if (f == 'G') - { - AppendNumber(ref sb, (long)days, 1); sb.Append(':'); AppendNumber(ref sb, hours, 2); sb.Append(':'); - AppendNumber(ref sb, minutes, 2); sb.Append(':'); AppendNumber(ref sb, seconds, 2); sb.Append(decimalSeparator); - AppendFraction(ref sb, fraction, 7, false); - } - else // 'c', the constant format - { - if (days != 0) { AppendNumber(ref sb, (long)days, 1); sb.Append('.'); } - AppendNumber(ref sb, hours, 2); sb.Append(':'); AppendNumber(ref sb, minutes, 2); sb.Append(':'); AppendNumber(ref sb, seconds, 2); - if (fraction != 0) { sb.Append('.'); AppendFraction(ref sb, fraction, 7, false); } - } - } - + // TimeSpan formatting is CoreLib's own TimeSpanFormat, served from the framework's IL (#447, + // src/Csharpc/upstream-types/System.Globalization.txt); TimeSpan's ToString/TryFormat members are hosted from their IL. These are + // the compiler's remaining entry points (interpolation holes, boxed values, Stopwatch.ToString). [RuntimeExport("csrt_timespan_to_string", "csrt_Boxed_TimeSpan_MT")] [RuntimeExport("csrt_timespan_to_string", "csrt_Stopwatch_MT")] - internal static string TimeSpanToString(long ticks) - { - Span chars = stackalloc char[32]; - var sb = new CharBuilder(chars); - TimeSpanStandard(ref sb, ticks, 'c'); - return sb.Build(); - } - - private static int RunLength(string f, int i) - { - int n = 1; - while (i + n < f.Length && f[i + n] == f[i]) n++; - return n; - } - - private static void ThrowInvalidFormat() => throw new FormatException("Input string was not in a correct format."); + internal static string TimeSpanToString(long ticks) => Globalization.TimeSpanFormat.FormatC(new TimeSpan(ticks)); - /// - /// .NET's DateTimeFormat.ParseQuoteString: copies a quoted literal (backslash escapes inside it) - /// and returns its length including both quotes; an unterminated quote is an error. - /// - private static int ParseQuoteString(ref CharBuilder sb, string f, int pos) - { - int begin = pos; - char quote = f[pos++]; - while (pos < f.Length) - { - char ch = f[pos++]; - if (ch == quote) return pos - begin; - if (ch == '\\') - { - if (pos >= f.Length) ThrowInvalidFormat(); - sb.Append(f[pos++]); - } - else sb.Append(ch); - } - throw new FormatException("Cannot find a matching quote character for the character '" + quote.ToString() + "'."); - } - - /// The character after a '%' or '\\'; a format ending there is an error. - private static char NextFormatChar(string f, int i) - { - if (i + 1 >= f.Length) ThrowInvalidFormat(); - return f[i + 1]; - } - - internal static string TimeSpanFormat(long ticks, string format) => TimeSpanFormatWith(ticks, format, null); - - /// TimeSpan.ToString(format, provider): only "g"/"G" depend on the culture (its decimal separator). - internal static string TimeSpanFormatWith(long ticks, string format, IFormatProvider provider) - { - Span chars = stackalloc char[64]; - var sb = new CharBuilder(chars); - string f = format ?? ""; - if (f.Length == 0 || (f.Length == 1 && (f[0] == 'c' || f[0] == 't' || f[0] == 'T' || f[0] == 'g' || f[0] == 'G'))) - { - char standard = f.Length == 0 ? 'c' : f[0] == 'g' ? 'g' : f[0] == 'G' ? 'G' : 'c'; - TimeSpanStandard(ref sb, ticks, standard, - standard == 'c' ? "." : Globalization.DateTimeFormatInfoInternals.DecimalSeparator(System.Globalization.DateTimeFormatInfo.GetInstance(provider))); - return sb.Build(); - } - // Any other single character is an unknown standard format, not a custom one. - if (f.Length == 1) ThrowInvalidFormat(); - TimeSpanCustom(ref sb, ticks, f); - return sb.Build(); - } - - /// .NET's TimeSpanFormat.FormatCustomized: anything but a known specifier, a quote or an escape is an error. - private static void TimeSpanCustom(ref CharBuilder sb, long ticks, string f) - { - ulong magnitude = ticks < 0 ? 0UL - (ulong)ticks : (ulong)ticks; - ulong days = magnitude / TicksPerDay, rem = magnitude % TicksPerDay; - int hours = (int)(rem / TicksPerHour), minutes = (int)(rem / TicksPerMinute % 60), seconds = (int)(rem / TicksPerSecond % 60); - long fraction = (long)(rem % TicksPerSecond); - for (int i = 0; i < f.Length;) - { - char c = f[i]; - int n; - switch (c) - { - case 'h': - case 'm': - case 's': - n = RunLength(f, i); - if (n > 2) ThrowInvalidFormat(); - AppendNumber(ref sb, c == 'h' ? hours : c == 'm' ? minutes : seconds, n); - break; - case 'f': - case 'F': - n = RunLength(f, i); - if (n > 7) ThrowInvalidFormat(); - AppendFraction(ref sb, fraction, n, c == 'F'); - break; - case 'd': - n = RunLength(f, i); - if (n > 8) ThrowInvalidFormat(); - AppendNumber(ref sb, (long)days, n); - break; - case '\'': - case '"': - n = ParseQuoteString(ref sb, f, i); - break; - case '%': - { - char next = NextFormatChar(f, i); - if (next == '%') ThrowInvalidFormat(); - TimeSpanCustom(ref sb, ticks, next.ToString()); - n = 2; - break; - } - case '\\': - sb.Append(NextFormatChar(f, i)); - n = 2; - break; - default: - ThrowInvalidFormat(); - n = 0; - break; - } - i += n; - } - } + internal static string TimeSpanFormat(long ticks, string format) => Globalization.TimeSpanFormat.Format(new TimeSpan(ticks), format, null); // ========================================================================================== // DateTime (the CLR's calendar algorithms) @@ -674,7 +512,8 @@ internal static long FromFileTimeUtc(long fileTime) internal static string BoxedDateTimeFormatWith(long data, string format, IFormatProvider provider) => FormatWith(data, format, provider); [RuntimeExport("csrt_timespan_format_with", "csrt_Boxed_TimeSpan_MT")] - internal static string BoxedTimeSpanFormatWith(long ticks, string format, IFormatProvider provider) => TimeSpanFormatWith(ticks, format, provider); + internal static string BoxedTimeSpanFormatWith(long ticks, string format, IFormatProvider provider) => + Globalization.TimeSpanFormat.Format(new TimeSpan(ticks), format, provider); [RuntimeExport("csrt_datetime_to_string", "csrt_Boxed_DateTime_MT")] internal static string DateTimeToString(long data) => FormatWith(data, null, null); diff --git a/src/Csharpc/corelib/Globalization/DateTimeFormatting.cs b/src/Csharpc/corelib/Globalization/DateTimeFormatting.cs index 6fbfed72a..572cbdbb6 100644 --- a/src/Csharpc/corelib/Globalization/DateTimeFormatting.cs +++ b/src/Csharpc/corelib/Globalization/DateTimeFormatting.cs @@ -1,4 +1,5 @@ -// DateTime, DateTimeOffset, DateOnly and TimeOnly formatting and parsing are CoreLib's own DateTimeFormat and DateTimeParse, served from +// DateTime, DateTimeOffset, DateOnly and TimeOnly formatting and parsing are CoreLib's own DateTimeFormat and DateTimeParse (and TimeSpan's +// compiler entry points CoreLib's TimeSpanFormat, #447), served from // the framework's IL with the rest of globalization (#426, src/Csharpc/upstream-types/System.Globalization.txt). The corelib keeps those // types' representation and their thin public members, which call the framework's code through these accessors (bound at compile time: // CodeGen/FunctionCodeGen.UnsafeAccessor.cs). The signatures are CoreLib's. @@ -71,6 +72,23 @@ internal static bool TryFormat(DateTime dateTime, Span destination, out in internal static bool IsValidCustomTimeOnlyFormat(ReadOnlySpan format, bool throwOnError) => UpstreamIsValidCustomTimeOnlyFormat(null, format, throwOnError); } + /// CoreLib's TimeSpanFormat (#447): TimeSpan's own ToString/TryFormat are hosted from their IL; these serve the compiler's + /// entry points (interpolation holes, boxed TimeSpans in composite formatting, Stopwatch.ToString). + internal static class TimeSpanFormat + { + private const string Type = "CsharpcCoreLib.Upstream.System.Globalization.TimeSpanFormat, CsharpcUpstream"; + + [UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name = "FormatC")] + private static extern string UpstreamFormatC([UnsafeAccessorType(Type)] object? type, TimeSpan value); + + [UnsafeAccessor(UnsafeAccessorKind.StaticMethod, Name = "Format")] + private static extern string UpstreamFormat([UnsafeAccessorType(Type)] object? type, TimeSpan value, string? format, IFormatProvider? formatProvider); + + internal static string FormatC(TimeSpan value) => UpstreamFormatC(null, value); + + internal static string Format(TimeSpan value, string? format, IFormatProvider? formatProvider) => UpstreamFormat(null, value, format, formatProvider); + } + internal static class DateTimeParse { private const string Type = "CsharpcCoreLib.Upstream.System.DateTimeParse, CsharpcUpstream"; diff --git a/src/Csharpc/corelib/SpanFormattableMembers.cs b/src/Csharpc/corelib/SpanFormattableMembers.cs index 41700b8b1..46bfaa741 100644 --- a/src/Csharpc/corelib/SpanFormattableMembers.cs +++ b/src/Csharpc/corelib/SpanFormattableMembers.cs @@ -1,4 +1,4 @@ -// ISpanFormattable / IUtf8SpanFormattable of char, DateTime and TimeSpan (decimal's is the framework's, #426), for constrained calls through +// ISpanFormattable / IUtf8SpanFormattable of char and DateTime (decimal's and TimeSpan's are the framework's, #426, #447), for constrained calls through // those interfaces (RazorSlices' Write overloads format values this way): exactly ToString(format, provider)'s // text, copied when it fits (charsWritten/bytesWritten 0 otherwise), as .NET's TryFormat produce the same text. #nullable disable @@ -17,16 +17,6 @@ [ShadowInstance] public static bool TryFormat(DateTime value, Span utf8Des NumberTryFormat.CopyUtf8(value.ToString(NumberTryFormat.Format(format), provider), utf8Destination, out bytesWritten); } - [ShadowMembers("System.TimeSpan")] - internal static class TimeSpanTryFormat - { - [ShadowInstance] public static bool TryFormat(TimeSpan value, Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider provider = null) => - NumberTryFormat.Copy(value.ToString(NumberTryFormat.Format(format), provider), destination, out charsWritten); - - [ShadowInstance] public static bool TryFormat(TimeSpan value, Span utf8Destination, out int bytesWritten, ReadOnlySpan format = default, IFormatProvider provider = null) => - NumberTryFormat.CopyUtf8(value.ToString(NumberTryFormat.Format(format), provider), utf8Destination, out bytesWritten); - } - /// char's explicit implementations (Char.cs): the char itself, or its UTF-8 (new Rune(char) throws for a surrogate). [ShadowMembers("System.Char")] internal static class CharTryFormat diff --git a/src/Csharpc/upstream-types/System.Globalization.txt b/src/Csharpc/upstream-types/System.Globalization.txt index 249140f94..77d849057 100644 --- a/src/Csharpc/upstream-types/System.Globalization.txt +++ b/src/Csharpc/upstream-types/System.Globalization.txt @@ -44,6 +44,10 @@ System.Globalization.TimeSpanParse # representation. DateTime's and DateTimeOffset's corelib members call DateTimeParse and DateTimeFormat through # corelib/Globalization/DateTimeFormatting.cs. host:System.DateOnly,System.TimeOnly,System.TimeSpan::Parse,TryParse,ParseExact,TryParseExact +# TimeSpan's formatting members (#447): ToString (every overload) and TryFormat (UTF-16 and UTF-8), from TimeSpan's own IL over +# TimeSpanFormat. The compiler's entry points (interpolation holes, boxed TimeSpans, Stopwatch.ToString) call TimeSpanFormat through +# corelib/Globalization/DateTimeFormatting.cs. +host:System.TimeSpan::this.ToString,this.TryFormat # CoreLib-internal helpers of reference-pack types that the code above calls, hosted from their own IL: the internal Vector128 load # from a char reference (Ordinal's vector paths; the generic loads stay the compiler's own), BitOperations.ResetLowestSetBit, and # ArgumentNullException's internal overloads. diff --git a/tests/platform-skips.txt b/tests/platform-skips.txt index d7b725d7e..1dddb51fe 100644 --- a/tests/platform-skips.txt +++ b/tests/platform-skips.txt @@ -362,3 +362,6 @@ wasi 1602_x509_pkcs12_key_storage_flags known gap: no OpenSSL on WebAssembly (W wasi 1603_tcplistener_disposable opens loopback sockets: WASI preview 1 has none (PlatformNotSupportedException) wasi 1579_runtime_events known gap: no runtime event session on WASI (its single thread cannot run EventPipe's dispatcher; runtime/events.c is empty there), as 1574 windows 1575_task_event_sources live: TplEventSource and AsyncProfilerEventSource are ETW providers on Windows, enabled by any ETW session the machine runs for them (IsEnabled reads the session state) +wasi 1604_timespan_format_edges no ICU on WASI (invariant globalization mode): the sample uses specific cultures (1605 covers TimeSpan formatting in invariant mode) +macos 1604_timespan_format_edges live: culture data comes from the OS's ICU (libicucore / icu.dll), not Linux's ICU 74 +windows 1604_timespan_format_edges live: culture data comes from the OS's ICU (libicucore / icu.dll), not Linux's ICU 74 diff --git a/tests/samples/1604_timespan_format_edges.cs b/tests/samples/1604_timespan_format_edges.cs new file mode 100644 index 000000000..680352533 --- /dev/null +++ b/tests/samples/1604_timespan_format_edges.cs @@ -0,0 +1,85 @@ +// TimeSpan formatting (#447, CoreLib's TimeSpanFormat from the framework's IL): every ToString overload and TryFormat (UTF-16 and UTF-8) +// on negative values, the extremes, custom formats with quotes and escapes, "c"/"g"/"G" with cultures, interpolation holes and boxed +// TimeSpans in composite formatting, and TryFormat into destinations one element too small (false, nothing past the end). +using System; +using System.Globalization; +using System.Text; + +TimeSpan[] spans = +{ + TimeSpan.Zero, new TimeSpan(1, 2, 3, 4, 567), new TimeSpan(-1, -2, -3, -4, -567), TimeSpan.FromTicks(1), TimeSpan.FromTicks(-1), + TimeSpan.FromTicks(10_000_001), new TimeSpan(0, 0, 0, 59, 999), TimeSpan.FromDays(10675199), TimeSpan.MaxValue, TimeSpan.MinValue, + TimeSpan.FromHours(-25.5), TimeSpan.FromMicroseconds(123), +}; +string[] formats = +{ + "c", "g", "G", @"d\.hh\:mm\:ss\.fffffff", @"%d", @"hh\:mm", "dd'd 'hh'h 'mm'm'", "'['h']'", "\"q\"s\"q\"", @"\'s\'", @"\""m", @"FFFFFFF", + @"fff\ \F", "ddddddd", @"%s\s", "s'\\''", "'a\\'b'F", +}; +var cultures = new[] { CultureInfo.InvariantCulture, new CultureInfo("fr-FR"), new CultureInfo("de-DE"), new CultureInfo("ar-SA"), new CultureInfo("fa-IR"), new CultureInfo("en-US") }; + +foreach (var span in spans) +{ + var line = new StringBuilder(); + line.Append(span.ToString()).Append(" | ").Append(span.ToString(null)).Append(" | ").Append(span.ToString("")).Append(" | ").Append(span.ToString(null, null)); + foreach (var f in formats) + { + try { line.Append(" | ").Append(span.ToString(f, CultureInfo.InvariantCulture)); } + catch (FormatException e) { line.Append(" | FormatException ").Append(e.Message); } + } + Console.WriteLine(line); +} + +foreach (var culture in cultures) +{ + var span = new TimeSpan(-3, -4, -5, -6, -78); + Console.WriteLine($"{culture.Name}: {span.ToString("c", culture)} {span.ToString("g", culture)} {span.ToString("G", culture)} {TimeSpan.FromTicks(15).ToString("g", culture)} {span.ToString(@"hh\:mm", culture)}"); + Console.WriteLine(string.Format(culture, "{0} {0:g} {0:G} {1:G} {0,20:c}|{0,-14:g}|", span, (object)TimeSpan.MaxValue)); + Console.WriteLine(span.ToString("G", culture.DateTimeFormat)); +} + +// Interpolation holes (with and without a format), and a boxed TimeSpan through object and IFormattable. +var t = new TimeSpan(4, 5, 6, 7, 89); +object boxed = t; +IFormattable formattable = t; +ISpanFormattable spanFormattable = t; +Console.WriteLine($"{t} {t:g} {t:G} {t,16} {t,-16:c}| {boxed} {formattable.ToString("G", new CultureInfo("fr-FR"))} {boxed:dd\\.hh}"); +Span scratch = stackalloc char[40]; +Console.WriteLine(spanFormattable.TryFormat(scratch, out int n, "g", CultureInfo.InvariantCulture) + " " + scratch[..n].ToString()); + +// TryFormat at every destination size up to the text: false (and 0 written, nothing past the end) until it fits. +foreach (var (span, format, culture) in new[] { (t, "", (IFormatProvider?)null), (-t, "G", new CultureInfo("fr-FR")), (TimeSpan.MinValue, "c", null), (t, @"d\'' days'", null) }) +{ + string expected = span.ToString(format, culture); + var chars = new StringBuilder(); + var bytes = new StringBuilder(); + for (int size = 0; size <= expected.Length + 1; size++) + { + var c = new char[size + 2]; + c.AsSpan().Fill('#'); + bool ok = span.TryFormat(c.AsSpan(0, size), out int written, format, culture); + chars.Append(ok ? $"[{written}:{new string(c, 0, written)}]" : $"[F{written}{(new string(c, size, 2) == "##" ? "" : "!overrun")}]"); + var b = new byte[size + 2]; + b.AsSpan().Fill((byte)'#'); + bool okUtf8 = span.TryFormat(b.AsSpan(0, size), out int bytesWritten, format, culture); + bytes.Append(okUtf8 ? $"[{bytesWritten}:{Encoding.UTF8.GetString(b, 0, bytesWritten)}]" : $"[F{bytesWritten}{(b[size] == '#' && b[size + 1] == '#' ? "" : "!overrun")}]"); + } + Console.WriteLine(expected); + Console.WriteLine(chars); + Console.WriteLine(bytes); +} + +// Invalid formats from TryFormat and the UTF-8 path: the same FormatException as ToString. +foreach (var bad in new[] { "x", "hhh", "'open", @"h\", "%", "%%", "dddddddddd", "T" }) +{ + Span d = stackalloc char[64]; + Span u = stackalloc byte[64]; + string r1, r2; + try { r1 = t.TryFormat(d, out int w, bad, null) ? d[..w].ToString() : "false"; } catch (FormatException e) { r1 = "FormatException: " + e.Message; } + try { r2 = t.TryFormat(u, out int w, bad, null) ? Encoding.UTF8.GetString(u[..w]) : "false"; } catch (FormatException e) { r2 = "FormatException: " + e.Message; } + Console.WriteLine($"{bad} -> {r1} / {r2}"); +} + +// Stopwatch.Elapsed and Stopwatch.ToString through the same formatter (a zero stopwatch, so the text is deterministic). +var sw = new System.Diagnostics.Stopwatch(); +Console.WriteLine($"{sw.Elapsed} {sw} {sw.Elapsed:g}"); diff --git a/tests/samples/1604_timespan_format_edges.expected b/tests/samples/1604_timespan_format_edges.expected new file mode 100644 index 000000000..fa516329e --- /dev/null +++ b/tests/samples/1604_timespan_format_edges.expected @@ -0,0 +1,53 @@ +00:00:00 | 00:00:00 | 00:00:00 | 00:00:00 | 00:00:00 | 0:00:00 | 0:00:00:00.0000000 | 0.00:00:00.0000000 | 0 | 00:00 | 00d 00h 00m | [0] | q0q | '0' | "0 | | 000 F | 0000000 | 0s | 0' | a'b +1.02:03:04.5670000 | 1.02:03:04.5670000 | 1.02:03:04.5670000 | 1.02:03:04.5670000 | 1.02:03:04.5670000 | 1:2:03:04.567 | 1:02:03:04.5670000 | 1.02:03:04.5670000 | 1 | 02:03 | 01d 02h 03m | [2] | q4q | '4' | "3 | 567 | 567 F | 0000001 | 4s | 4' | a'b5 +-1.02:03:04.5670000 | -1.02:03:04.5670000 | -1.02:03:04.5670000 | -1.02:03:04.5670000 | -1.02:03:04.5670000 | -1:2:03:04.567 | -1:02:03:04.5670000 | 1.02:03:04.5670000 | 1 | 02:03 | 01d 02h 03m | [2] | q4q | '4' | "3 | 567 | 567 F | 0000001 | 4s | 4' | a'b5 +00:00:00.0000001 | 00:00:00.0000001 | 00:00:00.0000001 | 00:00:00.0000001 | 00:00:00.0000001 | 0:00:00.0000001 | 0:00:00:00.0000001 | 0.00:00:00.0000001 | 0 | 00:00 | 00d 00h 00m | [0] | q0q | '0' | "0 | 0000001 | 000 F | 0000000 | 0s | 0' | a'b +-00:00:00.0000001 | -00:00:00.0000001 | -00:00:00.0000001 | -00:00:00.0000001 | -00:00:00.0000001 | -0:00:00.0000001 | -0:00:00:00.0000001 | 0.00:00:00.0000001 | 0 | 00:00 | 00d 00h 00m | [0] | q0q | '0' | "0 | 0000001 | 000 F | 0000000 | 0s | 0' | a'b +00:00:01.0000001 | 00:00:01.0000001 | 00:00:01.0000001 | 00:00:01.0000001 | 00:00:01.0000001 | 0:00:01.0000001 | 0:00:00:01.0000001 | 0.00:00:01.0000001 | 0 | 00:00 | 00d 00h 00m | [0] | q1q | '1' | "0 | 0000001 | 000 F | 0000000 | 1s | 1' | a'b +00:00:59.9990000 | 00:00:59.9990000 | 00:00:59.9990000 | 00:00:59.9990000 | 00:00:59.9990000 | 0:00:59.999 | 0:00:00:59.9990000 | 0.00:00:59.9990000 | 0 | 00:00 | 00d 00h 00m | [0] | q59q | '59' | "0 | 999 | 999 F | 0000000 | 59s | 59' | a'b9 +10675199.00:00:00 | 10675199.00:00:00 | 10675199.00:00:00 | 10675199.00:00:00 | 10675199.00:00:00 | 10675199:0:00:00 | 10675199:00:00:00.0000000 | 10675199.00:00:00.0000000 | 10675199 | 00:00 | 10675199d 00h 00m | [0] | q0q | '0' | "0 | | 000 F | 10675199 | 0s | 0' | a'b +10675199.02:48:05.4775807 | 10675199.02:48:05.4775807 | 10675199.02:48:05.4775807 | 10675199.02:48:05.4775807 | 10675199.02:48:05.4775807 | 10675199:2:48:05.4775807 | 10675199:02:48:05.4775807 | 10675199.02:48:05.4775807 | 10675199 | 02:48 | 10675199d 02h 48m | [2] | q5q | '5' | "48 | 4775807 | 477 F | 10675199 | 5s | 5' | a'b4 +-10675199.02:48:05.4775808 | -10675199.02:48:05.4775808 | -10675199.02:48:05.4775808 | -10675199.02:48:05.4775808 | -10675199.02:48:05.4775808 | -10675199:2:48:05.4775808 | -10675199:02:48:05.4775808 | 10675199.02:48:05.4775808 | 10675199 | 02:48 | 10675199d 02h 48m | [2] | q5q | '5' | "48 | 4775808 | 477 F | 10675199 | 5s | 5' | a'b4 +-1.01:30:00 | -1.01:30:00 | -1.01:30:00 | -1.01:30:00 | -1.01:30:00 | -1:1:30:00 | -1:01:30:00.0000000 | 1.01:30:00.0000000 | 1 | 01:30 | 01d 01h 30m | [1] | q0q | '0' | "30 | | 000 F | 0000001 | 0s | 0' | a'b +00:00:00.0001230 | 00:00:00.0001230 | 00:00:00.0001230 | 00:00:00.0001230 | 00:00:00.0001230 | 0:00:00.000123 | 0:00:00:00.0001230 | 0.00:00:00.0001230 | 0 | 00:00 | 00d 00h 00m | [0] | q0q | '0' | "0 | 000123 | 000 F | 0000000 | 0s | 0' | a'b +: -3.04:05:06.0780000 -3:4:05:06.078 -3:04:05:06.0780000 0:00:00.0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06.078 -3:04:05:06.0780000 10675199:02:48:05.4775807 -3.04:05:06.0780000|-3:4:05:06.078| +-3:04:05:06.0780000 +fr-FR: -3.04:05:06.0780000 -3:4:05:06,078 -3:04:05:06,0780000 0:00:00,0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06,078 -3:04:05:06,0780000 10675199:02:48:05,4775807 -3.04:05:06.0780000|-3:4:05:06,078| +-3:04:05:06,0780000 +de-DE: -3.04:05:06.0780000 -3:4:05:06,078 -3:04:05:06,0780000 0:00:00,0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06,078 -3:04:05:06,0780000 10675199:02:48:05,4775807 -3.04:05:06.0780000|-3:4:05:06,078| +-3:04:05:06,0780000 +ar-SA: -3.04:05:06.0780000 -3:4:05:06٫078 -3:04:05:06٫0780000 0:00:00٫0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06٫078 -3:04:05:06٫0780000 10675199:02:48:05٫4775807 -3.04:05:06.0780000|-3:4:05:06٫078| +-3:04:05:06٫0780000 +fa-IR: -3.04:05:06.0780000 -3:4:05:06٫078 -3:04:05:06٫0780000 0:00:00٫0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06٫078 -3:04:05:06٫0780000 10675199:02:48:05٫4775807 -3.04:05:06.0780000|-3:4:05:06٫078| +-3:04:05:06٫0780000 +en-US: -3.04:05:06.0780000 -3:4:05:06.078 -3:04:05:06.0780000 0:00:00.0000015 04:05 +-3.04:05:06.0780000 -3:4:05:06.078 -3:04:05:06.0780000 10675199:02:48:05.4775807 -3.04:05:06.0780000|-3:4:05:06.078| +-3:04:05:06.0780000 +4.05:06:07.0890000 4:5:06:07.089 4:05:06:07.0890000 4.05:06:07.0890000 4.05:06:07.0890000| 4.05:06:07.0890000 4:05:06:07,0890000 04.05 +True 4:5:06:07.089 +4.05:06:07.0890000 +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][18:4.05:06:07.0890000][18:4.05:06:07.0890000] +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][18:4.05:06:07.0890000][18:4.05:06:07.0890000] +-4:05:06:07,0890000 +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][19:-4:05:06:07,0890000][19:-4:05:06:07,0890000] +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][19:-4:05:06:07,0890000][19:-4:05:06:07,0890000] +-10675199.02:48:05.4775808 +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][26:-10675199.02:48:05.4775808][26:-10675199.02:48:05.4775808] +[F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][F0][26:-10675199.02:48:05.4775808][26:-10675199.02:48:05.4775808] +4' days +[F0][F0][F0][F0][F0][F0][F0][7:4' days][7:4' days] +[F0][F0][F0][F0][F0][F0][F0][7:4' days][7:4' days] +x -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +hhh -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +'open -> FormatException: Cannot find a matching quote character for the character '''. / FormatException: Cannot find a matching quote character for the character '''. +h\ -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +% -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +%% -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +dddddddddd -> FormatException: Input string was not in a correct format. / FormatException: Input string was not in a correct format. +T -> 4.05:06:07.0890000 / 4.05:06:07.0890000 +00:00:00 00:00:00 0:00:00 diff --git a/tests/samples/1605_timespan_format_invariant.cs b/tests/samples/1605_timespan_format_invariant.cs new file mode 100644 index 000000000..803ced60d --- /dev/null +++ b/tests/samples/1605_timespan_format_invariant.cs @@ -0,0 +1,26 @@ +// TimeSpan formatting under invariant globalization mode (#447): only the invariant culture exists there (a named culture is a +// CultureNotFoundException), and "g"/"G" take their decimal separator from the culture's data, not its NumberFormat, so a copy with +// another NumberDecimalSeparator still prints '.'; custom formats, TryFormat (UTF-16 and UTF-8) and composite formatting too. +using System; +using System.Globalization; +using System.Text; + +var spans = new[] { new TimeSpan(1, 2, 3, 4, 567), new TimeSpan(-2, -3, -4, -5, -6), TimeSpan.MinValue, TimeSpan.FromTicks(7) }; +foreach (var separator in new[] { null, ",", "" }) +{ + var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + if (separator is not null) culture.NumberFormat.NumberDecimalSeparator = separator; + string name = separator ?? "invariant"; + foreach (var span in spans) + Console.WriteLine($"[{name}] {span.ToString("c", culture)} {span.ToString("g", culture)} {span.ToString("G", culture)} {span.ToString(@"d\:hh\-mm\'ss\""FFF", culture)} " + + string.Format(culture, "{0:G}|{0,24:g}|", span)); +} +var comma = (CultureInfo)CultureInfo.InvariantCulture.Clone(); +comma.NumberFormat.NumberDecimalSeparator = ","; +CultureInfo.CurrentCulture = comma; +var t = new TimeSpan(0, 1, 2, 3, 400); +Console.WriteLine($"{t:G} {t:g} {t.ToString("G")} {t}"); +Span chars = stackalloc char[8]; +Span bytes = stackalloc byte[30]; +Console.WriteLine($"{t.TryFormat(chars, out int c, "G")} {c} {t.TryFormat(bytes, out int b, "G")} {b} {Encoding.UTF8.GetString(bytes[..b])}"); +try { t.ToString("G", new CultureInfo("fr-FR")); } catch (CultureNotFoundException e) { Console.WriteLine(e.GetType().Name + " " + e.InvalidCultureName); } diff --git a/tests/samples/1605_timespan_format_invariant.env b/tests/samples/1605_timespan_format_invariant.env new file mode 100644 index 000000000..b0fa8dd4a --- /dev/null +++ b/tests/samples/1605_timespan_format_invariant.env @@ -0,0 +1 @@ +DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 diff --git a/tests/samples/1605_timespan_format_invariant.expected b/tests/samples/1605_timespan_format_invariant.expected new file mode 100644 index 000000000..6bb36c000 --- /dev/null +++ b/tests/samples/1605_timespan_format_invariant.expected @@ -0,0 +1,15 @@ +[invariant] 1.02:03:04.5670000 1:2:03:04.567 1:02:03:04.5670000 1:02-03'04"567 1:02:03:04.5670000| 1:2:03:04.567| +[invariant] -2.03:04:05.0060000 -2:3:04:05.006 -2:03:04:05.0060000 2:03-04'05"006 -2:03:04:05.0060000| -2:3:04:05.006| +[invariant] -10675199.02:48:05.4775808 -10675199:2:48:05.4775808 -10675199:02:48:05.4775808 10675199:02-48'05"477 -10675199:02:48:05.4775808|-10675199:2:48:05.4775808| +[invariant] 00:00:00.0000007 0:00:00.0000007 0:00:00:00.0000007 0:00-00'00" 0:00:00:00.0000007| 0:00:00.0000007| +[,] 1.02:03:04.5670000 1:2:03:04.567 1:02:03:04.5670000 1:02-03'04"567 1:02:03:04.5670000| 1:2:03:04.567| +[,] -2.03:04:05.0060000 -2:3:04:05.006 -2:03:04:05.0060000 2:03-04'05"006 -2:03:04:05.0060000| -2:3:04:05.006| +[,] -10675199.02:48:05.4775808 -10675199:2:48:05.4775808 -10675199:02:48:05.4775808 10675199:02-48'05"477 -10675199:02:48:05.4775808|-10675199:2:48:05.4775808| +[,] 00:00:00.0000007 0:00:00.0000007 0:00:00:00.0000007 0:00-00'00" 0:00:00:00.0000007| 0:00:00.0000007| +[] 1.02:03:04.5670000 1:2:03:04.567 1:02:03:04.5670000 1:02-03'04"567 1:02:03:04.5670000| 1:2:03:04.567| +[] -2.03:04:05.0060000 -2:3:04:05.006 -2:03:04:05.0060000 2:03-04'05"006 -2:03:04:05.0060000| -2:3:04:05.006| +[] -10675199.02:48:05.4775808 -10675199:2:48:05.4775808 -10675199:02:48:05.4775808 10675199:02-48'05"477 -10675199:02:48:05.4775808|-10675199:2:48:05.4775808| +[] 00:00:00.0000007 0:00:00.0000007 0:00:00:00.0000007 0:00-00'00" 0:00:00:00.0000007| 0:00:00.0000007| +0:01:02:03.4000000 1:02:03.4 0:01:02:03.4000000 01:02:03.4000000 +False 0 True 18 0:01:02:03.4000000 +CultureNotFoundException fr-FR diff --git a/tools/il-first/bench/timespan_format_throughput.cs b/tools/il-first/bench/timespan_format_throughput.cs new file mode 100644 index 000000000..acabaf357 --- /dev/null +++ b/tools/il-first/bench/timespan_format_throughput.cs @@ -0,0 +1,29 @@ +// TimeSpan formatting throughput, the program behind the TimeSpan row of docs/il-first/System.Globalization.md (#447): ToString() and the +// "c"/"g"/"G" standard formats under the invariant culture and a named one (fr-FR: ',' decimal separator), custom formats with quotes and +// escapes, TryFormat into UTF-16 and UTF-8 buffers, and interpolation holes. The checksum depends on the fixed inputs only. +using System; +using System.Globalization; + +class Program +{ + static void Main() + { + long check = 0; + var inv = CultureInfo.InvariantCulture; + var fr = CultureInfo.GetCultureInfo("fr-FR"); + Span chars = stackalloc char[64]; + Span bytes = stackalloc byte[64]; + string[] customs = [@"hh\:mm\:ss", @"d\.hh\:mm\:ss\.fff", "dd'd 'hh'h 'mm'm'", @"%h\h\ FFFFFFF"]; + for (int i = 0; i < 400_000; i++) + { + var t = TimeSpan.FromTicks((long)(i - 200_000) * 1_234_567_891L + i); + check += t.ToString().Length; + check += t.ToString("g", inv).Length + t.ToString("G", fr).Length; + check += t.ToString(customs[i & 3]).Length; + if (t.TryFormat(chars, out int w, (i & 1) == 0 ? "c" : "g", fr)) check += w; + if (t.TryFormat(bytes, out int b, customs[(i >> 2) & 3], inv)) check += b; + check += $"{t} {t:G}".Length; + } + Console.WriteLine(check); + } +}