diff --git a/apiCount.include.md b/apiCount.include.md index 74a7b5bf..e4238911 100644 --- a/apiCount.include.md +++ b/apiCount.include.md @@ -1 +1 @@ -**API count: 594** \ No newline at end of file +**API count: 617** \ No newline at end of file diff --git a/api_list.include.md b/api_list.include.md index 9ca71863..07d2f569 100644 --- a/api_list.include.md +++ b/api_list.include.md @@ -8,15 +8,22 @@ * `ArraySegmentEnumerator GetEnumerator()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.arraysegment-1.getenumerator?view=net-10.0) -#### bool +#### Boolean * `bool TryFormat(Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.boolean.tryformat?view=net-10.0) -#### byte +#### Byte * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat?view=net-10.0#system-byte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat?view=net-10.0#system-byte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(string?, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@)) #### CancellationToken @@ -46,6 +53,20 @@ * `void Clear()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1.clear?view=net-10.0) +#### Convert + + * `byte[] FromHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char)))) + * `byte[] FromHexString(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string)) + * `string ToHexString(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32)) + * `string ToHexString(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte())) + * `string ToHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte)))) + * `string ToHexStringLower(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32)) + * `string ToHexStringLower(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte())) + * `string ToHexStringLower(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte)))) + * `bool TryToHexString(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0) + * `bool TryToHexStringLower(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0) + + #### DateOnly * `void Deconstruct(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.dateonly.deconstruct?view=net-10.0) @@ -62,6 +83,12 @@ * `int Nanosecond()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.nanosecond?view=net-10.0) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat?view=net-10.0#system-datetime-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat?view=net-10.0#system-datetime-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) + * `bool TryParse(string?, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) + * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) #### DateTimeOffset @@ -72,9 +99,15 @@ * `int Nanosecond()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.nanosecond?view=net-10.0) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat?view=net-10.0#system-datetimeoffset-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat?view=net-10.0#system-datetimeoffset-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) + * `bool TryParse(string?, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) + * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) -#### decimal +#### Decimal * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat?view=net-10.0#system-decimal-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat?view=net-10.0#system-decimal-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) @@ -87,7 +120,8 @@ #### Delegate - * `bool HasSingleTarget()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0) + * `InvocationListEnumerator EnumerateInvocationList(TDelegate?) where TDelegate : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0) + * `HasSingleTarget` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0) #### Dictionary @@ -102,10 +136,17 @@ * `void Deconstruct(object, object?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.dictionaryentry.deconstruct?view=net-10.0#system-collections-dictionaryentry-deconstruct(system-object@-system-object@)) -#### double +#### Double * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat?view=net-10.0#system-double-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat?view=net-10.0#system-double-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@)) + * `bool TryParse(string?, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)) #### Encoding @@ -119,6 +160,31 @@ * `bool TryGetChars(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.trygetchars?view=net-10.0) +#### Enum + + * `string[] GetNames() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0) + * `TEnum[] GetValues() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0) + * `bool IsDefined(TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0)) + * `TEnum Parse(ReadOnlySpan, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean)) + * `TEnum Parse(ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char)))) + * `TEnum Parse(string, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) + * `TEnum Parse(string) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) + * `bool TryFormat(TEnum, Span, int, ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0) + * `bool TryParse(ReadOnlySpan, bool, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@)) + * `bool TryParse(ReadOnlySpan, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@)) + + +#### Enumerable + + * `IEnumerable InfiniteSequence(T, T) where T : IAdditionOperators` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.infinitesequence?view=net-10.0) + * `IEnumerable Sequence(T, T, T) where T : INumber` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequence?view=net-10.0) + + +#### Environment + + * `ProcessId` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.environment.processid?view=net-10.0#system-environment-processid) + + #### EventInfo * `NullabilityState GetNullability()` @@ -133,16 +199,54 @@ * `bool IsNullable()` -#### float +#### File + + * `void AppendAllBytes(string, byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte())) + * `void AppendAllBytes(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte)))) + * `Task AppendAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) + * `Task AppendAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) + * `Task AppendAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) + * `Task AppendAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) + * `void AppendAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) + * `void AppendAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char)))) + * `Task AppendAllTextAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, ReadOnlyMemory, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + * `void Move(string, string, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0) + * `Task ReadAllBytesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0) + * `Task ReadAllLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) + * `Task ReadAllLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task ReadAllTextAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken)) + * `Task ReadAllTextAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `IAsyncEnumerable ReadLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) + * `IAsyncEnumerable ReadLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task WriteAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) + * `Task WriteAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) + * `Task WriteAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) + * `Task WriteAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) + * `void WriteAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) + * `void WriteAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char)))) + * `Task WriteAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task WriteAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + + +#### FileUnixMode - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) #### Guid * `bool TryFormat(Span, int, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat?view=net-10.0#system-guid-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char)))) * `bool TryFormat(Span, int, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat?view=net-10.0#system-guid-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char)))) + * `Guid CreateVersion7()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7) + * `Guid CreateVersion7(DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset)) + * `Guid Parse(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.parse?view=net-10.0#system-guid-parse(system-readonlyspan((system-byte)))) + * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-byte))-system-guid@)) + * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@)) + * `bool TryParse(string?, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@)) #### HashSet @@ -225,10 +329,43 @@ * `ReadOnlyCollection AsReadOnly()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.asreadonly?view=net-10.0#system-collections-generic-collectionextensions-asreadonly-1(system-collections-generic-ilist((-0)))) -#### int +#### Int16 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@)) + * `bool TryParse(string?, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@)) + + +#### Int32 * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat?view=net-10.0#system-int32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat?view=net-10.0#system-int32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(string?, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@)) + + +#### Int64 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(string?, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@)) #### IReadOnlyDictionary @@ -256,10 +393,21 @@ * `void TrimExcess()` -#### long +#### Math - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `byte Clamp(byte, byte, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `decimal Clamp(decimal, decimal, decimal)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `double Clamp(double, double, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `float Clamp(float, float, float)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `int Clamp(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `long Clamp(long, long, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `nint Clamp(nint, nint, nint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `nuint Clamp(nuint, nuint, nuint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `sbyte Clamp(sbyte, sbyte, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `short Clamp(short, short, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `uint Clamp(uint, uint, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `ulong Clamp(ulong, ulong, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `ushort Clamp(ushort, ushort, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) #### MemberInfo @@ -276,6 +424,31 @@ * `T CreateDelegate() where T : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/System.Reflection.MethodInfo.CreateDelegate?view=net-10.0#system-reflection-methodinfo-createdelegate-1) +#### OperatingSystem + + * `bool IsAndroid()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0) + * `bool IsAndroidVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0) + * `bool IsBrowser()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0) + * `bool IsFreeBSD()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0) + * `bool IsFreeBSDVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0) + * `bool IsIOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0) + * `bool IsIOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0) + * `bool IsLinux()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0) + * `bool IsMacCatalyst()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0) + * `bool IsMacCatalystVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0) + * `bool IsMacOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0) + * `bool IsMacOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0) + * `bool IsOSPlatform(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0) + * `bool IsOSPlatformVersionAtLeast(string, int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0) + * `bool IsTvOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0) + * `bool IsTvOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0) + * `bool IsWasi()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0) + * `bool IsWatchOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0) + * `bool IsWatchOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0) + * `bool IsWindows()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0) + * `bool IsWindowsVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0) + + #### OrderedDictionary * `bool TryAdd(TKey, TValue, int) where TKey : notnull` [reference](https://github.com/dotnet/core/blob/main/release-notes/10.0/preview/preview1/libraries.md#additional-tryadd-and-trygetvalue-overloads-for-ordereddictionarytkey-tvalue?view=net-10.0) @@ -289,6 +462,21 @@ * `bool IsNullable()` +#### Path + + * `string Combine(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string)))) + * `bool EndsInDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char)))) + * `bool EndsInDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string)) + * `bool Exists(string?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0) + * `ReadOnlySpan GetDirectoryName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetFileName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) + * `bool HasExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) + * `ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char)))) + * `string TrimEndingDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string)) + + #### Process * `void Kill(bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.kill?view=net-10.0#system-diagnostics-process-kill(system-boolean)) @@ -316,6 +504,21 @@ * `void NextBytes(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) * `void Shuffle(T[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) + * `Shared` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-10.0) + + +#### RandomNumberGenerator + + * `void Fill(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0) + * `byte[] GetBytes(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32)) + * `string GetHexString(int, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean)) + * `void GetHexString(Span, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) + * `int GetInt32(int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32)) + * `int GetInt32(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32)) + * `T[] GetItems(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32)) + * `void GetItems(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0)))) + * `string GetString(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) + * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0) #### ReadOnlySpan @@ -354,18 +557,55 @@ * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char)))) * `bool IsMatch(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-int32)) * `bool IsMatch(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char)))) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string)) + * `bool IsMatch(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) + * `bool IsMatch(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) + * `bool IsMatch(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string)) -#### sbyte +#### SByte * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat?view=net-10.0#system-sbyte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat?view=net-10.0#system-sbyte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@)) + * `bool TryParse(string?, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@)) -#### short +#### SHA256 - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte())) + * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) + * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte)))) + * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte)))) + * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream)) + * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken)) + * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) + * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0) + + +#### SHA512 + + * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte())) + * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) + * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte)))) + * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte)))) + * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream)) + * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken)) + * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) + * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0) + + +#### Single + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) #### SortedList @@ -414,7 +654,7 @@ * `ValueTask WriteAsync(ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.writeasync?view=net-10.0#system-io-stream-writeasync(system-readonlymemory((system-byte))-system-threading-cancellationtoken)) -#### string +#### String * `bool Contains(char, StringComparison)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=net-10.0#system-string-contains(system-char-system-stringcomparison)) * `bool Contains(char)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=net-10.0#system-string-contains(system-char)) @@ -431,6 +671,16 @@ * `string[] Split(string, StringSplitOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-10.0#system-string-split(system-string-system-stringsplitoptions)) * `bool StartsWith(char)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith?view=net-10.0#system-string-startswith(system-char)) * `bool TryCopyTo(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.trycopyto?view=net-10.0) + * `int GetHashCode(ReadOnlySpan, StringComparison)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char))-system-stringcomparison)) + * `int GetHashCode(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char)))) + * `string Join(char, object?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object())) + * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object)))) + * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string)))) + * `string Join(char, string?[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32)) + * `string Join(char, string?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string())) + * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object)))) + * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string)))) + * `string Join(char, IEnumerable)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0)))) #### StringBuilder @@ -526,22 +776,43 @@ * `bool IsGenericMethodParameter()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.type.isgenericmethodparameter?view=net-10.0) -#### uint - - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt16 + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@)) + * `bool TryParse(string?, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@)) -#### ulong - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt32 + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@)) + * `bool TryParse(string?, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@)) -#### ushort - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt64 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@)) + * `bool TryParse(string?, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@)) #### XDocument @@ -549,6 +820,9 @@ * `Task SaveAsync(Stream, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-io-stream-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(TextWriter, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-io-textwriter-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(XmlWriter, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-xml-xmlwriter-system-threading-cancellationtoken)) + * `Task LoadAsync(Stream, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(TextReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(XmlReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) #### XElement @@ -556,6 +830,9 @@ * `Task SaveAsync(Stream, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-io-stream-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(TextWriter, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-io-textwriter-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(XmlWriter, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-xml-xmlwriter-system-threading-cancellationtoken)) + * `Task LoadAsync(Stream, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(TextReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(XmlReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) #### ZipArchive @@ -572,339 +849,29 @@ * `Task ExtractToFileAsync(string, bool, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.extracttofileasync?view=net-10.0#system-io-compression-zipfileextensions-extracttofileasync(system-io-compression-ziparchiveentry-system-string-system-boolean-system-threading-cancellationtoken)) * `Task ExtractToFileAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.extracttofileasync?view=net-10.0#system-io-compression-zipfileextensions-extracttofileasync(system-io-compression-ziparchiveentry-system-string-system-threading-cancellationtoken)) * `Task OpenAsync(CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.openasync?view=net-10.0) + * `ExternalAttributes` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.externalattributes?view=net-10.0) -### Static helpers - -#### BytePolyfill - - * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(string?, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@)) - - -#### ConvertPolyfill - - * `byte[] FromHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char)))) - * `byte[] FromHexString(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string)) - * `string ToHexString(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32)) - * `string ToHexString(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte())) - * `string ToHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte)))) - * `string ToHexStringLower(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32)) - * `string ToHexStringLower(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte())) - * `string ToHexStringLower(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte)))) - * `bool TryToHexString(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0) - * `bool TryToHexStringLower(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0) - - -#### DateTimeOffsetPolyfill - - * `bool TryParse(ReadOnlySpan, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - * `bool TryParse(string?, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - - -#### DateTimePolyfill - - * `bool TryParse(ReadOnlySpan, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - * `bool TryParse(string?, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - - -#### DelegatePolyfill - - * `InvocationListEnumerator EnumerateInvocationList(TDelegate?) where TDelegate : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0) - - -#### DoublePolyfill - - * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@)) - * `bool TryParse(string?, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)) - - -#### EnumPolyfill - - * `string[] GetNames() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0) - * `TEnum[] GetValues() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0) - * `bool IsDefined(TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0)) - * `TEnum Parse(ReadOnlySpan, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean)) - * `TEnum Parse(ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char)))) - * `TEnum Parse(string, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) - * `TEnum Parse(string) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) - * `bool TryFormat(TEnum, Span, int, ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0) - * `bool TryParse(ReadOnlySpan, bool, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@)) - * `bool TryParse(ReadOnlySpan, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@)) - - -#### FilePolyfill - - * `void AppendAllBytes(string, byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte())) - * `void AppendAllBytes(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte)))) - * `Task AppendAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) - * `Task AppendAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) - * `Task AppendAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) - * `Task AppendAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) - * `void AppendAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) - * `void AppendAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char)))) - * `Task AppendAllTextAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, ReadOnlyMemory, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - * `UnixFileMode GetUnixFileMode(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.getunixfilemode?view=net-10.0#system-io-file-getunixfilemode(system-string)) - * `void Move(string, string, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0) - * `Task ReadAllBytesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0) - * `Task ReadAllLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) - * `Task ReadAllLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `Task ReadAllTextAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken)) - * `Task ReadAllTextAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `IAsyncEnumerable ReadLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) - * `IAsyncEnumerable ReadLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `void SetUnixFileMode(string, UnixFileMode)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setunixfilemode?view=net-10.0#system-io-file-setunixfilemode(system-string-system-io-unixfilemode)) - * `Task WriteAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) - * `Task WriteAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) - * `Task WriteAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) - * `Task WriteAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) - * `void WriteAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) - * `void WriteAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char)))) - * `Task WriteAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - * `Task WriteAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - - -#### GuidPolyfill - - * `Guid CreateVersion7()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7) - * `Guid CreateVersion7(DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset)) - * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@)) - * `bool TryParse(string?, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@)) - - -#### IntPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(string?, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@)) - - -#### LongPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(string?, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@)) - - -#### MathPolyfill - - * `byte Clamp(byte, byte, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `decimal Clamp(decimal, decimal, decimal)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `double Clamp(double, double, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `float Clamp(float, float, float)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `int Clamp(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `long Clamp(long, long, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `nint Clamp(nint, nint, nint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `nuint Clamp(nuint, nuint, nuint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `sbyte Clamp(sbyte, sbyte, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `short Clamp(short, short, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `uint Clamp(uint, uint, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `ulong Clamp(ulong, ulong, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `ushort Clamp(ushort, ushort, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - - -#### OperatingSystemPolyfill - - * `bool IsAndroid()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0) - * `bool IsAndroidVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0) - * `bool IsBrowser()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0) - * `bool IsFreeBSD()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0) - * `bool IsFreeBSDVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0) - * `bool IsIOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0) - * `bool IsIOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0) - * `bool IsLinux()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0) - * `bool IsMacCatalyst()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0) - * `bool IsMacCatalystVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0) - * `bool IsMacOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0) - * `bool IsMacOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0) - * `bool IsOSPlatform(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0) - * `bool IsOSPlatformVersionAtLeast(string, int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0) - * `bool IsTvOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0) - * `bool IsTvOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0) - * `bool IsWasi()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0) - * `bool IsWatchOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0) - * `bool IsWatchOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0) - * `bool IsWindows()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0) - * `bool IsWindowsVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0) - - -#### PathPolyfill - - * `string Combine(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string)))) - * `bool EndsInDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char)))) - * `bool EndsInDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string)) - * `bool Exists(string?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0) - * `ReadOnlySpan GetDirectoryName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetFileName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) - * `bool HasExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) - * `ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char)))) - * `string TrimEndingDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string)) - - -#### RandomNumberGeneratorPolyfill - - * `void Fill(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0) - * `byte[] GetBytes(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32)) - * `string GetHexString(int, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean)) - * `void GetHexString(Span, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) - * `int GetInt32(int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32)) - * `int GetInt32(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32)) - * `T[] GetItems(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32)) - * `void GetItems(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0)))) - * `string GetString(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) - * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0) - - -#### RandomPolyfill - - - -#### RegexPolyfill - - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string)) - * `bool IsMatch(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) - * `bool IsMatch(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) - * `bool IsMatch(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string)) - - -#### SBytePolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@)) - * `bool TryParse(string?, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@)) - - -#### SHA256Polyfill - - * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte())) - * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) - * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte)))) - * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte)))) - * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream)) - * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken)) - * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) - * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0) - - -#### SHA512Polyfill - - * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte())) - * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) - * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte)))) - * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte)))) - * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream)) - * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken)) - * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) - * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0) - - -#### ShortPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@)) - * `bool TryParse(string?, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@)) - - -#### StringPolyfill - - * `string Join(char, object?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object())) - * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object)))) - * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string)))) - * `string Join(char, string?[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32)) - * `string Join(char, string?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string())) - * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object)))) - * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string)))) - * `string Join(char, IEnumerable)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0)))) - - -#### UIntPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@)) - * `bool TryParse(string?, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@)) - - -#### ULongPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@)) - * `bool TryParse(string?, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@)) - - -#### UShortPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@)) - * `bool TryParse(string?, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@)) - - -#### Guard +#### Ensure * `void DirectoryExists(string)` + * `T Equal(T, T)` * `void FileExists(string)` - * `void NotEmpty(string?)` - * `void NotEmpty(Memory?)` - * `void NotEmpty(Memory)` - * `void NotEmpty(ReadOnlyMemory?)` - * `void NotEmpty(ReadOnlyMemory)` - * `void NotEmpty(ReadOnlySpan)` - * `void NotEmpty(Span)` - * `void NotEmpty(T?) where T : IEnumerable` + * `string? NotEmpty(string?)` + * `Memory? NotEmpty(Memory?)` + * `Memory NotEmpty(Memory)` + * `ReadOnlyMemory? NotEmpty(ReadOnlyMemory?)` + * `ReadOnlyMemory NotEmpty(ReadOnlyMemory)` + * `ReadOnlySpan NotEmpty(ReadOnlySpan)` + * `Span NotEmpty(Span)` + * `T? NotEmpty(T?) where T : IEnumerable` + * `T NotEqual(T, T)` + * `T NotGreaterThan(T, T) where T : IComparable` + * `T NotGreaterThanOrEqual(T, T) where T : IComparable` + * `T NotLessThan(T, T) where T : IComparable` + * `T NotLessThanOrEqual(T, T) where T : IComparable` + * `T NotNegative(T) where T : struct, IComparable` + * `T NotNegativeOrZero(T) where T : struct, IComparable` * `string NotNull(string?)` * `T NotNull(T?) where T : class` * `Memory NotNullOrEmpty(Memory?)` @@ -914,11 +881,12 @@ * `Memory NotNullOrWhiteSpace(Memory?)` * `ReadOnlyMemory NotNullOrWhiteSpace(ReadOnlyMemory?)` * `string NotNullOrWhiteSpace(string?)` - * `void NotWhiteSpace(Memory?)` - * `void NotWhiteSpace(ReadOnlyMemory?)` - * `void NotWhiteSpace(ReadOnlySpan)` - * `void NotWhiteSpace(Span)` - * `void NotWhiteSpace(string?)` + * `Memory? NotWhiteSpace(Memory?)` + * `ReadOnlyMemory? NotWhiteSpace(ReadOnlyMemory?)` + * `ReadOnlySpan NotWhiteSpace(ReadOnlySpan)` + * `Span NotWhiteSpace(Span)` + * `string? NotWhiteSpace(string?)` + * `T NotZero(T) where T : struct, IComparable` #### Lock diff --git a/consuming.md b/consuming.md index 58faeb92..35ea7af8 100644 --- a/consuming.md +++ b/consuming.md @@ -2,6 +2,11 @@ The default type visibility for all polyfills is `internal`. This means it can be consumed in multiple projects and types will not conflict. +## Recommended consuming pattern + +The recommended general way to consume polyfill is to use the source package (`Polyfill`, not `PolyfillLib`), with all types being `internal` (default). As many projects use `InternalsVisibleTo`, this can result in conflicts. To resolve this, specify `true` under a `PropertyGroup`. That way, every project will have its "embedded" version of the types of Polyfill. Simply put, "embedded" means that even if `InternalsVisibleTo` is used, the "embedded" types are still not visible to the other assemblies. + +Alternatively, and depending on your specific scenario, below states other ways to consume Polyfill. ## Consuming in an app @@ -27,4 +32,3 @@ If, however, `InternalsVisibleTo` is being used to expose APIs (for example to t * [PolyfillLib](polyfill-lib.md) * [Polyfill and TargetFrameworks](target-frameworks.md) - diff --git a/contributing.md b/contributing.md index 3301614d..7f16ef1d 100644 --- a/contributing.md +++ b/contributing.md @@ -149,6 +149,9 @@ using System.Diagnostics.CodeAnalysis; [AttributeUsage( validOn: AttributeTargets.Method, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif @@ -159,7 +162,7 @@ using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(ModuleInitializerAttribute))] #endif ``` -snippet source | anchor +snippet source | anchor diff --git a/readme.md b/readme.md index d889d0d1..740b296f 100644 --- a/readme.md +++ b/readme.md @@ -13,7 +13,7 @@ The package targets `netstandard2.0` and is designed to support the following ru * `uap10` -**API count: 594** +**API count: 617** **See [Milestones](../../milestones?state=closed) for release notes.** @@ -340,11 +340,11 @@ Reference: [CallerArgumentExpression](https://learn.microsoft.com/en-us/dotnet/c ```cs static class FileUtil { - public static void FileExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + public static void FileExists(string path, [CallerArgumentExpression("path")] string name = "") { if (!File.Exists(path)) { - throw new ArgumentException($"File not found. Path: {path}", argumentName); + throw new ArgumentException($"File not found. Path: {path}", name); } } } @@ -454,15 +454,22 @@ The class `Polyfill` includes the following extension methods: * `ArraySegmentEnumerator GetEnumerator()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.arraysegment-1.getenumerator?view=net-10.0) -#### bool +#### Boolean * `bool TryFormat(Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.boolean.tryformat?view=net-10.0) -#### byte +#### Byte * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat?view=net-10.0#system-byte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat?view=net-10.0#system-byte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) + * `bool TryParse(string?, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@)) #### CancellationToken @@ -492,6 +499,20 @@ The class `Polyfill` includes the following extension methods: * `void Clear()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1.clear?view=net-10.0) +#### Convert + + * `byte[] FromHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char)))) + * `byte[] FromHexString(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string)) + * `string ToHexString(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32)) + * `string ToHexString(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte())) + * `string ToHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte)))) + * `string ToHexStringLower(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32)) + * `string ToHexStringLower(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte())) + * `string ToHexStringLower(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte)))) + * `bool TryToHexString(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0) + * `bool TryToHexStringLower(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0) + + #### DateOnly * `void Deconstruct(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.dateonly.deconstruct?view=net-10.0) @@ -508,6 +529,12 @@ The class `Polyfill` includes the following extension methods: * `int Nanosecond()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.nanosecond?view=net-10.0) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat?view=net-10.0#system-datetime-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat?view=net-10.0#system-datetime-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) + * `bool TryParse(string?, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) + * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) #### DateTimeOffset @@ -518,9 +545,15 @@ The class `Polyfill` includes the following extension methods: * `int Nanosecond()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.nanosecond?view=net-10.0) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat?view=net-10.0#system-datetimeoffset-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat?view=net-10.0#system-datetimeoffset-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) + * `bool TryParse(string?, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) + * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) -#### decimal +#### Decimal * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat?view=net-10.0#system-decimal-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat?view=net-10.0#system-decimal-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) @@ -533,7 +566,8 @@ The class `Polyfill` includes the following extension methods: #### Delegate - * `bool HasSingleTarget()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0) + * `InvocationListEnumerator EnumerateInvocationList(TDelegate?) where TDelegate : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0) + * `HasSingleTarget` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0) #### Dictionary @@ -548,10 +582,17 @@ The class `Polyfill` includes the following extension methods: * `void Deconstruct(object, object?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.dictionaryentry.deconstruct?view=net-10.0#system-collections-dictionaryentry-deconstruct(system-object@-system-object@)) -#### double +#### Double * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat?view=net-10.0#system-double-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat?view=net-10.0#system-double-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@)) + * `bool TryParse(string?, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)) #### Encoding @@ -565,6 +606,31 @@ The class `Polyfill` includes the following extension methods: * `bool TryGetChars(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.trygetchars?view=net-10.0) +#### Enum + + * `string[] GetNames() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0) + * `TEnum[] GetValues() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0) + * `bool IsDefined(TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0)) + * `TEnum Parse(ReadOnlySpan, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean)) + * `TEnum Parse(ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char)))) + * `TEnum Parse(string, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) + * `TEnum Parse(string) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) + * `bool TryFormat(TEnum, Span, int, ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0) + * `bool TryParse(ReadOnlySpan, bool, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@)) + * `bool TryParse(ReadOnlySpan, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@)) + + +#### Enumerable + + * `IEnumerable InfiniteSequence(T, T) where T : IAdditionOperators` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.infinitesequence?view=net-10.0) + * `IEnumerable Sequence(T, T, T) where T : INumber` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequence?view=net-10.0) + + +#### Environment + + * `ProcessId` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.environment.processid?view=net-10.0#system-environment-processid) + + #### EventInfo * `NullabilityState GetNullability()` @@ -579,16 +645,54 @@ The class `Polyfill` includes the following extension methods: * `bool IsNullable()` -#### float +#### File + + * `void AppendAllBytes(string, byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte())) + * `void AppendAllBytes(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte)))) + * `Task AppendAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) + * `Task AppendAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) + * `Task AppendAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) + * `Task AppendAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) + * `void AppendAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) + * `void AppendAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char)))) + * `Task AppendAllTextAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, ReadOnlyMemory, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken)) + * `Task AppendAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + * `void Move(string, string, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0) + * `Task ReadAllBytesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0) + * `Task ReadAllLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) + * `Task ReadAllLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task ReadAllTextAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken)) + * `Task ReadAllTextAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `IAsyncEnumerable ReadLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) + * `IAsyncEnumerable ReadLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task WriteAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) + * `Task WriteAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) + * `Task WriteAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) + * `Task WriteAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) + * `void WriteAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) + * `void WriteAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char)))) + * `Task WriteAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + * `Task WriteAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) + + +#### FileUnixMode - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) #### Guid * `bool TryFormat(Span, int, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat?view=net-10.0#system-guid-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char)))) * `bool TryFormat(Span, int, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat?view=net-10.0#system-guid-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char)))) + * `Guid CreateVersion7()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7) + * `Guid CreateVersion7(DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset)) + * `Guid Parse(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.parse?view=net-10.0#system-guid-parse(system-readonlyspan((system-byte)))) + * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-byte))-system-guid@)) + * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@)) + * `bool TryParse(string?, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@)) + * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@)) #### HashSet @@ -671,10 +775,43 @@ The class `Polyfill` includes the following extension methods: * `ReadOnlyCollection AsReadOnly()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.asreadonly?view=net-10.0#system-collections-generic-collectionextensions-asreadonly-1(system-collections-generic-ilist((-0)))) -#### int +#### Int16 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) + * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@)) + * `bool TryParse(string?, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@)) + + +#### Int32 * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat?view=net-10.0#system-int32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat?view=net-10.0#system-int32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@)) + * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) + * `bool TryParse(string?, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@)) + + +#### Int64 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@)) + * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) + * `bool TryParse(string?, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@)) #### IReadOnlyDictionary @@ -702,10 +839,21 @@ The class `Polyfill` includes the following extension methods: * `void TrimExcess()` -#### long +#### Math - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat?view=net-10.0#system-int64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `byte Clamp(byte, byte, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `decimal Clamp(decimal, decimal, decimal)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `double Clamp(double, double, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `float Clamp(float, float, float)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `int Clamp(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `long Clamp(long, long, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `nint Clamp(nint, nint, nint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `nuint Clamp(nuint, nuint, nuint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `sbyte Clamp(sbyte, sbyte, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `short Clamp(short, short, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `uint Clamp(uint, uint, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `ulong Clamp(ulong, ulong, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) + * `ushort Clamp(ushort, ushort, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) #### MemberInfo @@ -722,6 +870,31 @@ The class `Polyfill` includes the following extension methods: * `T CreateDelegate() where T : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/System.Reflection.MethodInfo.CreateDelegate?view=net-10.0#system-reflection-methodinfo-createdelegate-1) +#### OperatingSystem + + * `bool IsAndroid()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0) + * `bool IsAndroidVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0) + * `bool IsBrowser()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0) + * `bool IsFreeBSD()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0) + * `bool IsFreeBSDVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0) + * `bool IsIOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0) + * `bool IsIOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0) + * `bool IsLinux()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0) + * `bool IsMacCatalyst()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0) + * `bool IsMacCatalystVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0) + * `bool IsMacOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0) + * `bool IsMacOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0) + * `bool IsOSPlatform(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0) + * `bool IsOSPlatformVersionAtLeast(string, int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0) + * `bool IsTvOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0) + * `bool IsTvOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0) + * `bool IsWasi()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0) + * `bool IsWatchOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0) + * `bool IsWatchOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0) + * `bool IsWindows()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0) + * `bool IsWindowsVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0) + + #### OrderedDictionary * `bool TryAdd(TKey, TValue, int) where TKey : notnull` [reference](https://github.com/dotnet/core/blob/main/release-notes/10.0/preview/preview1/libraries.md#additional-tryadd-and-trygetvalue-overloads-for-ordereddictionarytkey-tvalue?view=net-10.0) @@ -735,6 +908,21 @@ The class `Polyfill` includes the following extension methods: * `bool IsNullable()` +#### Path + + * `string Combine(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string)))) + * `bool EndsInDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char)))) + * `bool EndsInDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string)) + * `bool Exists(string?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0) + * `ReadOnlySpan GetDirectoryName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetFileName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char)))) + * `ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) + * `bool HasExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) + * `ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char)))) + * `string TrimEndingDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string)) + + #### Process * `void Kill(bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.kill?view=net-10.0#system-diagnostics-process-kill(system-boolean)) @@ -762,6 +950,21 @@ The class `Polyfill` includes the following extension methods: * `void NextBytes(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) * `void Shuffle(T[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=net-10.0#system-random-nextbytes(system-span((system-byte)))) + * `Shared` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-10.0) + + +#### RandomNumberGenerator + + * `void Fill(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0) + * `byte[] GetBytes(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32)) + * `string GetHexString(int, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean)) + * `void GetHexString(Span, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) + * `int GetInt32(int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32)) + * `int GetInt32(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32)) + * `T[] GetItems(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32)) + * `void GetItems(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0)))) + * `string GetString(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) + * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0) #### ReadOnlySpan @@ -800,18 +1003,55 @@ The class `Polyfill` includes the following extension methods: * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char)))) * `bool IsMatch(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-int32)) * `bool IsMatch(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char)))) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) + * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string)) + * `bool IsMatch(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) + * `bool IsMatch(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) + * `bool IsMatch(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string)) -#### sbyte +#### SByte * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat?view=net-10.0#system-sbyte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat?view=net-10.0#system-sbyte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) + * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@)) + * `bool TryParse(string?, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@)) -#### short +#### SHA256 - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat?view=net-10.0#system-int16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte())) + * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) + * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte)))) + * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte)))) + * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream)) + * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken)) + * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) + * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0) + + +#### SHA512 + + * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte())) + * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) + * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte)))) + * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte)))) + * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream)) + * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken)) + * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) + * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0) + + +#### Single + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat?view=net-10.0#system-single-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) #### SortedList @@ -860,7 +1100,7 @@ The class `Polyfill` includes the following extension methods: * `ValueTask WriteAsync(ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.writeasync?view=net-10.0#system-io-stream-writeasync(system-readonlymemory((system-byte))-system-threading-cancellationtoken)) -#### string +#### String * `bool Contains(char, StringComparison)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=net-10.0#system-string-contains(system-char-system-stringcomparison)) * `bool Contains(char)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=net-10.0#system-string-contains(system-char)) @@ -877,6 +1117,16 @@ The class `Polyfill` includes the following extension methods: * `string[] Split(string, StringSplitOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-10.0#system-string-split(system-string-system-stringsplitoptions)) * `bool StartsWith(char)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith?view=net-10.0#system-string-startswith(system-char)) * `bool TryCopyTo(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.trycopyto?view=net-10.0) + * `int GetHashCode(ReadOnlySpan, StringComparison)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char))-system-stringcomparison)) + * `int GetHashCode(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char)))) + * `string Join(char, object?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object())) + * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object)))) + * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string)))) + * `string Join(char, string?[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32)) + * `string Join(char, string?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string())) + * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object)))) + * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string)))) + * `string Join(char, IEnumerable)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0)))) #### StringBuilder @@ -972,22 +1222,43 @@ The class `Polyfill` includes the following extension methods: * `bool IsGenericMethodParameter()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.type.isgenericmethodparameter?view=net-10.0) -#### uint - - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt16 + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) + * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@)) + * `bool TryParse(string?, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@)) -#### ulong - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt32 + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat?view=net-10.0#system-uint32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) + * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@)) + * `bool TryParse(string?, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@)) -#### ushort - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) - * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat?view=net-10.0#system-uint16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) +#### UInt64 + + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryFormat(Span, int, ReadOnlySpan, IFormatProvider?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat?view=net-10.0#system-uint64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) + * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@)) + * `bool TryParse(string?, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@)) #### XDocument @@ -995,6 +1266,9 @@ The class `Polyfill` includes the following extension methods: * `Task SaveAsync(Stream, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-io-stream-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(TextWriter, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-io-textwriter-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(XmlWriter, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync?view=net-10.0#system-xml-linq-xdocument-saveasync(system-xml-xmlwriter-system-threading-cancellationtoken)) + * `Task LoadAsync(Stream, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(TextReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(XmlReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) #### XElement @@ -1002,6 +1276,9 @@ The class `Polyfill` includes the following extension methods: * `Task SaveAsync(Stream, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-io-stream-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(TextWriter, SaveOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-io-textwriter-system-xml-linq-saveoptions-system-threading-cancellationtoken)) * `Task SaveAsync(XmlWriter, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.saveasync?view=net-10.0#system-xml-linq-xelement-saveasync(system-xml-xmlwriter-system-threading-cancellationtoken)) + * `Task LoadAsync(Stream, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(TextReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) + * `Task LoadAsync(XmlReader, LoadOptions, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken)) #### ZipArchive @@ -1018,339 +1295,29 @@ The class `Polyfill` includes the following extension methods: * `Task ExtractToFileAsync(string, bool, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.extracttofileasync?view=net-10.0#system-io-compression-zipfileextensions-extracttofileasync(system-io-compression-ziparchiveentry-system-string-system-boolean-system-threading-cancellationtoken)) * `Task ExtractToFileAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.zipfileextensions.extracttofileasync?view=net-10.0#system-io-compression-zipfileextensions-extracttofileasync(system-io-compression-ziparchiveentry-system-string-system-threading-cancellationtoken)) * `Task OpenAsync(CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.openasync?view=net-10.0) - - -### Static helpers - -#### BytePolyfill - - * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@)) - * `bool TryParse(string?, IFormatProvider?, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@)) - - -#### ConvertPolyfill - - * `byte[] FromHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char)))) - * `byte[] FromHexString(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string)) - * `string ToHexString(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32)) - * `string ToHexString(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte())) - * `string ToHexString(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte)))) - * `string ToHexStringLower(byte[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32)) - * `string ToHexStringLower(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte())) - * `string ToHexStringLower(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte)))) - * `bool TryToHexString(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0) - * `bool TryToHexStringLower(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0) - - -#### DateTimeOffsetPolyfill - - * `bool TryParse(ReadOnlySpan, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - * `bool TryParse(string?, IFormatProvider?, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@)) - - -#### DateTimePolyfill - - * `bool TryParse(ReadOnlySpan, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - * `bool TryParse(string?, IFormatProvider?, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - * `bool TryParseExact(ReadOnlySpan, string, IFormatProvider?, DateTimeStyles, DateTime)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@)) - - -#### DelegatePolyfill - - * `InvocationListEnumerator EnumerateInvocationList(TDelegate?) where TDelegate : Delegate` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0) - - -#### DoublePolyfill - - * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@)) - * `bool TryParse(string?, IFormatProvider?, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@)) - - -#### EnumPolyfill - - * `string[] GetNames() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0) - * `TEnum[] GetValues() where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0) - * `bool IsDefined(TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0)) - * `TEnum Parse(ReadOnlySpan, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean)) - * `TEnum Parse(ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char)))) - * `TEnum Parse(string, bool) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) - * `TEnum Parse(string) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean)) - * `bool TryFormat(TEnum, Span, int, ReadOnlySpan) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0) - * `bool TryParse(ReadOnlySpan, bool, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@)) - * `bool TryParse(ReadOnlySpan, TEnum) where TEnum : struct, Enum` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@)) - - -#### FilePolyfill - - * `void AppendAllBytes(string, byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte())) - * `void AppendAllBytes(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte)))) - * `Task AppendAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) - * `Task AppendAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) - * `Task AppendAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) - * `Task AppendAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) - * `void AppendAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) - * `void AppendAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char)))) - * `Task AppendAllTextAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, ReadOnlyMemory, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken)) - * `Task AppendAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - * `UnixFileMode GetUnixFileMode(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.getunixfilemode?view=net-10.0#system-io-file-getunixfilemode(system-string)) - * `void Move(string, string, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0) - * `Task ReadAllBytesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0) - * `Task ReadAllLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) - * `Task ReadAllLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `Task ReadAllTextAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken)) - * `Task ReadAllTextAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `IAsyncEnumerable ReadLinesAsync(string, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken)) - * `IAsyncEnumerable ReadLinesAsync(string, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken)) - * `void SetUnixFileMode(string, UnixFileMode)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setunixfilemode?view=net-10.0#system-io-file-setunixfilemode(system-string-system-io-unixfilemode)) - * `Task WriteAllBytesAsync(string, byte[], CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken)) - * `Task WriteAllBytesAsync(string, ReadOnlyMemory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken)) - * `Task WriteAllLinesAsync(string, IEnumerable, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken)) - * `Task WriteAllLinesAsync(string, IEnumerable, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken)) - * `void WriteAllText(string, ReadOnlySpan, Encoding)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding)) - * `void WriteAllText(string, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char)))) - * `Task WriteAllTextAsync(string, string?, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - * `Task WriteAllTextAsync(string, string?, Encoding, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken)) - - -#### GuidPolyfill - - * `Guid CreateVersion7()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7) - * `Guid CreateVersion7(DateTimeOffset)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset)) - * `bool TryParse(ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@)) - * `bool TryParse(string?, IFormatProvider?, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@)) - * `bool TryParseExact(ReadOnlySpan, ReadOnlySpan, Guid)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@)) - - -#### IntPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@)) - * `bool TryParse(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@)) - * `bool TryParse(string?, IFormatProvider?, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@)) - - -#### LongPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@)) - * `bool TryParse(ReadOnlySpan, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@)) - * `bool TryParse(string?, IFormatProvider?, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@)) - - -#### MathPolyfill - - * `byte Clamp(byte, byte, byte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `decimal Clamp(decimal, decimal, decimal)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `double Clamp(double, double, double)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `float Clamp(float, float, float)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `int Clamp(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `long Clamp(long, long, long)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `nint Clamp(nint, nint, nint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `nuint Clamp(nuint, nuint, nuint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `sbyte Clamp(sbyte, sbyte, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `short Clamp(short, short, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `uint Clamp(uint, uint, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `ulong Clamp(ulong, ulong, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - * `ushort Clamp(ushort, ushort, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0) - - -#### OperatingSystemPolyfill - - * `bool IsAndroid()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0) - * `bool IsAndroidVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0) - * `bool IsBrowser()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0) - * `bool IsFreeBSD()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0) - * `bool IsFreeBSDVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0) - * `bool IsIOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0) - * `bool IsIOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0) - * `bool IsLinux()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0) - * `bool IsMacCatalyst()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0) - * `bool IsMacCatalystVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0) - * `bool IsMacOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0) - * `bool IsMacOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0) - * `bool IsOSPlatform(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0) - * `bool IsOSPlatformVersionAtLeast(string, int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0) - * `bool IsTvOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0) - * `bool IsTvOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0) - * `bool IsWasi()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0) - * `bool IsWatchOS()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0) - * `bool IsWatchOSVersionAtLeast(int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0) - * `bool IsWindows()` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0) - * `bool IsWindowsVersionAtLeast(int, int, int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0) - - -#### PathPolyfill - - * `string Combine(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string)))) - * `bool EndsInDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char)))) - * `bool EndsInDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string)) - * `bool Exists(string?)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0) - * `ReadOnlySpan GetDirectoryName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetFileName(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char)))) - * `ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) - * `bool HasExtension(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char)))) - * `ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char)))) - * `string TrimEndingDirectorySeparator(string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string)) - - -#### RandomNumberGeneratorPolyfill - - * `void Fill(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0) - * `byte[] GetBytes(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32)) - * `string GetHexString(int, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean)) - * `void GetHexString(Span, bool)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) - * `int GetInt32(int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32)) - * `int GetInt32(int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32)) - * `T[] GetItems(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32)) - * `void GetItems(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0)))) - * `string GetString(ReadOnlySpan, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0) - * `void Shuffle(Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0) - - -#### RandomPolyfill - - - -#### RegexPolyfill - - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) - * `ValueMatchEnumerator EnumerateMatches(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string)) - * `bool IsMatch(ReadOnlySpan, string, RegexOptions, TimeSpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan)) - * `bool IsMatch(ReadOnlySpan, string, RegexOptions)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions)) - * `bool IsMatch(ReadOnlySpan, string)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string)) - - -#### SBytePolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@)) - * `bool TryParse(ReadOnlySpan, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@)) - * `bool TryParse(string?, IFormatProvider?, sbyte)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@)) - - -#### SHA256Polyfill - - * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte())) - * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) - * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte)))) - * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte)))) - * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream)) - * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken)) - * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) - * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0) - - -#### SHA512Polyfill - - * `byte[] HashData(byte[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte())) - * `int HashData(ReadOnlySpan, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte)))) - * `byte[] HashData(ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte)))) - * `int HashData(Stream, Span)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte)))) - * `byte[] HashData(Stream)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream)) - * `ValueTask HashDataAsync(Stream, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken)) - * `ValueTask HashDataAsync(Stream, Memory, CancellationToken)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken)) - * `bool TryHashData(ReadOnlySpan, Span, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0) - - -#### ShortPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@)) - * `bool TryParse(ReadOnlySpan, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@)) - * `bool TryParse(string?, IFormatProvider?, short)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@)) - - -#### StringPolyfill - - * `string Join(char, object?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object())) - * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object)))) - * `string Join(char, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string)))) - * `string Join(char, string?[], int, int)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32)) - * `string Join(char, string?[])` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string())) - * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object)))) - * `string Join(string?, ReadOnlySpan)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string)))) - * `string Join(char, IEnumerable)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0)))) - - -#### UIntPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@)) - * `bool TryParse(ReadOnlySpan, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@)) - * `bool TryParse(string?, IFormatProvider?, uint)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@)) - - -#### ULongPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@)) - * `bool TryParse(ReadOnlySpan, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@)) - * `bool TryParse(string?, IFormatProvider?, ulong)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@)) - - -#### UShortPolyfill - - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, NumberStyles, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@)) - * `bool TryParse(ReadOnlySpan, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@)) - * `bool TryParse(string?, IFormatProvider?, ushort)` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@)) + * `ExternalAttributes` [reference](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.externalattributes?view=net-10.0) #### Guard * `void DirectoryExists(string)` + * `T Equal(T, T)` * `void FileExists(string)` - * `void NotEmpty(string?)` - * `void NotEmpty(Memory?)` - * `void NotEmpty(Memory)` - * `void NotEmpty(ReadOnlyMemory?)` - * `void NotEmpty(ReadOnlyMemory)` - * `void NotEmpty(ReadOnlySpan)` - * `void NotEmpty(Span)` - * `void NotEmpty(T?) where T : IEnumerable` + * `string? NotEmpty(string?)` + * `Memory? NotEmpty(Memory?)` + * `Memory NotEmpty(Memory)` + * `ReadOnlyMemory? NotEmpty(ReadOnlyMemory?)` + * `ReadOnlyMemory NotEmpty(ReadOnlyMemory)` + * `ReadOnlySpan NotEmpty(ReadOnlySpan)` + * `Span NotEmpty(Span)` + * `T? NotEmpty(T?) where T : IEnumerable` + * `T NotEqual(T, T)` + * `T NotGreaterThan(T, T) where T : IComparable` + * `T NotGreaterThanOrEqual(T, T) where T : IComparable` + * `T NotLessThan(T, T) where T : IComparable` + * `T NotLessThanOrEqual(T, T) where T : IComparable` + * `T NotNegative(T) where T : struct, IComparable` + * `T NotNegativeOrZero(T) where T : struct, IComparable` * `string NotNull(string?)` * `T NotNull(T?) where T : class` * `Memory NotNullOrEmpty(Memory?)` @@ -1360,11 +1327,12 @@ The class `Polyfill` includes the following extension methods: * `Memory NotNullOrWhiteSpace(Memory?)` * `ReadOnlyMemory NotNullOrWhiteSpace(ReadOnlyMemory?)` * `string NotNullOrWhiteSpace(string?)` - * `void NotWhiteSpace(Memory?)` - * `void NotWhiteSpace(ReadOnlyMemory?)` - * `void NotWhiteSpace(ReadOnlySpan)` - * `void NotWhiteSpace(Span)` - * `void NotWhiteSpace(string?)` + * `Memory? NotWhiteSpace(Memory?)` + * `ReadOnlyMemory? NotWhiteSpace(ReadOnlyMemory?)` + * `ReadOnlySpan NotWhiteSpace(ReadOnlySpan)` + * `Span NotWhiteSpace(Span)` + * `string? NotWhiteSpace(string?)` + * `T NotZero(T) where T : struct, IComparable` #### Lock @@ -1511,30 +1479,30 @@ public void Test() * Throws an exception if state is `NullabilityState.Unknown`. -## Guard +## Ensure -Enable by adding an MSBuild property `PolyGuard` +Enable by adding an MSBuild property `PolyEnsure` ``` ... - true + true ``` -`Guard` is designed to be a an alternative to the `Argument*Exception.ThrowIf*` APIs added in net7. +`Ensure` is designed to be a an alternative to the `Argument*Exception.ThrowIf*` APIs added in net7. * `ArgumentException.ThrowIf*` [reference](https://learn.microsoft.com/en-us/dotnet/api/?view=net-10.0&term=ArgumentException.ThrowIf) * `ArgumentNullException.ThrowIf*` [reference](https://learn.microsoft.com/en-us/dotnet/api/?view=net-10.0&term=ArgumentNullException.ThrowIf) * `ArgumentOutOfRangeException.ThrowIf*` [reference](https://learn.microsoft.com/en-us/dotnet/api/?view=net-10.0&term=ArgumentOutOfRangeException.ThrowIf) -With the equivalent Guard APIs: +With the equivalent Ensure APIs: - * `Guard.NotNullOrEmpty` - * `Guard.NotNullOrWhiteSpace` - * `Guard.NotNull` + * `Ensure.NotNullOrEmpty` + * `Ensure.NotNullOrWhiteSpace` + * `Ensure.NotNull` -`Polyfills.Guard` provides the following APIs: +`Polyfills.Ensure` provides the following APIs: #### Guard diff --git a/src/.gitattributes b/src/.gitattributes index 4f905c91..627071bd 100644 --- a/src/.gitattributes +++ b/src/.gitattributes @@ -7,4 +7,5 @@ *.verified.json text eol=lf working-tree-encoding=UTF-8 .editorconfig text eol=lf working-tree-encoding=UTF-8 -Shared.sln.DotSettings text eol=lf working-tree-encoding=UTF-8 \ No newline at end of file +*.sln.DotSettings text eol=lf working-tree-encoding=UTF-8 +*.slnx.DotSettings text eol=lf working-tree-encoding=UTF-8 \ No newline at end of file diff --git a/src/ApiBuilderTests/BuildApiTest.cs b/src/ApiBuilderTests/BuildApiTest.cs index cc5bc0df..2e02c8c5 100644 --- a/src/ApiBuilderTests/BuildApiTest.cs +++ b/src/ApiBuilderTests/BuildApiTest.cs @@ -13,40 +13,19 @@ static BuildApiTest() [Test] public void RunWithRoslyn() { - var types = ReadFiles(); - var md = Path.Combine(solutionDirectory, "..", "api_list.include.md"); File.Delete(md); using var writer = File.CreateText(md); var count = 0; + count = WriteExtensions(writer, count); - var extensions = types["Polyfill"]; - writer.WriteLine("### Extension methods"); - writer.WriteLine(); - foreach (var grouping in PublicMethods(extensions) - .GroupBy(_ => _.ParameterList.Parameters[0].Type!.ToString()) - .OrderBy(_ => _.Key)) - { - WriteTypeMethods(grouping.Key, writer, ref count, grouping); - } - - writer.WriteLine("### Static helpers"); - writer.WriteLine(); - foreach (var (key, value) in types - .OrderBy(_ => _.Key) - .Where(_ => _.Key.EndsWith("Polyfill") && - _.Key != "Polyfill")) - { - WriteTypeMethods(key, writer, ref count, value); - } - - WriteHelper(types, "Guard", writer, ref count); - WriteHelper(types, "Lock", writer, ref count); - WriteHelper(types, nameof(KeyValuePair), writer, ref count); + WriteHelper("Ensure*", writer, ref count); + WriteHelper("Lock", writer, ref count); + WriteHelper(nameof(KeyValuePair), writer, ref count); WriteType(nameof(TaskCompletionSource), writer, ref count); WriteType(nameof(UnreachableException), writer, ref count); - count += types.Count(_ => _.Key.EndsWith("Attribute")); + count += Directory.EnumerateFiles(polyfillDir, "*Attribute.cs", SearchOption.AllDirectories).Count(); // Index and Range count++; //Nullability* @@ -57,37 +36,152 @@ public void RunWithRoslyn() File.WriteAllText(countMd, $"**API count: {count}**"); } - static IEnumerable PublicMethods(HashSet type) => - type.Where(_ => _.IsPublic() && - !_.IsConstructor()) - .OrderBy(_ => _.Identifier.ToString()); - - static Dictionary> ReadFiles() + static int WriteExtensions(StreamWriter writer, int count) { - var types = new Dictionary>(); - var methodComparer = EqualityComparer - .Create( - (x, y) => Key(x!) == Key(y!), - _ => Key(_).GetHashCode()); - foreach (var file in Directory.EnumerateFiles(polyfillDir, "*.cs", SearchOption.AllDirectories)) + var files = Directory.EnumerateFiles(polyfillDir, "*Polyfill*.cs", SearchOption.AllDirectories).ToList(); + + var instanceFiles = files + .Where(_ => Path.GetFileNameWithoutExtension(_).StartsWith("Polyfill_")) + .ToList(); + + var staticFiles = files + .Where(_ => + { + var name = Path.GetFileNameWithoutExtension(_); + return name.EndsWith("Polyfill") && + name != "Polyfill"; + }) + .ToList(); + + var instanceMethods = ReadMethodsForFiles(instanceFiles); + + var instanceTypeNames = instanceMethods + .Select(FirstParameterType); + + var staticTypeNames = staticFiles + .Select(Path.GetFileNameWithoutExtension) + .Select(_ => _![..^8].ToString()); + + var typeNames = instanceTypeNames.Concat(staticTypeNames) + .Distinct() + .ToList(); + + writer.WriteLine("### Extension methods"); + writer.WriteLine(); + + foreach (var name in typeNames.Order()) { - foreach (var type in Identifiers.ReadTypesForFile(file)) + var instanceMethodsForType = instanceMethods + .Where(_ => FirstParameterType(_) == name) + .ToList(); + writer.WriteLine($"#### {name}"); + writer.WriteLine(); + if (instanceMethodsForType.Count != 0) + { + foreach (var method in instanceMethodsForType.OrderBy(Key)) + { + count++; + WriteSignature(method, writer); + } + } + + var staticExtension = staticFiles + .SingleOrDefault(_ => Path.GetFileNameWithoutExtension(_)[..^8].ToString() == name); + if (staticExtension != null) { - var identifier = type.Identifier.Text; - if (!types.TryGetValue(identifier, out var methods)) + foreach (var method in ReadMethodsForFiles([staticExtension]).OrderBy(Key)) { - methods = new(methodComparer); - types.Add(identifier, methods); + count++; + WriteSignature(method, writer); } - foreach (var method in type.PublicMethods()) + foreach (var property in ReadPropertiesForFiles([staticExtension])) { - methods.Add(method); + count++; + WriteSignature(property, writer); } } + + writer.WriteLine(); + writer.WriteLine(); + } + + return count; + } + + static Dictionary langwordToType = new() + { + ["bool"] = "Boolean", + ["byte"] = "Byte", + ["sbyte"] = "SByte", + ["char"] = "Char", + ["decimal"] = "Decimal", + ["double"] = "Double", + ["float"] = "Single", + ["int"] = "Int32", + ["uint"] = "UInt32", + ["long"] = "Int64", + ["ulong"] = "UInt64", + ["object"] = "Object", + ["short"] = "Int16", + ["ushort"] = "UInt16", + ["string"] = "String" + }; + + static string FirstParameterType(Method method) + { + var type = method.ParameterList.Parameters[0].Type!.ToString(); + return langwordToType.GetValueOrDefault(type, type); + } + + static List ReadMethodsForFiles(string pattern) + { + var files = Directory.EnumerateFiles(polyfillDir, $"{pattern}.cs", SearchOption.AllDirectories); + return ReadMethodsForFiles(files); + } + + private static List ReadMethodsForFiles(IEnumerable files) + { + var types = files + .SelectMany(Identifiers.ReadTypesForFile) + .ToList(); + + var distinctTypes = types.Select(_ => _.Identifier.Text).Distinct().ToList(); + if (distinctTypes.Count > 1) + { + throw new(string.Join(", ", distinctTypes)); + } + + return types + .SelectMany(_ => _.PublicMethods()) + .DistinctBy(Key) + .OrderBy(Key) + .ToList(); + } + + static List ReadPropertiesForFiles(string pattern) + { + var files = Directory.EnumerateFiles(polyfillDir, $"{pattern}.cs", SearchOption.AllDirectories); + return ReadPropertiesForFiles(files); + } + + static List ReadPropertiesForFiles(IEnumerable files) + { + var types = files + .SelectMany(Identifiers.ReadTypesForFile) + .ToList(); + + var distinctTypes = types.DistinctBy(_ => _.Identifier.Text).ToList(); + if (distinctTypes.Count > 1) + { + throw new(string.Join(", ", distinctTypes)); } - return types; + return types + .SelectMany(_ => _.PublicProperties()) + .DistinctBy(_ => _.Identifier.Text) + .OrderBy(_ => _.Identifier.Text) + .ToList(); } static void WriteType(string name, StreamWriter writer, ref int count) @@ -100,12 +194,8 @@ static void WriteType(string name, StreamWriter writer, ref int count) count++; } - static void WriteHelper(Dictionary> types, string name, StreamWriter writer, ref int count) - { - var methods = types[name]; - - WriteTypeMethods(name, writer, ref count, methods.OrderBy(Key)); - } + static void WriteHelper(string name, StreamWriter writer, ref int count) => + WriteTypeMethods(name.Trim('*'), writer, ref count, ReadMethodsForFiles(name)); static void WriteTypeMethods(string name, StreamWriter writer, ref int count, IEnumerable methods) { @@ -144,6 +234,20 @@ static void WriteSignature(Method method, StreamWriter writer) } } + static void WriteSignature(Property method, StreamWriter writer) + { + var signature = new StringBuilder(method.Identifier.Text); + + if (method.TryGetReference(out var reference)) + { + writer.WriteLine($" * `{signature}` [reference]({reference})"); + } + else + { + writer.WriteLine($" * `{signature}`"); + } + } + static string Key(Method method) => $"{method.Identifier.Text}{BuildTypeArgs(method)}({BuildParameters(method, false)})"; @@ -160,17 +264,16 @@ static string BuildTypeArgs(Method method) static string BuildParameters(Method method, bool skipThisModified) { - List parameters; + var parameters = method + .ParameterList + .Parameters + .ToList(); + if (skipThisModified) { - parameters = method.ParameterList - .Parameters - .Where(_ => !_.IsThis()).ToList(); - } - else - { - parameters = method.ParameterList - .Parameters.ToList(); + parameters = parameters + .Where(_ => !_.IsThis()) + .ToList(); } if (parameters.Count > 0) diff --git a/src/ApiBuilderTests/Identifiers.cs b/src/ApiBuilderTests/Identifiers.cs index 19d01b06..1b273984 100644 --- a/src/ApiBuilderTests/Identifiers.cs +++ b/src/ApiBuilderTests/Identifiers.cs @@ -27,7 +27,7 @@ public static IEnumerable ReadTypesForFile(string file) [ "FeatureMemory", "FeatureRuntimeInformation", - "PolyGuard", + "PolyEnsure", "PolyPublic", "FeatureHttp", "PolyNullability", diff --git a/src/ApiBuilderTests/LinkReader.cs b/src/ApiBuilderTests/LinkReader.cs index e3af6a23..b331026f 100644 --- a/src/ApiBuilderTests/LinkReader.cs +++ b/src/ApiBuilderTests/LinkReader.cs @@ -1,8 +1,8 @@ public static class LinkReader { - public static bool TryGetReference(this Method method, [NotNullWhen(true)] out string? reference) + public static bool TryGetReference(this Member member, [NotNullWhen(true)] out string? reference) { - var syntaxTrivia = method.GetLeadingTrivia(); + var syntaxTrivia = member.GetLeadingTrivia(); foreach (var trivia in syntaxTrivia) { if (!trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)) diff --git a/src/ApiBuilderTests/RoslynExtensions.cs b/src/ApiBuilderTests/RoslynExtensions.cs index ee0b1e02..f517bece 100644 --- a/src/ApiBuilderTests/RoslynExtensions.cs +++ b/src/ApiBuilderTests/RoslynExtensions.cs @@ -20,6 +20,13 @@ public static IEnumerable PublicMethods(this Type type) => _.IsPublic() && !_.IsConstructor()); + public static IEnumerable PublicProperties(this Type type) => + type + .DescendantNodes() + .OfType() + .Where(_ => _.Parent == type && + _.IsPublic()); + public static bool IsConstructor(this Method method) { if (method.Parent is Type type) diff --git a/src/Consume/Consume.cs b/src/Consume/Consume.cs index 00e5a7a0..68b917a5 100644 --- a/src/Consume/Consume.cs +++ b/src/Consume/Consume.cs @@ -38,6 +38,7 @@ using System.Xml.Linq; using MemoryStream = System.IO.MemoryStream; // ReSharper disable MethodHasAsyncOverload +// ReSharper disable RedundantCast #pragma warning disable CS4014 #pragma warning disable CA1416 @@ -156,48 +157,66 @@ void Method(object x) { } + void GuidUsage() + { + var guid = Guid.CreateVersion7(); + guid = Guid.CreateVersion7(timestamp: DateTimeOffset.UtcNow); + var result = Guid.TryParse(s: "", provider: null, result: out guid); +#if FeatureMemory + ReadOnlySpan byteSpan = default; + result = Guid.TryParse(utf8Text: byteSpan, result: out guid); + guid = Guid.Parse(utf8Text: byteSpan); + + Span charSpan = default; + result = Guid.TryParse(input: charSpan, result: out guid); + result = Guid.TryParse(s: charSpan, provider: null, result: out guid); + result = Guid.TryParseExact(input: charSpan, format: charSpan, result: out guid); + +#endif + } + void SHA256Usage() { - SHA256Polyfill.HashData((byte[])null!); - SHA256Polyfill.HashData((Stream)null!); + SHA256.HashData(source: (byte[]) null!); + SHA256.HashData(source: (Stream) null!); #if FeatureValueTask - SHA256Polyfill.HashDataAsync(null!, CancellationToken.None); + SHA256.HashDataAsync(source: null!, cancellationToken: CancellationToken.None); #endif #if FeatureMemory Span span = default; ReadOnlySpan readOnlySpan = default; Memory memory = default; - SHA256Polyfill.HashData((Stream)null!, span); - SHA256Polyfill.HashData(readOnlySpan); - SHA256Polyfill.HashData(readOnlySpan, span); - SHA256Polyfill.TryHashData(readOnlySpan, span, out _); + SHA256.HashData(source: (Stream) null!, destination: span); + SHA256.HashData(source: readOnlySpan); + SHA256.HashData(source: readOnlySpan, destination: span); + SHA256.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _); #if FeatureValueTask - SHA256Polyfill.HashDataAsync(null!, memory); - SHA256Polyfill.HashDataAsync(null!, memory, CancellationToken.None); + SHA256.HashDataAsync(source: null!, destination: memory); + SHA256.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None); #endif #endif } void SHA512Usage() { - SHA512Polyfill.HashData((byte[])null!); - SHA512Polyfill.HashData((Stream)null!); + SHA512.HashData(source: (byte[]) null!); + SHA512.HashData(source: (Stream) null!); #if FeatureValueTask - SHA512Polyfill.HashDataAsync(null!, CancellationToken.None); + SHA512.HashDataAsync(source: null!, cancellationToken: CancellationToken.None); #endif #if FeatureMemory Span span = default; ReadOnlySpan readOnlySpan = default; Memory memory = default; - SHA512Polyfill.HashData((Stream)null!, span); - SHA512Polyfill.HashData(readOnlySpan); - SHA512Polyfill.HashData(readOnlySpan, span); - SHA512Polyfill.TryHashData(readOnlySpan, span, out _); + SHA512.HashData((Stream) null!, destination: span); + SHA512.HashData(source: readOnlySpan); + SHA512.HashData(source: readOnlySpan, destination: span); + SHA512.TryHashData(source: readOnlySpan, destination: span, bytesWritten: out _); #if FeatureValueTask - SHA512Polyfill.HashDataAsync(null!, memory); - SHA512Polyfill.HashDataAsync(null!, memory, CancellationToken.None); + SHA512.HashDataAsync(source: null!, destination: memory); + SHA512.HashDataAsync(source: null!, destination: memory, cancellationToken: CancellationToken.None); #endif #endif } @@ -213,7 +232,7 @@ void CollectionBuilderAttribute() class MyCollection(ReadOnlySpan initValues) { int[] values = initValues.ToArray(); - public IEnumerator GetEnumerator() => ((IEnumerable)values).GetEnumerator(); + public IEnumerator GetEnumerator() => ((IEnumerable) values).GetEnumerator(); public static MyCollection Create(ReadOnlySpan values) => new(values); } @@ -238,14 +257,14 @@ void Ranges() void Byte_Methods() { - BytePolyfill.TryParse("1", null, out _); + byte.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - BytePolyfill.TryParse("1"u8, null, out _); - BytePolyfill.TryParse(['1'], out _); - BytePolyfill.TryParse(['1'], null, out _); - BytePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - BytePolyfill.TryParse("1"u8, out _); - BytePolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + byte.TryParse(utf8Text: "1"u8, provider: null, result: out _); + byte.TryParse(s: ['1'], result: out _); + byte.TryParse(s: ['1'], provider: null, result: out _); + byte.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + byte.TryParse(utf8Text: "1"u8, result: out _); + byte.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } @@ -253,8 +272,12 @@ void CancellationToken_Methods() { var source = new CancellationTokenSource(); var token = source.Token; - token.UnsafeRegister(_ => { }, null); - token.UnsafeRegister((_, _) => { }, null); + token.UnsafeRegister(_ => + { + }, null); + token.UnsafeRegister((_, _) => + { + }, null); } async Task CancellationTokenSource_Methods() @@ -319,7 +342,7 @@ void ConcurrentQueue_Methods() void Dictionary_Methods() { - var dictionary = new Dictionary { { "key", "value" } }; + var dictionary = new Dictionary {{"key", "value"}}; dictionary.GetValueOrDefault("key"); dictionary.GetValueOrDefault("key", "default"); dictionary.TryAdd("key", "value"); @@ -344,14 +367,14 @@ void Lock_Methods() void Double_Methods() { - DoublePolyfill.TryParse("1", null, out _); + double.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - DoublePolyfill.TryParse("1"u8, null, out _); - DoublePolyfill.TryParse(['1'], out _); - DoublePolyfill.TryParse(['1'], null, out _); - DoublePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - DoublePolyfill.TryParse("1"u8, out _); - DoublePolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + double.TryParse(utf8Text: "1"u8, provider: null, result: out _); + double.TryParse(s: ['1'], result: out _); + double.TryParse(s: ['1'], provider: null, result: out _); + double.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + double.TryParse(utf8Text: "1"u8, result: out _); + double.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } @@ -368,15 +391,15 @@ void File_Methods() var sourceContent = "Test content"; File.WriteAllText(TestFilePath, sourceContent); - var fileMode = FilePolyfill.GetUnixFileMode(TestFilePath); + var fileMode = File.GetUnixFileMode(TestFilePath); // Use the | bitwise OR operator to combine multiple file modes - FilePolyfill.SetUnixFileMode(TestFilePath, UnixFileMode.OtherRead | UnixFileMode.OtherWrite); + File.SetUnixFileMode(TestFilePath, UnixFileMode.OtherRead | UnixFileMode.OtherWrite); } void HashSet_Methods() { - var set = new HashSet { "value" }; + var set = new HashSet {"value"}; var found = set.TryGetValue("value", out var result); set.EnsureCapacity(1); set.TrimExcess(1); @@ -384,7 +407,7 @@ void HashSet_Methods() } #if FeatureHttp - void HttpClient_Methods( HttpClient target) + void HttpClient_Methods(HttpClient target) { target.GetStreamAsync("", CancellationToken.None); target.GetStreamAsync(new Uri(""), CancellationToken.None); @@ -442,14 +465,14 @@ void IList_Methods() void Int_Methods() { - IntPolyfill.TryParse("1", null, out _); + int.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - IntPolyfill.TryParse("1"u8, null, out _); - IntPolyfill.TryParse(['1'], out _); - IntPolyfill.TryParse(['1'], null, out _); - IntPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - IntPolyfill.TryParse("1"u8, out _); - IntPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + int.TryParse(utf8Text: "1"u8, provider: null, result: out _); + int.TryParse(s: ['1'], result: out _); + int.TryParse(s: ['1'], provider: null, result: out _); + int.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + int.TryParse(utf8Text: "1"u8, result: out _); + int.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } @@ -476,14 +499,14 @@ void Queue_Methods() void Long_Methods() { - LongPolyfill.TryParse("1", null, out _); + long.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - LongPolyfill.TryParse("1"u8, null, out _); - LongPolyfill.TryParse(['1'], out _); - LongPolyfill.TryParse(['1'], null, out _); - LongPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - LongPolyfill.TryParse("1"u8, out _); - LongPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + long.TryParse(utf8Text: "1"u8, provider: null, result: out _); + long.TryParse(s: ['1'], result: out _); + long.TryParse(s: ['1'], provider: null, result: out _); + long.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + long.TryParse(utf8Text: "1"u8, result: out _); + long.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } @@ -492,39 +515,39 @@ void MemberInfo_Methods(MemberInfo info) var result = info.HasSameMetadataDefinitionAs(info); } - #if FeatureRuntimeInformation +#if FeatureRuntimeInformation void OperatingSystem_Methods() { - var isOSPlatform = OperatingSystemPolyfill.IsOSPlatform("windows"); - var isOSPlatformWindows10 = OperatingSystemPolyfill.IsOSPlatformVersionAtLeast("windows", 10, 0, 10240); + var isOSPlatform = OperatingSystem.IsOSPlatform("windows"); + var isOSPlatformWindows10 = OperatingSystem.IsOSPlatformVersionAtLeast("windows", 10, 0, 10240); - var isWindows = OperatingSystemPolyfill.IsWindows(); - var isWindows11 = OperatingSystemPolyfill.IsWindowsVersionAtLeast(10,0,22000); + var isWindows = OperatingSystem.IsWindows(); + var isWindows11 = OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000); - var isMacOS = OperatingSystemPolyfill.IsMacOS(); - var isMacOsSonoma = OperatingSystemPolyfill.IsMacOSVersionAtLeast(14); - var isMacCatalyst = OperatingSystemPolyfill.IsMacCatalyst(); - var isMacCatalyst17 = OperatingSystemPolyfill.IsMacCatalystVersionAtLeast(17); + var isMacOS = OperatingSystem.IsMacOS(); + var isMacOsSonoma = OperatingSystem.IsMacOSVersionAtLeast(14); + var isMacCatalyst = OperatingSystem.IsMacCatalyst(); + var isMacCatalyst17 = OperatingSystem.IsMacCatalystVersionAtLeast(17); - var isLinux = OperatingSystemPolyfill.IsLinux(); + var isLinux = OperatingSystem.IsLinux(); - var isFreeBSD = OperatingSystemPolyfill.IsFreeBSD(); - var isFreeBSD14 = OperatingSystemPolyfill.IsFreeBSDVersionAtLeast(14, 0); + var isFreeBSD = OperatingSystem.IsFreeBSD(); + var isFreeBSD14 = OperatingSystem.IsFreeBSDVersionAtLeast(14, 0); - var isIOS = OperatingSystemPolyfill.IsIOS(); - var isIOS18 = OperatingSystemPolyfill.IsIOSVersionAtLeast(18); + var isIOS = OperatingSystem.IsIOS(); + var isIOS18 = OperatingSystem.IsIOSVersionAtLeast(18); - var isAndroid = OperatingSystemPolyfill.IsAndroid(); - var isAndroid13 = OperatingSystemPolyfill.IsAndroidVersionAtLeast(13); + var isAndroid = OperatingSystem.IsAndroid(); + var isAndroid13 = OperatingSystem.IsAndroidVersionAtLeast(13); - var isTvOS = OperatingSystemPolyfill.IsTvOS(); - var isTvOS17 = OperatingSystemPolyfill.IsTvOSVersionAtLeast(17); + var isTvOS = OperatingSystem.IsTvOS(); + var isTvOS17 = OperatingSystem.IsTvOSVersionAtLeast(17); - var isWatchOS = OperatingSystemPolyfill.IsWatchOS(); - var isWatchOS11 = OperatingSystemPolyfill.IsWatchOSVersionAtLeast(11); + var isWatchOS = OperatingSystem.IsWatchOS(); + var isWatchOS11 = OperatingSystem.IsWatchOSVersionAtLeast(11); - var isWasi = OperatingSystemPolyfill.IsWasi(); - var isBrowser = OperatingSystemPolyfill.IsBrowser(); + var isWasi = OperatingSystem.IsWasi(); + var isBrowser = OperatingSystem.IsBrowser(); } #endif @@ -609,27 +632,27 @@ void Set_Methods() void SByte_Methods() { - SBytePolyfill.TryParse("1", null, out _); + sbyte.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - SBytePolyfill.TryParse("1"u8, null, out _); - SBytePolyfill.TryParse(['1'], out _); - SBytePolyfill.TryParse(['1'], null, out _); - SBytePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - SBytePolyfill.TryParse("1"u8, out _); - SBytePolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + sbyte.TryParse("1"u8, provider: null, result: out _); + sbyte.TryParse(s: ['1'], result: out _); + sbyte.TryParse(s: ['1'], provider: null, result: out _); + sbyte.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + sbyte.TryParse(utf8Text: "1"u8, result: out _); + sbyte.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } void Short_Methods() { - ShortPolyfill.TryParse("1", null, out _); + short.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - ShortPolyfill.TryParse("1"u8, null, out _); - ShortPolyfill.TryParse(['1'], out _); - ShortPolyfill.TryParse(['1'], null, out _); - ShortPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - ShortPolyfill.TryParse("1"u8, out _); - ShortPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + short.TryParse(utf8Text: "1"u8, provider: null, result: out _); + short.TryParse(s: ['1'], result: out _); + short.TryParse(s: ['1'], provider: null, result: out _); + short.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + short.TryParse(utf8Text: "1"u8, result: out _); + short.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } @@ -663,7 +686,7 @@ void Stack_Methods() async Task Stream_Methods() { - var input = new byte[] { 1, 2 }; + var input = new byte[] {1, 2}; using var stream = new MemoryStream(input); var result = new byte[2]; #if FeatureMemory @@ -671,9 +694,9 @@ async Task Stream_Methods() var read = await stream.ReadAsync(memory); #endif await stream.CopyToAsync(stream); - #if FeatureValueTask +#if FeatureValueTask await stream.DisposeAsync(); - #endif +#endif } async Task StreamReader_Methods() @@ -701,14 +724,14 @@ void String_Methods() splitString = "a b".Split(" ", 2, StringSplitOptions.RemoveEmptyEntries); } - #if !NoStringInterpolation && FeatureMemory +#if !NoStringInterpolation && FeatureMemory void DefaultInterpolatedStringHandler_Methods() { var handler = new DefaultInterpolatedStringHandler(); handler.AppendLiteral("value"); handler.Clear(); } - #endif +#endif void StringBuilder_Methods() { @@ -778,57 +801,61 @@ void Type_Methods(MemberInfo info) void UInt_Methods() { - UIntPolyfill.TryParse("1", null, out _); + uint.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - UIntPolyfill.TryParse("1"u8, null, out _); - UIntPolyfill.TryParse(['1'], out _); - UIntPolyfill.TryParse(['1'], null, out _); - UIntPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - UIntPolyfill.TryParse("1"u8, out _); - UIntPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + uint.TryParse(utf8Text: "1"u8, provider: null, result: out _); + uint.TryParse(s: ['1'], result: out _); + uint.TryParse(s: ['1'], provider: null, result: out _); + uint.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + uint.TryParse(utf8Text: "1"u8, result: out _); + uint.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } void ULong_Methods() { - ULongPolyfill.TryParse("1", null, out _); + ulong.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - ULongPolyfill.TryParse("1"u8, null, out _); - ULongPolyfill.TryParse(['1'], out _); - ULongPolyfill.TryParse(['1'], null, out _); - ULongPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - ULongPolyfill.TryParse("1"u8, out _); - ULongPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + ulong.TryParse(utf8Text: "1"u8, provider: null, result: out _); + ulong.TryParse(s: ['1'], result: out _); + ulong.TryParse(s: ['1'], provider: null, result: out _); + ulong.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, provider: null, result: out _); + ulong.TryParse(utf8Text: "1"u8, result: out _); + ulong.TryParse(s: ['1'], style: NumberStyles.Integer, provider: null, result: out _); #endif } void UShort_Methods() { - UShortPolyfill.TryParse("1", null, out _); + ushort.TryParse(s: "1", provider: null, result: out _); #if FeatureMemory - UShortPolyfill.TryParse("1"u8, null, out _); - UShortPolyfill.TryParse(['1'], out _); - UShortPolyfill.TryParse(['1'], null, out _); - UShortPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out _); - UShortPolyfill.TryParse("1"u8, out _); - UShortPolyfill.TryParse(['1'], NumberStyles.Integer, null, out _); + ushort.TryParse(utf8Text: "1"u8, provider: null, result: out _); + ushort.TryParse(s: ['1'], result: out _); + ushort.TryParse(s: ['1'], provider: null, result: out _); + ushort.TryParse(utf8Text: "1"u8, style: NumberStyles.Integer, null, result: out _); + ushort.TryParse(utf8Text: "1"u8, result: out _); + ushort.TryParse(s: ['1'], style: NumberStyles.Integer, null, result: out _); #endif } - void XDocument_Methods() + async Task XDocument_Methods(XDocument document) { - var document = new XDocument(); document.SaveAsync(new XmlTextWriter(null!), CancellationToken.None); document.SaveAsync(new StringWriter(), SaveOptions.None, CancellationToken.None); document.SaveAsync(new MemoryStream(), SaveOptions.None, CancellationToken.None); + await XDocument.LoadAsync((Stream) null!, LoadOptions.None, CancellationToken.None); + await XDocument.LoadAsync((TextReader) null!, LoadOptions.None, CancellationToken.None); + await XDocument.LoadAsync((XmlReader) null!, LoadOptions.None, CancellationToken.None); } - void XElement_Methods() + async Task XElement_Methods(XElement element) { - XElement element = null!; element.SaveAsync(new XmlTextWriter(null!), CancellationToken.None); element.SaveAsync(new StringWriter(), SaveOptions.None, CancellationToken.None); element.SaveAsync(new MemoryStream(), SaveOptions.None, CancellationToken.None); + await XElement.LoadAsync((Stream) null!, LoadOptions.None, CancellationToken.None); + await XElement.LoadAsync((TextReader) null!, LoadOptions.None, CancellationToken.None); + await XElement.LoadAsync((XmlReader) null!, LoadOptions.None, CancellationToken.None); } #if FeatureCompression diff --git a/src/ConsumeCs13/ConsumeCs13.csproj b/src/ConsumeCs14/ConsumeCs14.csproj similarity index 92% rename from src/ConsumeCs13/ConsumeCs13.csproj rename to src/ConsumeCs14/ConsumeCs14.csproj index 4f9f0644..617d5bb0 100644 --- a/src/ConsumeCs13/ConsumeCs13.csproj +++ b/src/ConsumeCs14/ConsumeCs14.csproj @@ -2,7 +2,11 @@ $(NoWarn);PolyfillTargetsForNuget true - 13.0 + + preview net461;net462;net47;net471;net472;net48;net481;net6.0-windows $(TargetFrameworks);netstandard2.0;netstandard2.1;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 diff --git a/src/ConsumeCsDefault/ConsumeCsDefault.csproj b/src/ConsumeCsDefault/ConsumeCsDefault.csproj index 1164cc8f..331bd501 100644 --- a/src/ConsumeCsDefault/ConsumeCsDefault.csproj +++ b/src/ConsumeCsDefault/ConsumeCsDefault.csproj @@ -2,7 +2,11 @@ $(NoWarn);PolyfillTargetsForNuget true - default + + preview net461;net462;net47;net471;net472;net48;net481;net6.0-windows $(TargetFrameworks);netstandard2.0;netstandard2.1;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 diff --git a/src/ConsumeCsLatest/ConsumeCsLatest.csproj b/src/ConsumeCsLatest/ConsumeCsLatest.csproj index 76026f72..cd167712 100644 --- a/src/ConsumeCsLatest/ConsumeCsLatest.csproj +++ b/src/ConsumeCsLatest/ConsumeCsLatest.csproj @@ -2,7 +2,11 @@ $(NoWarn);PolyfillTargetsForNuget true - latest + + preview net461;net462;net47;net471;net472;net48;net481;net6.0-windows $(TargetFrameworks);netstandard2.0;netstandard2.1;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 diff --git a/src/ConsumeCsLatestMajor/ConsumeCsLatestMajor.csproj b/src/ConsumeCsLatestMajor/ConsumeCsLatestMajor.csproj index 53b14ba9..8249f2a2 100644 --- a/src/ConsumeCsLatestMajor/ConsumeCsLatestMajor.csproj +++ b/src/ConsumeCsLatestMajor/ConsumeCsLatestMajor.csproj @@ -2,7 +2,11 @@ $(NoWarn);PolyfillTargetsForNuget true - latestMajor + + preview net461;net462;net47;net471;net472;net48;net481;net6.0-windows $(TargetFrameworks);netstandard2.0;netstandard2.1;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 diff --git a/src/ConsumeEmbeddedLib/ConsumeEmbeddedLib.csproj b/src/ConsumeEmbeddedLib/ConsumeEmbeddedLib.csproj new file mode 100644 index 00000000..3150c347 --- /dev/null +++ b/src/ConsumeEmbeddedLib/ConsumeEmbeddedLib.csproj @@ -0,0 +1,22 @@ + + + $(NoWarn);PolyfillTargetsForNuget + true + + preview + + netstandard2.0 + true + + + + + + + + + + \ No newline at end of file diff --git a/src/ConsumeEmbeddedLib/UsageOfConstantExpected.cs b/src/ConsumeEmbeddedLib/UsageOfConstantExpected.cs new file mode 100644 index 00000000..8c90e3c9 --- /dev/null +++ b/src/ConsumeEmbeddedLib/UsageOfConstantExpected.cs @@ -0,0 +1,11 @@ +using System.Diagnostics.CodeAnalysis; + +namespace ConsumeEmbeddedLib; + +internal class UsageOfConstantExpected +{ + // Only ensures that this does compile. + public void M([ConstantExpected] int _) + { + } +} diff --git a/src/ConsumeNoOptional/ConsumeNoOptional.csproj b/src/ConsumeNoOptional/ConsumeNoOptional.csproj index 2ec22488..a07c33e9 100644 --- a/src/ConsumeNoOptional/ConsumeNoOptional.csproj +++ b/src/ConsumeNoOptional/ConsumeNoOptional.csproj @@ -4,7 +4,7 @@ true net461;net462;net47;net471;net472;net48;net481;net6.0-windows;netstandard2.0;netstandard2.1;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 false - false + false false $(DefineConstants);NoStringInterpolation diff --git a/src/Directory.Build.props b/src/Directory.Build.props index c1943370..c8ad8661 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ CS1591;NETSDK1138;NU1901;NU1902;NU1903;CA1822;CA1847;CA1861;NU1510;NU1608;NU1109 - 8.9.1 + 9.0.0-beta.24 1.0.0 Polyfill true @@ -15,11 +15,13 @@ true true true - true + true true true enable true + + false \ No newline at end of file diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index cecc1019..11572908 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -4,14 +4,14 @@ true - + - - + + @@ -19,6 +19,6 @@ - + \ No newline at end of file diff --git a/src/EmbeddedTests/EmbeddedTests.csproj b/src/EmbeddedTests/EmbeddedTests.csproj new file mode 100644 index 00000000..06c2a261 --- /dev/null +++ b/src/EmbeddedTests/EmbeddedTests.csproj @@ -0,0 +1,26 @@ + + + $(NoWarn);PolyfillTargetsForNuget + net462;net472;net48 + $(TargetFrameworks);netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0 + true + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/EmbeddedTests/UsageOfConstantExpected.cs b/src/EmbeddedTests/UsageOfConstantExpected.cs new file mode 100644 index 00000000..8bec7582 --- /dev/null +++ b/src/EmbeddedTests/UsageOfConstantExpected.cs @@ -0,0 +1,12 @@ +namespace EmbeddedTests; + +internal class UsageOfConstantExpected +{ + // Only ensures that this does compile. + // 1. The typeof expression ensures that ConsumeEmbeddedLib is referenced and is exposing IVT to EmbeddedTests. + // 2. ConsumeEmbeddedLib.UsageOfConstantExpected is expected to be using ConstantExpected from Polyfill. + // 3. Because EmbeddedAttribute is used, there is no clash between EmbeddedAttribute from Polyfill in ConsumeEmbeddedLib and + // the one in System.Runtime when EmbeddedTests is compiled against .NET 7 or later. + public void M([ConstantExpected] int x) + => _ = typeof(ConsumeEmbeddedLib.UsageOfConstantExpected); +} diff --git a/src/NoExtrasTests/NoExtrasTests.csproj b/src/NoExtrasTests/NoExtrasTests.csproj index c548becd..783eca0c 100644 --- a/src/NoExtrasTests/NoExtrasTests.csproj +++ b/src/NoExtrasTests/NoExtrasTests.csproj @@ -2,7 +2,7 @@ $(NoWarn);PolyfillTargetsForNuget net10.0 - false + false false false NoExtras diff --git a/src/NoExtrasTests/Tests.cs b/src/NoExtrasTests/Tests.cs index ad5b0826..841bb8e2 100644 --- a/src/NoExtrasTests/Tests.cs +++ b/src/NoExtrasTests/Tests.cs @@ -2,8 +2,8 @@ public class Tests { [Test] - public void NoGuard() => - Assert.IsNull(GetType().Assembly.GetType("Polyfills.Guard")); + public void NoEnsure() => + Assert.IsNull(GetType().Assembly.GetType("Polyfills.Ensure")); [Test] public void NoNullExtensions() diff --git a/src/Polyfill.sln b/src/Polyfill.sln deleted file mode 100644 index 94b8c7a7..00000000 --- a/src/Polyfill.sln +++ /dev/null @@ -1,192 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.1.32120.378 -MinimumVisualStudioVersion = 16.0.29201.188 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9A6C4741-C83D-4E05-A62F-8049F65B9B6C}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .gitattributes = .gitattributes - ..\.gitignore = ..\.gitignore - appveyor.yml = appveyor.yml - Directory.Build.props = Directory.Build.props - Directory.Packages.props = Directory.Packages.props - global.json = global.json - mdsnippets.json = mdsnippets.json - ..\readme.md = ..\readme.md - Polyfill\Polyfill.nuspec = Polyfill\Polyfill.nuspec - Polyfill\Polyfill.targets = Polyfill\Polyfill.targets - TestIncludes.targets = TestIncludes.targets - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Polyfill", "Polyfill\Polyfill.csproj", "{698FB675-3480-4107-8CAE-51452C6138CE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Tests\Tests.csproj", "{CA1869D1-4531-40C7-AE55-5885F4DD8448}" - ProjectSection(ProjectDependencies) = postProject - {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA} = {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Consume", "Consume\Consume.csproj", "{32C38E3C-4040-455F-A27D-4EA5DB0F8EFA}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnsafeTests", "UnsafeTests\UnsafeTests.csproj", "{F49A3C33-48A3-4954-9AC0-5C7B30AC2B2B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PublicTests", "PublicTests\PublicTests.csproj", "{9FBD54A6-461C-4754-B77A-222E06BF89B6}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsumeClassicReferences", "ConsumeClassicReferences\ConsumeClassicReferences.csproj", "{CF7D4778-6A32-4E7D-B80B-3507974B443B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsumeIndirect", "ConsumeIndirect\ConsumeIndirect.csproj", "{955038AF-1073-4BB0-8AF7-D4597B7C2DAB}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoRefsTests", "NoRefsTests\NoRefsTests.csproj", "{A9EEAECD-A8B2-45C1-9A9D-94443601CB5F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsumeNoRefs", "ConsumeNoRefs\ConsumeNoRefs.csproj", "{B4DC96CA-C700-499F-A9A2-0C767DCF8C30}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsumeOnlyTasks", "ConsumeOnlyTasks\ConsumeOnlyTasks.csproj", "{96EF1E04-5862-4D9E-B800-A6402F1ADF7A}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TargetFrameworkUsage", "TargetFrameworkUsage\TargetFrameworkUsage.csproj", "{41CB5A0C-E0F5-4C5C-B2FC-9A289E8CFDF8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeOnlyMemory", "ConsumeOnlyMemory\ConsumeOnlyMemory.csproj", "{1BDDA7F0-0D45-418C-B3DB-BBA39C29FD77}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeCs13", "ConsumeCs13\ConsumeCs13.csproj", "{EE99F818-0D49-434F-B787-348CA34051EF}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeCsLatest", "ConsumeCsLatest\ConsumeCsLatest.csproj", "{684570FB-7049-44F0-9DCC-32F73F242694}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeCsLatestMajor", "ConsumeCsLatestMajor\ConsumeCsLatestMajor.csproj", "{9BB64345-DE4F-4396-9320-AAA712D7E3CE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeCsDefault", "ConsumeCsDefault\ConsumeCsDefault.csproj", "{86AA1F8D-4081-4D31-812E-866C0951415D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiBuilderTests", "ApiBuilderTests\ApiBuilderTests.csproj", "{CC0C08FE-14E1-4A3D-8547-EFC8097D48C4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeOnlyValueTuple", "ConsumeOnlyValueTuple\ConsumeOnlyValueTuple.csproj", "{2FE1429A-68B0-4C71-B1ED-D371C72DAD0E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoExtrasTests", "NoExtrasTests\NoExtrasTests.csproj", "{4F482296-D4BF-4E56-AF23-351CCEF1B96E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeBclMemory", "ConsumeBclMemory\ConsumeBclMemory.csproj", "{A89A3ACD-3DC8-4321-AEBC-05DAF0DEC9E5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeConsumeBclMemory", "ConsumeConsumeBclMemory\ConsumeConsumeBclMemory.csproj", "{E83A80D1-10E3-4CBE-942D-E671A04C93F7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeOnlyCompression", "ConsumeOnlyCompression\ConsumeOnlyCompression.csproj", "{E8E46E75-763A-4031-8545-E67DFB768D1E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeNoOptional", "ConsumeNoOptional\ConsumeNoOptional.csproj", "{AD562B55-4340-4AFC-8FDE-78F3C87A5435}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolyfillLib", "PolyfillLib\PolyfillLib.csproj", "{FD2DAEE4-7931-4A3B-93E5-2FC5C3AE8D4D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeLib", "ConsumeLib\ConsumeLib.csproj", "{FD473139-ACDA-4795-A829-31DA3B883063}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeTrimmed", "ConsumeTrimmed\ConsumeTrimmed.csproj", "{4BC31EB7-4545-4C96-B6B7-B94131BDD426}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {698FB675-3480-4107-8CAE-51452C6138CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Release|Any CPU.Build.0 = Release|Any CPU - {CA1869D1-4531-40C7-AE55-5885F4DD8448}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CA1869D1-4531-40C7-AE55-5885F4DD8448}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CA1869D1-4531-40C7-AE55-5885F4DD8448}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CA1869D1-4531-40C7-AE55-5885F4DD8448}.Release|Any CPU.Build.0 = Release|Any CPU - {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {32C38E3C-4040-455F-A27D-4EA5DB0F8EFA}.Release|Any CPU.Build.0 = Release|Any CPU - {F49A3C33-48A3-4954-9AC0-5C7B30AC2B2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F49A3C33-48A3-4954-9AC0-5C7B30AC2B2B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F49A3C33-48A3-4954-9AC0-5C7B30AC2B2B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F49A3C33-48A3-4954-9AC0-5C7B30AC2B2B}.Release|Any CPU.Build.0 = Release|Any CPU - {9FBD54A6-461C-4754-B77A-222E06BF89B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9FBD54A6-461C-4754-B77A-222E06BF89B6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9FBD54A6-461C-4754-B77A-222E06BF89B6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9FBD54A6-461C-4754-B77A-222E06BF89B6}.Release|Any CPU.Build.0 = Release|Any CPU - {CF7D4778-6A32-4E7D-B80B-3507974B443B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CF7D4778-6A32-4E7D-B80B-3507974B443B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CF7D4778-6A32-4E7D-B80B-3507974B443B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CF7D4778-6A32-4E7D-B80B-3507974B443B}.Release|Any CPU.Build.0 = Release|Any CPU - {955038AF-1073-4BB0-8AF7-D4597B7C2DAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {955038AF-1073-4BB0-8AF7-D4597B7C2DAB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {955038AF-1073-4BB0-8AF7-D4597B7C2DAB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {955038AF-1073-4BB0-8AF7-D4597B7C2DAB}.Release|Any CPU.Build.0 = Release|Any CPU - {A9EEAECD-A8B2-45C1-9A9D-94443601CB5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A9EEAECD-A8B2-45C1-9A9D-94443601CB5F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A9EEAECD-A8B2-45C1-9A9D-94443601CB5F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A9EEAECD-A8B2-45C1-9A9D-94443601CB5F}.Release|Any CPU.Build.0 = Release|Any CPU - {B4DC96CA-C700-499F-A9A2-0C767DCF8C30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B4DC96CA-C700-499F-A9A2-0C767DCF8C30}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B4DC96CA-C700-499F-A9A2-0C767DCF8C30}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B4DC96CA-C700-499F-A9A2-0C767DCF8C30}.Release|Any CPU.Build.0 = Release|Any CPU - {96EF1E04-5862-4D9E-B800-A6402F1ADF7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {96EF1E04-5862-4D9E-B800-A6402F1ADF7A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {96EF1E04-5862-4D9E-B800-A6402F1ADF7A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {96EF1E04-5862-4D9E-B800-A6402F1ADF7A}.Release|Any CPU.Build.0 = Release|Any CPU - {41CB5A0C-E0F5-4C5C-B2FC-9A289E8CFDF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {41CB5A0C-E0F5-4C5C-B2FC-9A289E8CFDF8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {41CB5A0C-E0F5-4C5C-B2FC-9A289E8CFDF8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1BDDA7F0-0D45-418C-B3DB-BBA39C29FD77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1BDDA7F0-0D45-418C-B3DB-BBA39C29FD77}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1BDDA7F0-0D45-418C-B3DB-BBA39C29FD77}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1BDDA7F0-0D45-418C-B3DB-BBA39C29FD77}.Release|Any CPU.Build.0 = Release|Any CPU - {EE99F818-0D49-434F-B787-348CA34051EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE99F818-0D49-434F-B787-348CA34051EF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE99F818-0D49-434F-B787-348CA34051EF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE99F818-0D49-434F-B787-348CA34051EF}.Release|Any CPU.Build.0 = Release|Any CPU - {684570FB-7049-44F0-9DCC-32F73F242694}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {684570FB-7049-44F0-9DCC-32F73F242694}.Debug|Any CPU.Build.0 = Debug|Any CPU - {684570FB-7049-44F0-9DCC-32F73F242694}.Release|Any CPU.ActiveCfg = Release|Any CPU - {684570FB-7049-44F0-9DCC-32F73F242694}.Release|Any CPU.Build.0 = Release|Any CPU - {9BB64345-DE4F-4396-9320-AAA712D7E3CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9BB64345-DE4F-4396-9320-AAA712D7E3CE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9BB64345-DE4F-4396-9320-AAA712D7E3CE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9BB64345-DE4F-4396-9320-AAA712D7E3CE}.Release|Any CPU.Build.0 = Release|Any CPU - {86AA1F8D-4081-4D31-812E-866C0951415D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {86AA1F8D-4081-4D31-812E-866C0951415D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {86AA1F8D-4081-4D31-812E-866C0951415D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {86AA1F8D-4081-4D31-812E-866C0951415D}.Release|Any CPU.Build.0 = Release|Any CPU - {CC0C08FE-14E1-4A3D-8547-EFC8097D48C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CC0C08FE-14E1-4A3D-8547-EFC8097D48C4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CC0C08FE-14E1-4A3D-8547-EFC8097D48C4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2FE1429A-68B0-4C71-B1ED-D371C72DAD0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2FE1429A-68B0-4C71-B1ED-D371C72DAD0E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2FE1429A-68B0-4C71-B1ED-D371C72DAD0E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2FE1429A-68B0-4C71-B1ED-D371C72DAD0E}.Release|Any CPU.Build.0 = Release|Any CPU - {4F482296-D4BF-4E56-AF23-351CCEF1B96E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4F482296-D4BF-4E56-AF23-351CCEF1B96E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4F482296-D4BF-4E56-AF23-351CCEF1B96E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4F482296-D4BF-4E56-AF23-351CCEF1B96E}.Release|Any CPU.Build.0 = Release|Any CPU - {A89A3ACD-3DC8-4321-AEBC-05DAF0DEC9E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A89A3ACD-3DC8-4321-AEBC-05DAF0DEC9E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A89A3ACD-3DC8-4321-AEBC-05DAF0DEC9E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A89A3ACD-3DC8-4321-AEBC-05DAF0DEC9E5}.Release|Any CPU.Build.0 = Release|Any CPU - {E83A80D1-10E3-4CBE-942D-E671A04C93F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E83A80D1-10E3-4CBE-942D-E671A04C93F7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E83A80D1-10E3-4CBE-942D-E671A04C93F7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E83A80D1-10E3-4CBE-942D-E671A04C93F7}.Release|Any CPU.Build.0 = Release|Any CPU - {E8E46E75-763A-4031-8545-E67DFB768D1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E8E46E75-763A-4031-8545-E67DFB768D1E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E8E46E75-763A-4031-8545-E67DFB768D1E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E8E46E75-763A-4031-8545-E67DFB768D1E}.Release|Any CPU.Build.0 = Release|Any CPU - {AD562B55-4340-4AFC-8FDE-78F3C87A5435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AD562B55-4340-4AFC-8FDE-78F3C87A5435}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AD562B55-4340-4AFC-8FDE-78F3C87A5435}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AD562B55-4340-4AFC-8FDE-78F3C87A5435}.Release|Any CPU.Build.0 = Release|Any CPU - {FD2DAEE4-7931-4A3B-93E5-2FC5C3AE8D4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FD2DAEE4-7931-4A3B-93E5-2FC5C3AE8D4D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FD2DAEE4-7931-4A3B-93E5-2FC5C3AE8D4D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FD2DAEE4-7931-4A3B-93E5-2FC5C3AE8D4D}.Release|Any CPU.Build.0 = Release|Any CPU - {FD473139-ACDA-4795-A829-31DA3B883063}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FD473139-ACDA-4795-A829-31DA3B883063}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FD473139-ACDA-4795-A829-31DA3B883063}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FD473139-ACDA-4795-A829-31DA3B883063}.Release|Any CPU.Build.0 = Release|Any CPU - {4BC31EB7-4545-4C96-B6B7-B94131BDD426}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4BC31EB7-4545-4C96-B6B7-B94131BDD426}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4BC31EB7-4545-4C96-B6B7-B94131BDD426}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4BC31EB7-4545-4C96-B6B7-B94131BDD426}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B0B94980-5385-4EC6-A0EE-C9A191DDFC05} - EndGlobalSection -EndGlobal diff --git a/src/Polyfill.slnf b/src/Polyfill.slnf index 98f38428..d8bab2fb 100644 --- a/src/Polyfill.slnf +++ b/src/Polyfill.slnf @@ -1,6 +1,6 @@ { "solution": { - "path": "Polyfill.sln", + "path": "Polyfill.slnx", "projects": [ "ApiBuilderTests\\ApiBuilderTests.csproj", "Consume\\Consume.csproj", diff --git a/src/Polyfill.slnx b/src/Polyfill.slnx new file mode 100644 index 00000000..86590540 --- /dev/null +++ b/src/Polyfill.slnx @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Polyfill.sln.DotSettings b/src/Polyfill.slnx.DotSettings similarity index 100% rename from src/Polyfill.sln.DotSettings rename to src/Polyfill.slnx.DotSettings diff --git a/src/Polyfill/CallerArgumentExpressionAttribute.cs b/src/Polyfill/CallerArgumentExpressionAttribute.cs index cc2c053c..974e1cf8 100644 --- a/src/Polyfill/CallerArgumentExpressionAttribute.cs +++ b/src/Polyfill/CallerArgumentExpressionAttribute.cs @@ -14,6 +14,9 @@ namespace System.Runtime.CompilerServices; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/CollectionBuilderAttribute.cs b/src/Polyfill/CollectionBuilderAttribute.cs index fa8591ef..28757a94 100644 --- a/src/Polyfill/CollectionBuilderAttribute.cs +++ b/src/Polyfill/CollectionBuilderAttribute.cs @@ -12,6 +12,9 @@ namespace System.Runtime.CompilerServices; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.collectionbuilderattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/CompilerFeatureRequiredAttribute.cs b/src/Polyfill/CompilerFeatureRequiredAttribute.cs index 5dc5d03a..0e312ca6 100644 --- a/src/Polyfill/CompilerFeatureRequiredAttribute.cs +++ b/src/Polyfill/CompilerFeatureRequiredAttribute.cs @@ -17,6 +17,9 @@ namespace System.Runtime.CompilerServices; validOn: AttributeTargets.All, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.compilerfeaturerequiredattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/ConstantExpectedAttribute.cs b/src/Polyfill/ConstantExpectedAttribute.cs index 25178de5..ada9f988 100644 --- a/src/Polyfill/ConstantExpectedAttribute.cs +++ b/src/Polyfill/ConstantExpectedAttribute.cs @@ -14,6 +14,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.constantexpectedattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/ConvertPolyfill.cs b/src/Polyfill/ConvertPolyfill.cs index 6e91a7ea..5ba75418 100644 --- a/src/Polyfill/ConvertPolyfill.cs +++ b/src/Polyfill/ConvertPolyfill.cs @@ -1,203 +1,172 @@ // #pragma warning disable +#if !NET9_0_OR_GREATER + namespace Polyfills; using System; using System.Text; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class ConvertPolyfill +static partial class Polyfill { - /// - /// Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. - /// Parameters specify the subset as an offset in the input array and the number of elements in the array to convert. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32) - public static string ToHexString(byte[] inArray, int offset, int length) => -#if NET - Convert.ToHexString(inArray, offset, length); -#else - ToHexString(inArray, offset, length, "X2"); + extension(Convert) + { +#if !NET + + /// + /// Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. + /// Parameters specify the subset as an offset in the input array and the number of elements in the array to convert. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()-system-int32-system-int32) + public static string ToHexString(byte[] inArray, int offset, int length) => + ToHexString(inArray, offset, length, "X2"); #endif - /// - /// Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. - /// Parameters specify the subset as an offset in the input array and the number of elements in the array to convert. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32) - public static string ToHexStringLower(byte[] inArray, int offset, int length) => -#if NET9_0_OR_GREATER - Convert.ToHexStringLower(inArray, offset, length); -#else - ToHexString(inArray, offset, length, "x2"); +#if !NET9_0_OR_GREATER + /// + /// Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. + /// Parameters specify the subset as an offset in the input array and the number of elements in the array to convert. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()-system-int32-system-int32) + public static string ToHexStringLower(byte[] inArray, int offset, int length) => + ToHexString(inArray, offset, length, "x2"); + + /// + /// Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()) + public static string ToHexStringLower(byte[] inArray) => + Polyfill.ToHexStringLower(inArray, 0, inArray.Length); #endif - -#if !NET || !NET9_0_OR_GREATER - static string ToHexString(byte[] inArray, int offset, int length, string format) - { - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length)); - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); - if (offset > (inArray.Length - length)) - throw new ArgumentOutOfRangeException(nameof(offset)); - - var builder = new StringBuilder(length * 2); - - var end = length + offset; - for (int i = offset; i < end; i++) +#if !NET + /// + /// Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()) + public static string ToHexString(byte[] inArray) => + Polyfill.ToHexString(inArray, 0, inArray.Length); + + /// + /// Converts the specified string, which encodes binary data as hex characters, to an equivalent 8-bit unsigned integer array. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string) + public static byte[] FromHexString(string hexString) { - var item = inArray[i]; - builder.Append(item.ToString(format)); - } + if (hexString.Length % 2 != 0) + throw new FormatException("Hex string must have an even length."); - return builder.ToString(); - } -#endif + var result = new byte[hexString.Length / 2]; - /// - /// Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-byte()) - public static string ToHexString(byte[] inArray) => -#if NET - Convert.ToHexString(inArray); -#else - ConvertPolyfill.ToHexString(inArray, 0, inArray.Length); -#endif + for (int i = 0; i < result.Length; i++) + { + result[i] = (byte) ((GetHexValue(hexString[i * 2]) << 4) + GetHexValue(hexString[i * 2 + 1])); + } - /// - /// Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-byte()) - public static string ToHexStringLower(byte[] inArray) => -#if NET9_0_OR_GREATER - Convert.ToHexStringLower(inArray); -#else - ConvertPolyfill.ToHexStringLower(inArray, 0, inArray.Length); + return result; + + static int GetHexValue(char hex) + { + return hex switch + { + >= '0' and <= '9' => hex - '0', + >= 'A' and <= 'F' => hex - 'A' + 10, + >= 'a' and <= 'f' => hex - 'a' + 10, + _ => throw new FormatException($"Invalid hex character: {hex}") + }; + } + } #endif #if FeatureMemory - /// - /// Converts a span of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte))) - public static string ToHexString(ReadOnlySpan bytes) => -#if NET - Convert.ToHexString(bytes); -#else - ConvertPolyfill.ToHexString(bytes.ToArray()); -#endif - /// - /// Converts a span of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte))) - public static string ToHexStringLower(ReadOnlySpan bytes) => -#if NET9_0_OR_GREATER - Convert.ToHexStringLower(bytes); -#else - ConvertPolyfill.ToHexStringLower(bytes.ToArray()); +#if !NET + /// + /// Converts the span, which encodes binary data as hex characters, to an equivalent 8-bit unsigned integer array. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char))) + public static byte[] FromHexString(ReadOnlySpan chars) => + Polyfill.FromHexString(chars.ToString()); + + /// + /// Converts a span of 8-bit unsigned integers to its equivalent string representation that is encoded with uppercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-10.0#system-convert-tohexstring(system-readonlyspan((system-byte))) + public static string ToHexString(ReadOnlySpan bytes) => + Polyfill.ToHexString(bytes.ToArray()); #endif - /// - /// Converts a span of 8-bit unsigned integers to its equivalent span representation that is encoded with uppercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0 - public static bool TryToHexString(ReadOnlySpan source, Span destination, out int charsWritten) -#if NET9_0_OR_GREATER - => Convert.TryToHexString(source, destination, out charsWritten); -#else - { - if (source.Length > destination.Length / 2) +#if !NET9_0_OR_GREATER + /// + /// Converts a span of 8-bit unsigned integers to its equivalent string representation that is encoded with lowercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstringlower?view=net-10.0#system-convert-tohexstringlower(system-readonlyspan((system-byte))) + public static string ToHexStringLower(ReadOnlySpan bytes) => + Polyfill.ToHexStringLower(bytes.ToArray()); + + /// + /// Converts a span of 8-bit unsigned integers to its equivalent span representation that is encoded with uppercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstring?view=net-10.0 + public static bool TryToHexString(ReadOnlySpan source, Span destination, out int charsWritten) { - charsWritten = 0; - return false; + if (source.Length > destination.Length / 2) + { + charsWritten = 0; + return false; + } + + var hexString = Convert.ToHexString(source); + hexString.CopyTo(destination); + charsWritten = hexString.Length; + return true; } - var hexString = ConvertPolyfill.ToHexString(source); - hexString.CopyTo(destination); - charsWritten = hexString.Length; - return true; - } -#endif - - /// - /// Converts a span of 8-bit unsigned integers to its equivalent span representation that is encoded with lowercase hex characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0 - public static bool TryToHexStringLower(ReadOnlySpan source, Span destination, out int charsWritten) -#if NET9_0_OR_GREATER - => Convert.TryToHexStringLower(source, destination, out charsWritten); -#else - { - if (source.Length > destination.Length / 2) + /// + /// Converts a span of 8-bit unsigned integers to its equivalent span representation that is encoded with lowercase hex characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.trytohexstringlower?view=net-10.0 + public static bool TryToHexStringLower(ReadOnlySpan source, Span destination, out int charsWritten) { - charsWritten = 0; - return false; + if (source.Length > destination.Length / 2) + { + charsWritten = 0; + return false; + } + + var hexString = Convert.ToHexStringLower(source); + hexString.CopyTo(destination); + charsWritten = hexString.Length; + return true; } - - var hexString = ConvertPolyfill.ToHexStringLower(source); - hexString.CopyTo(destination); - charsWritten = hexString.Length; - return true; - } #endif - #endif - /// - /// Converts the specified string, which encodes binary data as hex characters, to an equivalent 8-bit unsigned integer array. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-string) - public static byte[] FromHexString(string hexString) -#if NET - => Convert.FromHexString(hexString); -#else - { - if (hexString.Length % 2 != 0) - throw new FormatException("Hex string must have an even length."); - - var result = new byte[hexString.Length / 2]; +#if !NET || !NET9_0_OR_GREATER - for (int i = 0; i < result.Length; i++) + static string ToHexString(byte[] inArray, int offset, int length, string format) { - result[i] = (byte) ((GetHexValue(hexString[i * 2]) << 4) + GetHexValue(hexString[i * 2 + 1])); - } + if (length < 0) + throw new ArgumentOutOfRangeException(nameof(length)); + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset)); + if (offset > (inArray.Length - length)) + throw new ArgumentOutOfRangeException(nameof(offset)); - return result; + var builder = new StringBuilder(length * 2); - static int GetHexValue(char hex) - { - return hex switch + var end = length + offset; + for (int i = offset; i < end; i++) { - >= '0' and <= '9' => hex - '0', - >= 'A' and <= 'F' => hex - 'A' + 10, - >= 'a' and <= 'f' => hex - 'a' + 10, - _ => throw new FormatException($"Invalid hex character: {hex}") - }; + var item = inArray[i]; + builder.Append(item.ToString(format)); + } + + return builder.ToString(); } - } -#endif -#if FeatureMemory - /// - /// Converts the span, which encodes binary data as hex characters, to an equivalent 8-bit unsigned integer array. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring?view=net-10.0#system-convert-fromhexstring(system-readonlyspan((system-char))) - public static byte[] FromHexString(ReadOnlySpan chars) => -#if NET - Convert.FromHexString(chars); -#else - ConvertPolyfill.FromHexString(chars.ToString()); #endif -#endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/DateTimeOffsetPolyfill.cs b/src/Polyfill/DateTimeOffsetPolyfill.cs index 28f1319f..846911bd 100644 --- a/src/Polyfill/DateTimeOffsetPolyfill.cs +++ b/src/Polyfill/DateTimeOffsetPolyfill.cs @@ -3,86 +3,69 @@ #nullable enable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class DateTimeOffsetPolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@) - public static bool TryParse(string? target, IFormatProvider? provider, out DateTimeOffset result) => -#if NET7_0_OR_GREATER - DateTimeOffset.TryParse(target, provider, out result); -#else - DateTimeOffset.TryParse(target, provider, DateTimeStyles.None, out result); + extension(DateTimeOffset) + { +#if !NET7_0_OR_GREATER + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-string-system-iformatprovider-system-datetimeoffset@) + public static bool TryParse(string? s, IFormatProvider? provider, out DateTimeOffset result) => + DateTimeOffset.TryParse(s, provider, DateTimeStyles.None, out result); #endif #if FeatureMemory - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out DateTimeOffset result) => -#if NET8_0_OR_GREATER - DateTimeOffset.TryParse(target, provider, out result); -#else - DateTimeOffset.TryParse(target.ToString(), provider, DateTimeStyles.None, out result); +#if !NET8_0_OR_GREATER + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetimeoffset@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out DateTimeOffset result) => + DateTimeOffset.TryParse(s.ToString(), provider, DateTimeStyles.None, out result); #endif - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@) - public static bool TryParse(ReadOnlySpan target, out DateTimeOffset result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTimeOffset.TryParse(target, out result); -#else - DateTimeOffset.TryParse(target.ToString(), null, DateTimeStyles.None, out result); -#endif +#if !(NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER) + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-datetimeoffset@) + public static bool TryParse(ReadOnlySpan input, out DateTimeOffset result) => + DateTimeOffset.TryParse(input.ToString(), null, DateTimeStyles.None, out result); - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTimeOffset.TryParse(target, provider, styles, out result); -#else - DateTimeOffset.TryParse(target.ToString(), provider, styles, out result); -#endif + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse?view=net-10.0#system-datetimeoffset-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => + DateTimeOffset.TryParse(s.ToString(), provider, styles, out result); - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) - public static bool TryParseExact(ReadOnlySpan target, string format, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTimeOffset.TryParseExact(target, format, provider, styles, out result); -#else - DateTimeOffset.TryParseExact(target.ToString(), format, provider, styles, out result); + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) + public static bool TryParseExact(ReadOnlySpan input, string format, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => + DateTimeOffset.TryParseExact(input.ToString(), format, provider, styles, out result); #endif - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) - public static bool TryParseExact(ReadOnlySpan target, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - DateTimeOffset.TryParseExact(target, format, provider, styles, out result); -#else - DateTimeOffset.TryParseExact(target.ToString(), format.ToString(), provider, styles, out result); +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact?view=net-10.0#system-datetimeoffset-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetimeoffset@) + public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles styles, out DateTimeOffset result) => + DateTimeOffset.TryParseExact(input.ToString(), format.ToString(), provider, styles, out result); #endif #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/DateTimePolyfill.cs b/src/Polyfill/DateTimePolyfill.cs index b381dc6f..3feaeeaa 100644 --- a/src/Polyfill/DateTimePolyfill.cs +++ b/src/Polyfill/DateTimePolyfill.cs @@ -1,87 +1,70 @@ // #pragma warning disable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class DateTimePolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@) - public static bool TryParse(string? target, IFormatProvider? provider, out DateTime result) => -#if NET7_0_OR_GREATER - DateTime.TryParse(target, provider, out result); -#else - DateTime.TryParse(target, provider, DateTimeStyles.None, out result); + extension(DateTime) + { +#if !NET7_0_OR_GREATER + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-string-system-iformatprovider-system-datetime@) + public static bool TryParse(string? s, IFormatProvider? provider, out DateTime result) => + DateTime.TryParse(s, provider, DateTimeStyles.None, out result); #endif #if FeatureMemory - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out DateTime result) => -#if NET8_0_OR_GREATER - DateTime.TryParse(target, provider, out result); -#else - DateTime.TryParse(target.ToString(), provider, DateTimeStyles.None, out result); +#if !NET8_0_OR_GREATER + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-datetime@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out DateTime result) => + DateTime.TryParse(s.ToString(), provider, DateTimeStyles.None, out result); #endif - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@) - public static bool TryParse(ReadOnlySpan target, out DateTime result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTime.TryParse(target, out result); -#else - DateTime.TryParse(target.ToString(), null, DateTimeStyles.None, out result); -#endif +#if !(NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER) + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-datetime@) + public static bool TryParse(ReadOnlySpan s, out DateTime result) => + DateTime.TryParse(s.ToString(), null, DateTimeStyles.None, out result); - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTime.TryParse(target, provider, styles, out result); -#else - DateTime.TryParse(target.ToString(), provider, styles, out result); -#endif + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-10.0#system-datetime-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) => + DateTime.TryParse(s.ToString(), provider, styles, out result); - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) - public static bool TryParseExact(ReadOnlySpan target, string format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - DateTime.TryParseExact(target, format, provider, style, out result); -#else - DateTime.TryParseExact(target.ToString(), format, provider, style, out result); + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) + public static bool TryParseExact(ReadOnlySpan s, string format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) => + DateTime.TryParseExact(s.ToString(), format, provider, style, out result); #endif - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) - public static bool TryParseExact(ReadOnlySpan target, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) => -#if NETCOREAPP2_1_OR_GREATER && NETSTANDARD2_1_OR_GREATER - DateTime.TryParseExact(target, format, provider, styles, out result); -#else - DateTime.TryParseExact(target.ToString(), format.ToString(), provider, styles, out result); +#if !(NETCOREAPP2_1_OR_GREATER && NETSTANDARD2_1_OR_GREATER) + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=net-10.0#system-datetime-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-iformatprovider-system-globalization-datetimestyles-system-datetime@) + public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) => + DateTime.TryParseExact(s.ToString(), format.ToString(), provider, styles, out result); #endif #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs b/src/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs index 6df31411..d2ba635f 100644 --- a/src/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs +++ b/src/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs @@ -13,6 +13,9 @@ namespace System.Diagnostics; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(System.AttributeTargets.Method)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerdisableuserunhandledexceptionsattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/DelegatePolyfill.cs b/src/Polyfill/DelegatePolyfill.cs index ecf4237b..d9b84ac3 100644 --- a/src/Polyfill/DelegatePolyfill.cs +++ b/src/Polyfill/DelegatePolyfill.cs @@ -1,32 +1,17 @@ // #pragma warning disable +#if !NET9_0_OR_GREATER + namespace Polyfills; using System; using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class DelegatePolyfill +static partial class Polyfill { - /// - /// Gets an enumerator for the invocation targets of this delegate. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0 -#if NET9_0_OR_GREATER - public static Delegate.InvocationListEnumerator EnumerateInvocationList(TDelegate? target) where TDelegate : Delegate => - Delegate.EnumerateInvocationList(target); -#else - public static InvocationListEnumerator EnumerateInvocationList(TDelegate? target) - where TDelegate : Delegate => - new(target); +#if !NET9_0_OR_GREATER /// /// Provides an enumerator for the invocation list of a delegate. @@ -63,6 +48,27 @@ public bool MoveNext() [EditorBrowsable(EditorBrowsableState.Never)] public InvocationListEnumerator GetEnumerator() => this; } -#endif -} \ No newline at end of file + extension(Delegate) + { + /// + /// Gets an enumerator for the invocation targets of this delegate. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist?view=net-10.0 + public static InvocationListEnumerator EnumerateInvocationList(TDelegate? target) + where TDelegate : Delegate => + new(target); + } + + extension(Delegate target) + { + /// + /// Gets a value that indicates whether the Delegate has a single invocation target. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0 + public bool HasSingleTarget => target.GetInvocationList().Length == 1; + } + +#endif +} +#endif \ No newline at end of file diff --git a/src/Polyfill/DisableRuntimeMarshallingAttribute.cs b/src/Polyfill/DisableRuntimeMarshallingAttribute.cs index 36919285..d02d0aa5 100644 --- a/src/Polyfill/DisableRuntimeMarshallingAttribute.cs +++ b/src/Polyfill/DisableRuntimeMarshallingAttribute.cs @@ -15,6 +15,9 @@ namespace System.Runtime.CompilerServices; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Assembly)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.disableruntimemarshallingattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/EmbeddedAttribute.cs b/src/Polyfill/EmbeddedAttribute.cs new file mode 100644 index 00000000..e4878257 --- /dev/null +++ b/src/Polyfill/EmbeddedAttribute.cs @@ -0,0 +1,16 @@ +// +#pragma warning disable + +#if PolyUseEmbeddedAttribute + +#if PolyPublic +#error PolyPublic should not be used with PolyUseEmbeddedAttribute. +#endif + +namespace Microsoft.CodeAnalysis +{ + internal sealed partial class EmbeddedAttribute : global::System.Attribute + { + } +} +#endif diff --git a/src/Polyfill/Guard/Guard.cs b/src/Polyfill/Ensure/Ensure.cs similarity index 69% rename from src/Polyfill/Guard/Guard.cs rename to src/Polyfill/Ensure/Ensure.cs index c2e15bd6..e413164d 100644 --- a/src/Polyfill/Guard/Guard.cs +++ b/src/Polyfill/Ensure/Ensure.cs @@ -14,26 +14,29 @@ namespace Polyfills; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [StackTraceHidden] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif -static partial class Guard +static partial class Ensure { - public static void FileExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + public static void FileExists(string path, [CallerArgumentExpression("path")] string name = "") { - NotNullOrEmpty(path, argumentName); + NotNullOrEmpty(path, name); if (!File.Exists(path)) { - throw new ArgumentException($"File not found. Path: {path}", argumentName); + throw new ArgumentException($"File not found. Path: {path}", name); } } - public static void DirectoryExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + public static void DirectoryExists(string path, [CallerArgumentExpression("path")] string name = "") { - NotNullOrEmpty(path, argumentName); + NotNullOrEmpty(path, name); if (!Directory.Exists(path)) { - throw new ArgumentException($"Directory not found. Path: {path}", argumentName); + throw new ArgumentException($"Directory not found. Path: {path}", name); } } } \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_Equal.cs b/src/Polyfill/Ensure/Ensure_Equal.cs new file mode 100644 index 00000000..7afbe4fe --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_Equal.cs @@ -0,0 +1,33 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + /// Throws an if is not equal to . + /// The argument to validate as equal to . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T Equal(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + { + if (EqualityComparer.Default.Equals(value, other)) + { + return value; + } + + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{(object?) value ?? "null"}') must be equal to '{(object?) other ?? "null"}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Guard/Guard_NotEmpty.cs b/src/Polyfill/Ensure/Ensure_NotEmpty.cs similarity index 59% rename from src/Polyfill/Guard/Guard_NotEmpty.cs rename to src/Polyfill/Ensure/Ensure_NotEmpty.cs index 8bfb05ae..d550b694 100644 --- a/src/Polyfill/Guard/Guard_NotEmpty.cs +++ b/src/Polyfill/Ensure/Ensure_NotEmpty.cs @@ -12,116 +12,132 @@ namespace Polyfills; #if PolyPublic public #endif - -static partial class Guard +static partial class Ensure { - public static void NotEmpty(string? value, [CallerArgumentExpression("value")] string argumentName = "") + [return: NotNullIfNotNull(nameof(value))] + public static string? NotEmpty(string? value, [CallerArgumentExpression("value")] string name = "") { if (value is null) { - return; + return value; } #if NET7_0_OR_GREATER - ArgumentException.ThrowIfNullOrEmpty(value, argumentName); + ArgumentException.ThrowIfNullOrEmpty(value, name); #else if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } #endif + return value; } #if FeatureMemory - public static void NotEmpty(ReadOnlySpan value, [CallerArgumentExpression("value")] string argumentName = "") + public static ReadOnlySpan NotEmpty(ReadOnlySpan value, [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } - public static void NotEmpty(Span value, [CallerArgumentExpression("value")] string argumentName = "") + public static Span NotEmpty(Span value, [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } - public static void NotEmpty(Memory? value, [CallerArgumentExpression("value")] string argumentName = "") + [return: NotNullIfNotNull(nameof(value))] + public static Memory? NotEmpty(Memory? value, [CallerArgumentExpression("value")] string name = "") { if (value is null) { - return; + return value; } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } - public static void NotEmpty(Memory value, [CallerArgumentExpression("value")] string argumentName = "") + public static Memory NotEmpty(Memory value, [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } - public static void NotEmpty(ReadOnlyMemory? value, [CallerArgumentExpression("value")] string argumentName = "") + [return: NotNullIfNotNull(nameof(value))] + public static ReadOnlyMemory? NotEmpty(ReadOnlyMemory? value, [CallerArgumentExpression("value")] string name = "") { if (value is null) { - return; + return value; } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } - public static void NotEmpty(ReadOnlyMemory value, [CallerArgumentExpression("value")] string argumentName = "") + public static ReadOnlyMemory NotEmpty(ReadOnlyMemory value, [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } + + return value; } #endif - public static void NotEmpty( - [NotNull] T? value, - [CallerArgumentExpression("value")] string argumentName = "") + [return: NotNullIfNotNull(nameof(value))] + public static T? NotEmpty( + T? value, + [CallerArgumentExpression("value")] string name = "") where T : IEnumerable { if (value is null) { - return; + return value; } if (value is ICollection {Count: 0}) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } if (value is ICollection {Count: 0}) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } if (value is IReadOnlyCollection {Count: 0}) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } if (value is T[] {Length: 0}) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } var enumerator = value.GetEnumerator(); @@ -129,7 +145,7 @@ public static void NotEmpty( { if (!enumerator.MoveNext()) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } } finally @@ -139,5 +155,7 @@ public static void NotEmpty( disposable.Dispose(); } } + + return value; } } \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotEqual.cs b/src/Polyfill/Ensure/Ensure_NotEqual.cs new file mode 100644 index 00000000..84d4e905 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotEqual.cs @@ -0,0 +1,34 @@ +// + + +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif +static partial class Ensure +{ + /// Throws an if is equal to . + /// The argument to validate as not equal to . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T NotEqual(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + { + if (!EqualityComparer.Default.Equals(value, other)) + { + return value; + } + + throw new ArgumentOutOfRangeException( + name, + value, + $"{name} ('{(object?) value ?? "null"}') must not be equal to '{(object?) other ?? "null"}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotGreater.cs b/src/Polyfill/Ensure/Ensure_NotGreater.cs new file mode 100644 index 00000000..e27035d6 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotGreater.cs @@ -0,0 +1,32 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + /// Throws an if is greater than . + /// The argument to validate as less or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T NotGreaterThan(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + where T : IComparable + { + if (value.CompareTo(other) <= 0) + { + return value; + } + + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be less than or equal to '{other}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotGreaterThanOrEqual.cs b/src/Polyfill/Ensure/Ensure_NotGreaterThanOrEqual.cs new file mode 100644 index 00000000..b9eb29f3 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotGreaterThanOrEqual.cs @@ -0,0 +1,32 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + /// Throws an if is greater than or equal . + /// The argument to validate as less than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T NotGreaterThanOrEqual(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + where T : IComparable + { + if (value.CompareTo(other) < 0) + { + return value; + } + + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be less than '{other}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotLessThan.cs b/src/Polyfill/Ensure/Ensure_NotLessThan.cs new file mode 100644 index 00000000..b9405f72 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotLessThan.cs @@ -0,0 +1,32 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + /// Throws an if is less than . + /// The argument to validate as greater than or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T NotLessThan(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + where T : IComparable + { + if (value.CompareTo(other) >= 0) + { + return value; + } + + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be greater than or equal to '{other}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotLessThanOrEqual.cs b/src/Polyfill/Ensure/Ensure_NotLessThanOrEqual.cs new file mode 100644 index 00000000..e81c4529 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotLessThanOrEqual.cs @@ -0,0 +1,32 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + /// Throws an if is less than or equal . + /// The argument to validate as greater than than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static T NotLessThanOrEqual(T value, T other, [CallerArgumentExpression(nameof(value))] string? name = null) + where T : IComparable + { + if (value.CompareTo(other) > 0) + { + return value; + } + + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be greater than '{other}'."); + } +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotNegative.cs b/src/Polyfill/Ensure/Ensure_NotNegative.cs new file mode 100644 index 00000000..9b38b891 --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotNegative.cs @@ -0,0 +1,47 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + [DoesNotReturn] + static void ThrowNegative(T value, string? name) => + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be a non-negative value."); + + /// Throws an if is negative. + /// The argument to validate as non-negative. + /// The name of the parameter with which corresponds. + public static T NotNegative(T value, [CallerArgumentExpression(nameof(value))] string? name = null) +#if NET7_0_OR_GREATER + where T : INumberBase + { + if (T.IsNegative(value)) + { + ThrowNegative(value, name); + } + + return value; + } +#else + where T : struct, IComparable + { + if (value.CompareTo(default(T)) < 0) + { + ThrowNegative(value, name); + } + + return value; + } +#endif +} \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotNegativeOrZero.cs b/src/Polyfill/Ensure/Ensure_NotNegativeOrZero.cs new file mode 100644 index 00000000..58bd4a1c --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotNegativeOrZero.cs @@ -0,0 +1,47 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + [DoesNotReturn] + static void ThrowNegativeOrZero(T value, string? name) => + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be a non-negative and non-zero value."); + + /// Throws an if is negative or zero. + /// The argument to validate as non-zero or non-negative. + /// The name of the parameter with which corresponds. + public static T NotNegativeOrZero(T value, [CallerArgumentExpression(nameof(value))] string? name = null) +#if NET7_0_OR_GREATER + where T : INumberBase + { + if (T.IsNegative(value) || T.IsZero(value)) + { + ThrowNegativeOrZero(value, name); + } + + return value; + } +#else + where T : struct, IComparable + { + if (value.CompareTo(default(T)) <= 0) + { + ThrowNegativeOrZero(value, name); + } + + return value; + } +#endif +} \ No newline at end of file diff --git a/src/Polyfill/Guard/Guard_NotNull.cs b/src/Polyfill/Ensure/Ensure_NotNull.cs similarity index 96% rename from src/Polyfill/Guard/Guard_NotNull.cs rename to src/Polyfill/Ensure/Ensure_NotNull.cs index 2f380c3a..a1995bfc 100644 --- a/src/Polyfill/Guard/Guard_NotNull.cs +++ b/src/Polyfill/Ensure/Ensure_NotNull.cs @@ -10,7 +10,7 @@ namespace Polyfills; #if PolyPublic public #endif -static partial class Guard +static partial class Ensure { public static T NotNull( [NotNull] T? argument, diff --git a/src/Polyfill/Guard/Guard_NotNullOrEmpty.cs b/src/Polyfill/Ensure/Ensure_NotNullOrEmpty.cs similarity index 71% rename from src/Polyfill/Guard/Guard_NotNullOrEmpty.cs rename to src/Polyfill/Ensure/Ensure_NotNullOrEmpty.cs index c50f2b1f..2e659c28 100644 --- a/src/Polyfill/Guard/Guard_NotNullOrEmpty.cs +++ b/src/Polyfill/Ensure/Ensure_NotNullOrEmpty.cs @@ -12,24 +12,24 @@ namespace Polyfills; public #endif -static partial class Guard +static partial class Ensure { public static string NotNullOrEmpty( [NotNull] string? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { #if NET7_0_OR_GREATER - ArgumentException.ThrowIfNullOrEmpty(value, argumentName); + ArgumentException.ThrowIfNullOrEmpty(value, name); return value; #else if (value is null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } return value; @@ -38,12 +38,12 @@ public static string NotNullOrEmpty( public static T NotNullOrEmpty( [NotNull] T? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") where T : IEnumerable { if (value is null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } NotEmpty(value); @@ -55,16 +55,16 @@ public static T NotNullOrEmpty( #if FeatureMemory public static Memory NotNullOrEmpty( [NotNull] Memory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) @@ -75,21 +75,21 @@ public static Memory NotNullOrEmpty( } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } public static ReadOnlyMemory NotNullOrEmpty( [NotNull] ReadOnlyMemory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) @@ -100,7 +100,7 @@ public static ReadOnlyMemory NotNullOrEmpty( } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } #endif } \ No newline at end of file diff --git a/src/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs b/src/Polyfill/Ensure/Ensure_NotNullOrWhiteSpace.cs similarity index 74% rename from src/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs rename to src/Polyfill/Ensure/Ensure_NotNullOrWhiteSpace.cs index fc934f6b..047f50bf 100644 --- a/src/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs +++ b/src/Polyfill/Ensure/Ensure_NotNullOrWhiteSpace.cs @@ -11,24 +11,24 @@ namespace Polyfills; public #endif -static partial class Guard +static partial class Ensure { public static string NotNullOrWhiteSpace( [NotNull] string? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { #if NET8_0_OR_GREATER - ArgumentException.ThrowIfNullOrWhiteSpace(value, argumentName); + ArgumentException.ThrowIfNullOrWhiteSpace(value, name); return value; #else if (value == null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value) @@ -39,23 +39,23 @@ public static string NotNullOrWhiteSpace( } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); #endif } #if FeatureMemory public static Memory NotNullOrWhiteSpace( [NotNull] Memory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) @@ -66,21 +66,21 @@ public static Memory NotNullOrWhiteSpace( } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } public static ReadOnlyMemory NotNullOrWhiteSpace( [NotNull] ReadOnlyMemory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - throw new ArgumentNullException(argumentName); + throw new ArgumentNullException(name); } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) @@ -91,7 +91,7 @@ public static ReadOnlyMemory NotNullOrWhiteSpace( } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } #endif } \ No newline at end of file diff --git a/src/Polyfill/Guard/Guard_NotWhiteSpace.cs b/src/Polyfill/Ensure/Ensure_NotWhiteSpace.cs similarity index 63% rename from src/Polyfill/Guard/Guard_NotWhiteSpace.cs rename to src/Polyfill/Ensure/Ensure_NotWhiteSpace.cs index 40068526..e2737590 100644 --- a/src/Polyfill/Guard/Guard_NotWhiteSpace.cs +++ b/src/Polyfill/Ensure/Ensure_NotWhiteSpace.cs @@ -1,4 +1,7 @@ // + +using System.Diagnostics.CodeAnalysis; + #pragma warning disable namespace Polyfills; @@ -10,126 +13,131 @@ namespace Polyfills; public #endif -static partial class Guard +static partial class Ensure { - public static void NotWhiteSpace( + [return: NotNullIfNotNull(nameof(value))] + public static string? NotWhiteSpace( string? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - return; + return value; } + #if NET8_0_OR_GREATER - ArgumentException.ThrowIfNullOrWhiteSpace(value, argumentName); + ArgumentException.ThrowIfNullOrWhiteSpace(value, name); + return value; #else if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value) { if (!char.IsWhiteSpace(ch)) { - return; + return value; } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); #endif } #if FeatureMemory - public static void NotWhiteSpace( + public static ReadOnlySpan NotWhiteSpace( ReadOnlySpan value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value) { if (!char.IsWhiteSpace(ch)) { - return; + return value; } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } - public static void NotWhiteSpace( + [return: NotNullIfNotNull(nameof(value))] + public static Memory? NotWhiteSpace( Memory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - return; + return value; } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) { if (!char.IsWhiteSpace(ch)) { - return; + return value; } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } - public static void NotWhiteSpace( + [return: NotNullIfNotNull(nameof(value))] + public static ReadOnlyMemory? NotWhiteSpace( ReadOnlyMemory? value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value == null) { - return; + return value; } if (value.Value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value.Value.Span) { if (!char.IsWhiteSpace(ch)) { - return; + return value; } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } - public static void NotWhiteSpace( + public static Span NotWhiteSpace( Span value, - [CallerArgumentExpression("value")] string argumentName = "") + [CallerArgumentExpression("value")] string name = "") { if (value.Length == 0) { - throw new ArgumentException("Argument cannot be empty.", argumentName); + throw new ArgumentException("Argument cannot be empty.", name); } foreach (var ch in value) { if (!char.IsWhiteSpace(ch)) { - return; + return value; } } - throw new ArgumentException("Argument cannot be whitespace.", argumentName); + throw new ArgumentException("Argument cannot be whitespace.", name); } #endif } \ No newline at end of file diff --git a/src/Polyfill/Ensure/Ensure_NotZero.cs b/src/Polyfill/Ensure/Ensure_NotZero.cs new file mode 100644 index 00000000..95b1f2cc --- /dev/null +++ b/src/Polyfill/Ensure/Ensure_NotZero.cs @@ -0,0 +1,47 @@ +// + +#pragma warning disable + +namespace Polyfills; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Ensure +{ + [DoesNotReturn] + static void ThrowZero(T value, string? name) => + throw new ArgumentOutOfRangeException(name, value, $"{name} ('{value}') must be a non-zero value."); + + /// Throws an if is zero. + /// The argument to validate as non-zero. + /// The name of the parameter with which corresponds. + public static T NotZero(T value, [CallerArgumentExpression(nameof(value))] string? name = null) +#if NET7_0_OR_GREATER + where T : INumberBase + { + if (T.IsZero(value)) + { + ThrowZero(value, name); + } + + return value; + } +#else + where T : struct, IComparable + { + if (value.CompareTo(default(T)) == 0) + { + ThrowZero(value, name); + } + + return value; + } +#endif +} \ No newline at end of file diff --git a/src/Polyfill/EnumPolyfill.cs b/src/Polyfill/EnumPolyfill.cs index 8e26f987..385b3266 100644 --- a/src/Polyfill/EnumPolyfill.cs +++ b/src/Polyfill/EnumPolyfill.cs @@ -1,167 +1,142 @@ // #pragma warning disable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class EnumPolyfill +static partial class Polyfill { - /// - /// Retrieves an array of the values of the constants in a specified enumeration type. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0 - public static TEnum[] GetValues() - where TEnum : struct, Enum + extension(Enum) { -#if NET - return Enum.GetValues(); -#else - var values = Enum.GetValues(typeof(TEnum)); - var result = new TEnum[values.Length]; - Array.Copy(values, result, values.Length); - return result; -#endif - } - - /// Returns a telling whether a given integral value exists in a specified enumeration. - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0) - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsDefined (TEnum value) - where TEnum : struct, Enum => -#if NET - Enum.IsDefined(value); -#else - Enum.IsDefined(typeof(TEnum), value); -#endif +#if !NET + + /// + /// Retrieves an array of the values of the constants in a specified enumeration type. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-10.0 + public static TEnum[] GetValues() + where TEnum : struct, Enum + { + var values = Enum.GetValues(typeof(TEnum)); + var result = new TEnum[values.Length]; + Array.Copy(values, result, values.Length); + return result; + } - /// - /// Retrieves an array of the names of the constants in a specified enumeration type. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0 - public static string[] GetNames() - where TEnum : struct, Enum => -#if NET - Enum.GetNames(); -#else - Enum.GetNames(typeof(TEnum)); -#endif + /// Returns a telling whether a given integral value exists in a specified enumeration. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=net-10.0#system-enum-isdefined-1(-0) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsDefined(TEnum value) + where TEnum : struct, Enum => + Enum.IsDefined(typeof(TEnum), value); + + /// + /// Retrieves an array of the names of the constants in a specified enumeration type. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-10.0 + public static string[] GetNames() + where TEnum : struct, Enum => + Enum.GetNames(typeof(TEnum)); - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean) - public static TEnum Parse(string value) - where TEnum : struct, Enum => -#if NETFRAMEWORK || NETSTANDARD - (TEnum)Enum.Parse(typeof(TEnum), value); -#else - Enum.Parse(value); #endif - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean) - public static TEnum Parse(string value, bool ignoreCase) - where TEnum : struct, Enum => #if NETFRAMEWORK || NETSTANDARD - (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase); -#else - Enum.Parse(value, ignoreCase); -#endif -#if FeatureMemory + /// + /// Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean) + public static TEnum Parse(string value) + where TEnum : struct, Enum => + (TEnum) Enum.Parse(typeof(TEnum), value); + + /// + /// Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-string-system-boolean) + public static TEnum Parse(string value, bool ignoreCase) + where TEnum : struct, Enum => + (TEnum) Enum.Parse(typeof(TEnum), value, ignoreCase); - /// - /// Converts the span of characters representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))) - public static TEnum Parse(ReadOnlySpan value) - where TEnum : struct, Enum => -#if NET6_0_OR_GREATER - Enum.Parse(value); -#else - (TEnum)Enum.Parse(typeof(TEnum), value.ToString()); #endif - /// - /// Converts the span of characters representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean) - public static TEnum Parse(ReadOnlySpan value, bool ignoreCase) - where TEnum : struct, Enum => -#if NET6_0_OR_GREATER - Enum.Parse(value, ignoreCase); -#else - (TEnum)Enum.Parse(typeof(TEnum), value.ToString(), ignoreCase); -#endif +#if FeatureMemory - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@) - public static bool TryParse(ReadOnlySpan value, out TEnum result) - where TEnum : struct, Enum => -#if NET6_0_OR_GREATER - Enum.TryParse(value, out result); -#else - Enum.TryParse(value.ToString(), out result); -#endif +#if !NET6_0_OR_GREATER + + /// + /// Converts the span of characters representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))) + public static TEnum Parse(ReadOnlySpan value) + where TEnum : struct, Enum => + (TEnum)Enum.Parse(typeof(TEnum), value.ToString()); + + /// + /// Converts the span of characters representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-10.0#system-enum-parse-1(system-readonlyspan((system-char))-system-boolean) + public static TEnum Parse(ReadOnlySpan value, bool ignoreCase) + where TEnum : struct, Enum => + (TEnum)Enum.Parse(typeof(TEnum), value.ToString(), ignoreCase); + + /// + /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-0@) + public static bool TryParse(ReadOnlySpan value, out TEnum result) + where TEnum : struct, Enum => + Enum.TryParse(value.ToString(), out result); + + /// + /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@) + public static bool TryParse(ReadOnlySpan value, bool ignoreCase, out TEnum result) + where TEnum : struct, Enum => + Enum.TryParse(value.ToString(), ignoreCase, out result); - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=net-10.0#system-enum-tryparse-1(system-readonlyspan((system-char))-system-boolean-0@) - public static bool TryParse(ReadOnlySpan value, bool ignoreCase, out TEnum result) - where TEnum : struct, Enum => -#if NET6_0_OR_GREATER - Enum.TryParse(value, ignoreCase, out result); -#else - Enum.TryParse(value.ToString(), ignoreCase, out result); #endif - /// - /// Tries to format the value of the enumerated type instance into the provided span of characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0 - public static bool TryFormat(TEnum value, Span destination, out int charsWritten, ReadOnlySpan format = default) - where TEnum : struct, Enum => -#if NET8_0_OR_GREATER - Enum.TryFormat(value, destination, out charsWritten, format); -#else - TryFormatUnconstrained(value, destination, out charsWritten, format); -#endif +#if !NET8_0_OR_GREATER - internal static bool TryFormatUnconstrained(object value, Span destination, out int charsWritten, ReadOnlySpan format = default) - { - string result; - if (format.Length == 0) - { - result = value.ToString()!; - } - else - { - result = Enum.Format(value.GetType(), value, format.ToString()); - } + /// + /// Tries to format the value of the enumerated type instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryformat?view=net-10.0 + public static bool TryFormat(TEnum value, Span destination, out int charsWritten, ReadOnlySpan format = default) + where TEnum : struct, Enum => + TryFormatUnconstrained(value, destination, out charsWritten, format); - if (result.Length > destination.Length) + internal static bool TryFormatUnconstrained(object value, Span destination, out int charsWritten, ReadOnlySpan format = default) { - charsWritten = 0; - return false; + string result; + if (format.Length == 0) + { + result = value.ToString()!; + } + else + { + result = Enum.Format(value.GetType(), value, format.ToString()); + } + + if (result.Length > destination.Length) + { + charsWritten = 0; + return false; + } + + charsWritten = result.Length; + result.CopyTo(destination); + return true; } - charsWritten = result.Length; - result.CopyTo(destination); - return true; - } #endif -} \ No newline at end of file +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/EnumerablePolyfill.cs b/src/Polyfill/EnumerablePolyfill.cs new file mode 100644 index 00000000..1e41a244 --- /dev/null +++ b/src/Polyfill/EnumerablePolyfill.cs @@ -0,0 +1,108 @@ +// +#pragma warning disable + +#if NET7_0_OR_GREATER && !NET10_0_OR_GREATER +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Linq; + +static partial class Polyfill +{ + extension(Enumerable) + { + /// + /// + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.infinitesequence?view=net-10.0 + public static IEnumerable InfiniteSequence(T start, T step) + where T : IAdditionOperators + { + while (true) + { + yield return start; + start += step; + } + } + + /// + /// + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequence?view=net-10.0 + public static IEnumerable Sequence(T start, T endInclusive, T step) + where T : INumber + { + if (T.IsPositive(step)) + { + // Presumed to be the most common case, step > 0. Validate that endInclusive >= start, as otherwise we can't easily + // guarantee that the sequence will terminate. + if (endInclusive < start) + { + throw new ArgumentOutOfRangeException("endInclusive < start"); + } + + return IncrementingIterator(start, endInclusive, step); + } + else + { + // step < 0. Validate that endInclusive <= start, as otherwise we can't easily guarantee that the sequence will terminate. + if (endInclusive > start) + { + throw new ArgumentOutOfRangeException("endInclusive > start"); + } + + return DecrementingIterator(start, endInclusive, step); + } + + static IEnumerable IncrementingIterator(T current, T endInclusive, T step) + { + yield return current; + + while (true) + { + T next = current + step; + // handle overflow and saturation + if (next >= endInclusive || next <= current) + { + if (next == endInclusive && current != next) + { + yield return next; + } + + yield break; + } + + yield return next; + current = next; + } + } + + static IEnumerable DecrementingIterator(T current, T endInclusive, T step) + { + yield return current; + + while (true) + { + T next = current + step; + // handle overflow and saturation + if (next <= endInclusive || next >= current) + { + if (next == endInclusive && current != next) + { + yield return next; + } + + yield break; + } + + yield return next; + current = next; + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/src/Polyfill/EnvironmentPolyfill.cs b/src/Polyfill/EnvironmentPolyfill.cs new file mode 100644 index 00000000..34ef8fdb --- /dev/null +++ b/src/Polyfill/EnvironmentPolyfill.cs @@ -0,0 +1,36 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Diagnostics; + +static partial class Polyfill +{ + static int processId; + + extension(Environment) + { + /// + /// Gets the unique identifier for the current process. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.environment.processid?view=net-10.0#system-environment-processid + public static int ProcessId + { + get + { + if (processId == 0) + { + using var process = Process.GetCurrentProcess(); + processId = process.Id; + } + + return processId; + } + } + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/ExperimentalAttribute.cs b/src/Polyfill/ExperimentalAttribute.cs index a1734b6a..9a827353 100644 --- a/src/Polyfill/ExperimentalAttribute.cs +++ b/src/Polyfill/ExperimentalAttribute.cs @@ -29,6 +29,9 @@ namespace System.Diagnostics.CodeAnalysis; AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.experimentalattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/FeatureGuardAttribute.cs b/src/Polyfill/FeatureGuardAttribute.cs index fc026f9b..99bf7e6d 100644 --- a/src/Polyfill/FeatureGuardAttribute.cs +++ b/src/Polyfill/FeatureGuardAttribute.cs @@ -14,6 +14,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.featureguardattribute #if PolyPublic public diff --git a/src/Polyfill/FeatureSwitchDefinitionAttribute.cs b/src/Polyfill/FeatureSwitchDefinitionAttribute.cs index 54f5bfa1..515738a8 100644 --- a/src/Polyfill/FeatureSwitchDefinitionAttribute.cs +++ b/src/Polyfill/FeatureSwitchDefinitionAttribute.cs @@ -13,6 +13,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.featureswitchdefinitionattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/FilePolyfill.cs b/src/Polyfill/FilePolyfill.cs index 5050a8cc..f5257ad6 100644 --- a/src/Polyfill/FilePolyfill.cs +++ b/src/Polyfill/FilePolyfill.cs @@ -1,7 +1,7 @@ // - #pragma warning disable +#if !NET9_0_OR_GREATER namespace Polyfills; using System; @@ -9,474 +9,373 @@ namespace Polyfills; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; -using System.Diagnostics; using System.Threading; -using System.Runtime.InteropServices; -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class FilePolyfill +static partial class Polyfill { - /// - /// Appends the specified byte array to the end of the file at the given path. - /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte()) - public static void AppendAllBytes(string path, byte[] bytes) - { -#if NET9_0_OR_GREATER - File.AppendAllBytes(path, bytes); -#else - using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); - stream.Write(bytes, 0, bytes.Length); -#endif - } - -#if FeatureMemory - /// - /// Appends the specified byte array to the end of the file at the given path. - /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte))) - public static void AppendAllBytes(string path, ReadOnlySpan bytes) - { -#if NET9_0_OR_GREATER - File.AppendAllBytes(path, bytes); -#else - using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); - stream.Write(bytes.ToArray(), 0, bytes.Length); -#endif - } -#endif - - /// - /// Asynchronously appends the specified byte array to the end of the file at the given path. - /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken) -#if NET9_0_OR_GREATER - public static Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) - => File.AppendAllBytesAsync(path, bytes, cancellationToken); -#else - public static async Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + extension(File) { - using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); - await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken); - } -#endif - - /// - /// Moves a specified file to a new location, providing the options to specify a new file name and to replace the destination file if it already exists. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0 - public static void Move(string sourceFileName, string destFileName, bool overwrite) - { - sourceFileName = Path.GetFullPath(sourceFileName); - destFileName = Path.GetFullPath(destFileName); - if (sourceFileName == destFileName) +#if !NET9_0_OR_GREATER + + /// + /// Appends the specified byte array to the end of the file at the given path. + /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-byte()) + public static void AppendAllBytes(string path, byte[] bytes) { - return; + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); + stream.Write(bytes, 0, bytes.Length); } -#if NETCOREAPP3_0_OR_GREATER - File.Move(sourceFileName, destFileName, overwrite: overwrite); -#else - if (overwrite) - { - File.Copy(sourceFileName, destFileName, overwrite: true); - File.Delete(sourceFileName); - } - else + /// + /// Asynchronously appends the specified byte array to the end of the file at the given path. + /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-byte()-system-threading-cancellationtoken) + public static async Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) { - File.Move(sourceFileName, destFileName); + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); + await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken); } -#endif - } -#if FeatureMemory - /// - /// Asynchronously appends the specified byte array to the end of the file at the given path. - /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken) - public static Task AppendAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) => -#if NET9_0_OR_GREATER - File.AppendAllBytesAsync(path, bytes, cancellationToken); -#else - AppendAllBytesAsync(path, bytes.ToArray(), cancellationToken); -#endif #endif - /// - /// Asynchronously appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken) - public static Task AppendAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => -#if NETCOREAPP || NETSTANDARD2_1 - File.AppendAllLinesAsync(path, contents, cancellationToken); -#else - AppendAllLinesAsync(path, contents, Encoding.UTF8, cancellationToken); -#endif - - /// - /// Asynchronously appends lines to a file by using a specified encoding, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken) -#if NETCOREAPP || NETSTANDARD2_1 - public static Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) - => File.AppendAllLinesAsync(path, contents, encoding, cancellationToken); -#else - public static async Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); - using var writer = new StreamWriter(stream, encoding); +#if FeatureMemory - foreach (var content in contents) +#if !NET9_0_OR_GREATER + + /// + /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file using the specified encoding, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken) + public static Task AppendAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, CancellationToken cancellationToken = default) => + File.AppendAllTextAsync(path, contents.ToString(), encoding, cancellationToken); + + /// + /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken) + public static Task AppendAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) => + File.AppendAllTextAsync(path, contents.ToString(), cancellationToken); + + /// + /// Appends the specified string to the file, creating the file if it does not already exist. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))) + public static void AppendAllText(string path, ReadOnlySpan contents) => + File.AppendAllText(path, contents.ToString()); + + /// + /// Appends the specified string to the file, creating the file if it does not already exist. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding) + public static void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding) => + File.AppendAllText(path, contents.ToString(), encoding); + + /// + /// Appends the specified byte array to the end of the file at the given path. + /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytes?view=net-10.0#system-io-file-appendallbytes(system-string-system-readonlyspan((system-byte))) + public static void AppendAllBytes(string path, ReadOnlySpan bytes) { - cancellationToken.ThrowIfCancellationRequested(); - await writer.WriteLineAsync(content); + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); + stream.Write(bytes.ToArray(), 0, bytes.Length); } - await writer.FlushAsync(cancellationToken); - } -#endif - -#if FeatureMemory - /// - /// Appends the specified string to the file, creating the file if it does not already exist. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))) - public static void AppendAllText(string path, ReadOnlySpan contents) => -#if NET9_0_OR_GREATER - File.AppendAllText(path, contents); -#else - File.AppendAllText(path, contents.ToString()); -#endif + /// + /// Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken) + public static Task WriteAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) => + WriteAllBytesAsync(path, bytes.ToArray(), cancellationToken); + + /// + /// Creates a new file, writes the specified string to the file, and then closes the file. + /// If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))) + public static void WriteAllText(string path, ReadOnlySpan contents) => + File.WriteAllText(path, contents.ToString()); + + /// + /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. + /// If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding) + public static void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding) => + File.WriteAllText(path, contents.ToString(), encoding); + + /// + /// Asynchronously appends the specified byte array to the end of the file at the given path. + /// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken) + public static Task AppendAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) => + AppendAllBytesAsync(path, bytes.ToArray(), cancellationToken); + +#endif + +#endif + + /// + /// Moves a specified file to a new location, providing the options to specify a new file name and to replace the destination file if it already exists. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?system-io-file-move(system-string-system-string-system-boolean)?view=net-10.0 + public static void Move(string sourceFileName, string destFileName, bool overwrite) + { + sourceFileName = Path.GetFullPath(sourceFileName); + destFileName = Path.GetFullPath(destFileName); + if (sourceFileName == destFileName) + { + return; + } - /// - /// Appends the specified string to the file, creating the file if it does not already exist. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-10.0#system-io-file-appendalltext(system-string-system-readonlyspan((system-char))-system-text-encoding) - public static void AppendAllText(string path, ReadOnlySpan contents, Encoding encoding) => -#if NET9_0_OR_GREATER - File.AppendAllText(path, contents, encoding); +#if NETCOREAPP3_0_OR_GREATER + File.Move(sourceFileName, destFileName, overwrite: overwrite); #else - File.AppendAllText(path, contents.ToString(), encoding); -#endif + if (overwrite) + { + File.Copy(sourceFileName, destFileName, overwrite: true); + File.Delete(sourceFileName); + } + else + { + File.Move(sourceFileName, destFileName); + } #endif + } - /// - /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file using the specified encoding, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) -#if NETFRAMEWORK || NETSTANDARD2_0 - public static async Task AppendAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); - using var writer = new StreamWriter(stream, encoding); - - await writer.WriteAsync(contents); +#if !NETCOREAPP && !NETSTANDARD2_1 - await writer.FlushAsync(cancellationToken); - } -#else - public static Task AppendAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) - => File.AppendAllTextAsync(path, contents, encoding, cancellationToken); -#endif + /// + /// Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken) + public static async Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) + { + using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); + await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken); + } - /// - /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken) - public static Task AppendAllTextAsync(string path, string? contents, CancellationToken cancellationToken = default) => -#if NETFRAMEWORK || NETSTANDARD2_0 - AppendAllTextAsync(path, contents, Encoding.UTF8, cancellationToken); -#else - File.AppendAllTextAsync(path, contents, cancellationToken); -#endif + /// + /// Asynchronously creates a new file, writes the specified lines to the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken) + public static Task WriteAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => + WriteAllLinesAsync(path, contents, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously creates a new file, write the specified lines to the file by using the specified encoding, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken) + public static async Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) + { + using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); + using var writer = new StreamWriter(stream, encoding); -#if FeatureMemory - /// - /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file using the specified encoding, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-text-encoding-system-threading-cancellationtoken) - public static Task AppendAllTextAsync(string path, ReadOnlyMemory contents, Encoding encoding, CancellationToken cancellationToken = default) => -#if NET9_0_OR_GREATER - File.AppendAllTextAsync(path, contents, encoding, cancellationToken); -#else - AppendAllTextAsync(path, contents.ToString(), encoding, cancellationToken); -#endif + foreach (var line in contents) + { + cancellationToken.ThrowIfCancellationRequested(); + await writer.WriteLineAsync(line); + } - /// - /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-readonlymemory((system-char))-system-threading-cancellationtoken) - public static Task AppendAllTextAsync(string path, ReadOnlyMemory contents, CancellationToken cancellationToken = default) => -#if NET9_0_OR_GREATER - File.AppendAllTextAsync(path, contents, cancellationToken); -#else - AppendAllTextAsync(path, contents.ToString(), cancellationToken); -#endif -#endif + await writer.FlushAsync(cancellationToken); + } - /// - /// Asynchronously opens a binary file, reads the contents of the file into a byte array, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0 -#if NETFRAMEWORK || NETSTANDARD2_0 - public static async Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - var length = (int) stream.Length; - var bytes = new byte[length]; - var bytesRead = 0; - while (bytesRead < length) + /// + /// Asynchronously appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken) + public static Task AppendAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => + AppendAllLinesAsync(path, contents, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously appends lines to a file by using a specified encoding, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalllinesasync?view=net-10.0#system-io-file-appendalllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken) + public static async Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) { - var read = await stream.ReadAsync(bytes, bytesRead, length - bytesRead, cancellationToken); - if (read == 0) + cancellationToken.ThrowIfCancellationRequested(); + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); + using var writer = new StreamWriter(stream, encoding); + + foreach (var content in contents) { - throw new EndOfStreamException($"End of stream reached with {length - bytesRead} bytes left to read"); + cancellationToken.ThrowIfCancellationRequested(); + await writer.WriteLineAsync(content); } - bytesRead += read; + await writer.FlushAsync(cancellationToken); } - return bytes; - } -#else - public static Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default) - => File.ReadAllBytesAsync(path, cancellationToken); #endif - /// - /// Asynchronously opens a text file, reads all lines of the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken) - public static Task ReadAllLinesAsync(string path, CancellationToken cancellationToken = default) => #if NETFRAMEWORK || NETSTANDARD2_0 - ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken); -#else - File.ReadAllLinesAsync(path, cancellationToken); -#endif - - /// - /// Asynchronously opens a text file, reads all lines of the file with the specified encoding, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken) -#if NETFRAMEWORK || NETSTANDARD2_0 - public static async Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - { - var lines = new List(); - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + /// + /// Asynchronously creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) + public static async Task WriteAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync(); - if (line != null) + using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); + using var writer = new StreamWriter(stream, encoding); + + if (contents != null) { - lines.Add(line); + await writer.WriteAsync(contents); } - } - return lines.ToArray(); - } -#else - public static Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - => File.ReadAllLinesAsync(path, encoding, cancellationToken); -#endif + await writer.FlushAsync(cancellationToken); + } - /// - /// Asynchronously opens a text file, reads all the text in the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken) - public static Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default) => -#if NETFRAMEWORK || NETSTANDARD2_0 - ReadAllTextAsync(path, Encoding.UTF8, cancellationToken); -#else - File.ReadAllTextAsync(path, cancellationToken); -#endif + /// + /// Asynchronously creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is truncated and overwritten. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) + public static Task WriteAllTextAsync(string path, string? contents, CancellationToken cancellationToken = default) => + WriteAllTextAsync(path, contents, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file using the specified encoding, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) + public static async Task AppendAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None); + using var writer = new StreamWriter(stream, encoding); - /// - /// Asynchronously opens a text file, reads all text in the file with the specified encoding, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken) -#if NETFRAMEWORK || NETSTANDARD2_0 - public static async Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - using var reader = new StreamReader(stream, encoding); - return await reader.ReadToEndAsync(cancellationToken); - } -#else - public static Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - => File.ReadAllTextAsync(path, encoding, cancellationToken); -#endif + await writer.WriteAsync(contents); - //TODO: re add NETSTANDARD via https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces#dependencies-body-tab -#if NETCOREAPP3_0_OR_GREATER // || NETSTANDARD - /// - /// Asynchronously reads the lines of a file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken) - public static IAsyncEnumerable ReadLinesAsync(string path, [EnumeratorCancellation] CancellationToken cancellationToken = default) => -#if NET7_0_OR_GREATER - File.ReadLinesAsync(path, cancellationToken); -#else - ReadLinesAsync(path, Encoding.UTF8, cancellationToken); -#endif + await writer.FlushAsync(cancellationToken); + } - /// - /// Asynchronously reads the lines of a file that has a specified encoding. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken) -#if NET7_0_OR_GREATER - public static IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - => File.ReadLinesAsync(path, encoding, cancellationToken); -#else - public static async IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - using var reader = new StreamReader(stream, encoding); - while (!reader.EndOfStream) + /// + /// Asynchronously opens a file or creates the file if it does not already exist, appends the specified string to the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltextasync?view=net-10.0#system-io-file-appendalltextasync(system-string-system-string-system-threading-cancellationtoken) + public static Task AppendAllTextAsync(string path, string? contents, CancellationToken cancellationToken = default) => + AppendAllTextAsync(path, contents, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously opens a binary file, reads the contents of the file into a byte array, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=net-10.0 + public static async Task ReadAllBytesAsync(string path, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync(); - if (line != null) + #if (NETCOREAPP2_0_OR_GREATER || NETSTANDARD) && FeatureRuntimeInformation + var options = FileOptions.Asynchronous | (OperatingSystem.IsWindows() ? FileOptions.SequentialScan : FileOptions.None); + #else + var options = FileOptions.Asynchronous | FileOptions.SequentialScan; + #endif + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, options); + var length = (int) stream.Length; + var bytes = new byte[length]; + var bytesRead = 0; + while (bytesRead < length) { - yield return line; + var read = await stream.ReadAsync(bytes, bytesRead, length - bytesRead, cancellationToken); + if (read == 0) + { + throw new EndOfStreamException($"End of stream reached with {length - bytesRead} bytes left to read"); + } + + bytesRead += read; } - } - } -#endif -#endif - /// - /// Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytesasync?view=net-10.0#system-io-file-writeallbytesasync(system-string-system-byte()-system-threading-cancellationtoken) -#if NETCOREAPP || NETSTANDARD2_1 - public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) - => File.WriteAllBytesAsync(path, bytes, cancellationToken); -#else - public static async Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken); - } -#endif + return bytes; + } -#if FeatureMemory - /// - /// Asynchronously creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendallbytesasync?view=net-10.0#system-io-file-appendallbytesasync(system-string-system-readonlymemory((system-byte))-system-threading-cancellationtoken) - public static Task WriteAllBytesAsync(string path, ReadOnlyMemory bytes, CancellationToken cancellationToken = default) => -#if NET9_0_OR_GREATER - File.WriteAllBytesAsync (path, bytes, cancellationToken); -#else - WriteAllBytesAsync(path, bytes.ToArray(), cancellationToken); -#endif -#endif + /// + /// Asynchronously opens a text file, reads all lines of the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken) + public static Task ReadAllLinesAsync(string path, CancellationToken cancellationToken = default) => + ReadAllLinesAsync(path, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously opens a text file, reads all lines of the file with the specified encoding, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken) + public static async Task ReadAllLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) + { + var lines = new List(); + using var reader = AsyncStreamReader(path, encoding); - /// - /// Asynchronously creates a new file, writes the specified lines to the file, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-threading-cancellationtoken) - public static Task WriteAllLinesAsync(string path, IEnumerable contents, CancellationToken cancellationToken = default) => -#if NETCOREAPP || NETSTANDARD2_1 - File.WriteAllLinesAsync(path, contents, cancellationToken); -#else - WriteAllLinesAsync(path, contents, Encoding.UTF8, cancellationToken); -#endif + while (!reader.EndOfStream) + { + cancellationToken.ThrowIfCancellationRequested(); + var line = await reader.ReadLineAsync(); + if (line != null) + { + lines.Add(line); + } + } - /// - /// Asynchronously creates a new file, write the specified lines to the file by using the specified encoding, and then closes the file. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllinesasync?view=net-10.0#system-io-file-writealllinesasync(system-string-system-collections-generic-ienumerable((system-string))-system-text-encoding-system-threading-cancellationtoken) -#if NETCOREAPP || NETSTANDARD2_1 - public static Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) - => File.WriteAllLinesAsync(path, contents, encoding, cancellationToken); -#else - public static async Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - using var writer = new StreamWriter(stream, encoding); + return lines.ToArray(); + } - foreach (var line in contents) + /// + /// Asynchronously opens a text file, reads all the text in the file, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-threading-cancellationtoken) + public static Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default) => + ReadAllTextAsync(path, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously opens a text file, reads all text in the file with the specified encoding, and then closes the file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalltextasync?view=net-10.0#system-io-file-readalltextasync(system-string-system-text-encoding-system-threading-cancellationtoken) + public static async Task ReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) { - cancellationToken.ThrowIfCancellationRequested(); - await writer.WriteLineAsync(line); + using var reader = AsyncStreamReader(path, encoding); + return await reader.ReadToEndAsync(cancellationToken); } - await writer.FlushAsync(cancellationToken); - } -#endif - -#if FeatureMemory - /// - /// Creates a new file, writes the specified string to the file, and then closes the file. - /// If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))) - public static void WriteAllText(string path, ReadOnlySpan contents) => -#if NET9_0_OR_GREATER - File.WriteAllText(path, contents); -#else - File.WriteAllText(path, contents.ToString()); -#endif - - /// - /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. - /// If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-10.0#system-io-file-writealltext(system-string-system-readonlyspan((system-char))-system-text-encoding) - public static void WriteAllText(string path, ReadOnlySpan contents, Encoding encoding) => -#if NET9_0_OR_GREATER - File.WriteAllText(path, contents, encoding); -#else - File.WriteAllText(path, contents.ToString(), encoding); -#endif + static StreamReader AsyncStreamReader(string path, Encoding encoding) + { + var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); + return new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); + } #endif - /// - /// Asynchronously creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) -#if NETFRAMEWORK || NETSTANDARD2_0 - public static async Task WriteAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) - { - using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - using var writer = new StreamWriter(stream, encoding); - - if (contents != null) + //TODO: re add NETSTANDARD via https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces#dependencies-body-tab +#if NETCOREAPP3_0_OR_GREATER // || NETSTANDARD +#if !NET7_0_OR_GREATER + /// + /// Asynchronously reads the lines of a file. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-threading-cancellationtoken) + public static IAsyncEnumerable ReadLinesAsync(string path, [EnumeratorCancellation] CancellationToken cancellationToken = default) => + ReadLinesAsync(path, Encoding.UTF8, cancellationToken); + + /// + /// Asynchronously reads the lines of a file that has a specified encoding. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readlinesasync?view=net-10.0#system-io-file-readalllinesasync(system-string-system-text-encoding-system-threading-cancellationtoken) + public static async IAsyncEnumerable ReadLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default) { - await writer.WriteAsync(contents); + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); + using var reader = new StreamReader(stream, encoding); + while (!reader.EndOfStream) + { + cancellationToken.ThrowIfCancellationRequested(); + var line = await reader.ReadLineAsync(); + if (line != null) + { + yield return line; + } + } } - await writer.FlushAsync(cancellationToken); - } -#else - public static Task WriteAllTextAsync(string path, string? contents, Encoding encoding, CancellationToken cancellationToken = default) - => File.WriteAllTextAsync(path, contents, encoding, cancellationToken); #endif - /// - /// Asynchronously creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is truncated and overwritten. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltextasync?view=net-10.0#system-io-file-writealltextasync(system-string-system-string-system-text-encoding-system-threading-cancellationtoken) - public static Task WriteAllTextAsync(string path, string? contents, CancellationToken cancellationToken = default) => -#if NETFRAMEWORK || NETSTANDARD2_0 - WriteAllTextAsync(path, contents, Encoding.UTF8, cancellationToken); -#else - File.WriteAllTextAsync(path, contents, cancellationToken); #endif -} \ No newline at end of file + + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/FileUnixModePolyfill.cs b/src/Polyfill/FileUnixModePolyfill.cs index b7527416..8fb12ea5 100644 --- a/src/Polyfill/FileUnixModePolyfill.cs +++ b/src/Polyfill/FileUnixModePolyfill.cs @@ -2,6 +2,7 @@ #pragma warning disable +#if !NET7_0_OR_GREATER namespace Polyfills; using System; @@ -10,280 +11,268 @@ namespace Polyfills; using System.Runtime.InteropServices; using System.Runtime.Versioning; -static partial class FilePolyfill +static partial class Polyfill { - /// - /// Gets the UnixFileMode of the file on the path. - /// - /// The path to the file. - /// The UnixFileMode of the file handle. - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.getunixfilemode?view=net-10.0#system-io-file-getunixfilemode(system-string) - [UnsupportedOSPlatform("windows")] - public static UnixFileMode GetUnixFileMode(string path) => -#if NET7_0_OR_GREATER - File.GetUnixFileMode(path); -#else - GetUnixFileModeFallback(path); - - [UnsupportedOSPlatform("windows")] - static UnixFileMode GetUnixFileModeFallback(string path) + extension(File) { -#if FeatureRuntimeInformation - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + /// + /// Gets the UnixFileMode of the file on the path. + /// + /// The path to the file. + /// The UnixFileMode of the file handle. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.getunixfilemode?view=net-10.0#system-io-file-getunixfilemode(system-string) + [UnsupportedOSPlatform("windows")] + public static UnixFileMode GetUnixFileMode(string path) { - throw new PlatformNotSupportedException(); - } +#if FeatureRuntimeInformation + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + throw new PlatformNotSupportedException(); + } #else - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - throw new PlatformNotSupportedException(); - } + if (Environment.OSVersion.Platform == PlatformID.Win32NT) + { + throw new PlatformNotSupportedException(); + } #endif - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("path is a zero-length string, or contains one or more invalid characters. Query for invalid characters by using the GetInvalidPathChars() method."); - } - - var startInfo = new ProcessStartInfo() - { - FileName = "stat", - Arguments = $"-c %a {Path.GetFullPath(path)}", - RedirectStandardOutput = true, - RedirectStandardInput = false, - UseShellExecute = false, - CreateNoWindow = true, - }; - - using var process = Process.Start(startInfo); - - process.WaitForExit(); - - var output = process.StandardOutput.ReadToEnd(); - - output = output.Length == 4 ? output : output.Insert(0, "0"); - - UnixFileMode mode; - - // Digit 1 (out of 4) is for Special permissions - switch (output[0]) - { - case '1': - mode = UnixFileMode.StickyBit; - break; - case '2': - mode = UnixFileMode.SetUser; - break; - case '4': - mode = UnixFileMode.SetGroup; - break; - default: - mode = UnixFileMode.None; - break; - } + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("path is a zero-length string, or contains one or more invalid characters. Query for invalid characters by using the GetInvalidPathChars() method."); + } - // Digit 2 (out of 4) for Users - switch (output[1]) - { - case '0': - mode = mode | UnixFileMode.None; - break; - case '1': - mode = mode | UnixFileMode.UserExecute; - break; - case '2': - mode = mode | UnixFileMode.UserWrite; - break; - case '3': - mode = mode | UnixFileMode.UserExecute | UnixFileMode.UserWrite; - break; - case '4': - mode = mode | UnixFileMode.UserRead; - break; - case '5': - mode = mode | UnixFileMode.UserRead | UnixFileMode.UserExecute; - break; - case '6': - mode = mode | UnixFileMode.UserRead | UnixFileMode.UserWrite; - break; - case '7': - mode = mode | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; - break; - default: - throw new Exception("Invalid octal notation detected"); - } + var startInfo = new ProcessStartInfo() + { + FileName = "stat", + Arguments = $"-c %a {Path.GetFullPath(path)}", + RedirectStandardOutput = true, + RedirectStandardInput = false, + UseShellExecute = false, + CreateNoWindow = true, + }; - // Digit 3 (out of 4) for Groups - switch (output[2]) - { - case '0': - mode = mode | UnixFileMode.None; - break; - case '1': - mode = mode | UnixFileMode.GroupExecute; - break; - case '2': - mode = mode | UnixFileMode.GroupWrite; - break; - case '3': - mode = mode | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite; - break; - case '4': - mode = mode | UnixFileMode.GroupRead; - break; - case '5': - mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupExecute; - break; - case '6': - mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupWrite; - break; - case '7': - mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute; - break; - default: - throw new Exception("Invalid octal notation detected"); - } + using var process = Process.Start(startInfo); - // Digit 4 (out of 4) for Others - switch (output[3]) - { - case '0': - mode = mode | UnixFileMode.None; - break; - case '1': - mode = mode | UnixFileMode.OtherExecute; - break; - case '2': - mode = mode | UnixFileMode.OtherWrite; - break; - case '3': - mode = mode | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite; - break; - case '4': - mode = mode | UnixFileMode.OtherRead; - break; - case '5': - mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; - break; - case '6': - mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherWrite; - break; - case '7': - mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; - break; - default: - throw new Exception("Invalid octal notation detected"); - } + process.WaitForExit(); - return mode; - } -#endif + var output = process.StandardOutput.ReadToEnd(); - /// - /// Sets the specified UnixFileMode of the file on the specified pat - /// - /// The path to the file. - /// The Unix file mode. - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setunixfilemode?view=net-10.0#system-io-file-setunixfilemode(system-string-system-io-unixfilemode) - [UnsupportedOSPlatform("windows")] - public static void SetUnixFileMode(string path, UnixFileMode mode) => -#if NET7_0_OR_GREATER - File.SetUnixFileMode(path, mode); -#else - SetUnixFileModeFallback(path, mode); + output = output.Length == 4 ? output : output.Insert(0, "0"); - [UnsupportedOSPlatform("windows")] - static void SetUnixFileModeFallback(string path, UnixFileMode mode) - { -#if FeatureRuntimeInformation - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - throw new PlatformNotSupportedException(); - } -#else - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - throw new PlatformNotSupportedException(); - } -#endif - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException("path is a zero-length string, or contains one or more invalid characters. Query for invalid characters by using the GetInvalidPathChars() method."); - } + UnixFileMode mode; - var octal = new int[4] - { - 0, - 0, - 0, - 0 - }; + // Digit 1 (out of 4) is for Special permissions + switch (output[0]) + { + case '1': + mode = UnixFileMode.StickyBit; + break; + case '2': + mode = UnixFileMode.SetUser; + break; + case '4': + mode = UnixFileMode.SetGroup; + break; + default: + mode = UnixFileMode.None; + break; + } - string[] fileModeStrings = mode.ToString() - .Replace("UnixFileMode.", "") - .Replace(",", string.Empty) - .Replace(Environment.NewLine, string.Empty) - .Split(' '); + // Digit 2 (out of 4) for Users + switch (output[1]) + { + case '0': + mode = mode | UnixFileMode.None; + break; + case '1': + mode = mode | UnixFileMode.UserExecute; + break; + case '2': + mode = mode | UnixFileMode.UserWrite; + break; + case '3': + mode = mode | UnixFileMode.UserExecute | UnixFileMode.UserWrite; + break; + case '4': + mode = mode | UnixFileMode.UserRead; + break; + case '5': + mode = mode | UnixFileMode.UserRead | UnixFileMode.UserExecute; + break; + case '6': + mode = mode | UnixFileMode.UserRead | UnixFileMode.UserWrite; + break; + case '7': + mode = mode | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + break; + default: + throw new Exception("Invalid octal notation detected"); + } - foreach (var fileModeString in fileModeStrings) - { - switch (fileModeString.ToLower()) + // Digit 3 (out of 4) for Groups + switch (output[2]) { - //The digits are set to 0 by default, so we don't need to do anything. - case "none": + case '0': + mode = mode | UnixFileMode.None; + break; + case '1': + mode = mode | UnixFileMode.GroupExecute; + break; + case '2': + mode = mode | UnixFileMode.GroupWrite; break; - case "userread": - octal[1] = octal[1] + 4; + case '3': + mode = mode | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite; break; - case "userwrite": - octal[1] = octal[1] + 2; + case '4': + mode = mode | UnixFileMode.GroupRead; break; - case "userexecute": - octal[1] = octal[1] + 1; + case '5': + mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupExecute; break; - case "groupread": - octal[2] = octal[2] + 4; + case '6': + mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupWrite; break; - case "groupwrite": - octal[2] = octal[2] + 2; + case '7': + mode = mode | UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute; + break; + default: + throw new Exception("Invalid octal notation detected"); + } + + // Digit 4 (out of 4) for Others + switch (output[3]) + { + case '0': + mode = mode | UnixFileMode.None; break; - case "groupexecute": - octal[2] = octal[2] + 1; + case '1': + mode = mode | UnixFileMode.OtherExecute; break; - case "otherread": - octal[3] = octal[3] + 4; + case '2': + mode = mode | UnixFileMode.OtherWrite; break; - case "otherwrite": - octal[3] = octal[3] + 2; + case '3': + mode = mode | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite; break; - case "otherexecute": - octal[3] = octal[3] + 1; + case '4': + mode = mode | UnixFileMode.OtherRead; break; - case "setuser": - octal[0] = octal[0] + 2; + case '5': + mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherExecute; break; - case "stickybit": - octal[0] = octal[0] + 1; + case '6': + mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherWrite; break; - case "setgroup": - octal[0] = octal[0] + 4; + case '7': + mode = mode | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; break; default: - throw new Exception("Invalid notation detected"); + throw new Exception("Invalid octal notation detected"); } + + return mode; } - var startInfo = new ProcessStartInfo() + /// + /// Sets the specified UnixFileMode of the file on the specified pat + /// + /// The path to the file. + /// The Unix file mode. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.setunixfilemode?view=net-10.0#system-io-file-setunixfilemode(system-string-system-io-unixfilemode) + [UnsupportedOSPlatform("windows")] + public static void SetUnixFileMode(string path, UnixFileMode mode) { - FileName = "chmod", - Arguments = $"{string.Concat(octal)} {Path.GetFullPath(path)}", - RedirectStandardOutput = true, - RedirectStandardInput = false, - UseShellExecute = false, - CreateNoWindow = true, - }; +#if FeatureRuntimeInformation + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + throw new PlatformNotSupportedException(); + } +#else + if (Environment.OSVersion.Platform == PlatformID.Win32NT) + { + throw new PlatformNotSupportedException(); + } +#endif + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("path is a zero-length string, or contains one or more invalid characters. Query for invalid characters by using the GetInvalidPathChars() method."); + } + + var octal = new int[4] + { + 0, + 0, + 0, + 0 + }; - using var process = Process.Start(startInfo); - process.WaitForExit(); + string[] fileModeStrings = mode.ToString() + .Replace("UnixFileMode.", "") + .Replace(",", string.Empty) + .Replace(Environment.NewLine, string.Empty) + .Split(' '); + + foreach (var fileModeString in fileModeStrings) + { + switch (fileModeString.ToLower()) + { + //The digits are set to 0 by default, so we don't need to do anything. + case "none": + break; + case "userread": + octal[1] = octal[1] + 4; + break; + case "userwrite": + octal[1] = octal[1] + 2; + break; + case "userexecute": + octal[1] = octal[1] + 1; + break; + case "groupread": + octal[2] = octal[2] + 4; + break; + case "groupwrite": + octal[2] = octal[2] + 2; + break; + case "groupexecute": + octal[2] = octal[2] + 1; + break; + case "otherread": + octal[3] = octal[3] + 4; + break; + case "otherwrite": + octal[3] = octal[3] + 2; + break; + case "otherexecute": + octal[3] = octal[3] + 1; + break; + case "setuser": + octal[0] = octal[0] + 2; + break; + case "stickybit": + octal[0] = octal[0] + 1; + break; + case "setgroup": + octal[0] = octal[0] + 4; + break; + default: + throw new Exception("Invalid notation detected"); + } + } + + var startInfo = new ProcessStartInfo() + { + FileName = "chmod", + Arguments = $"{string.Concat(octal)} {Path.GetFullPath(path)}", + RedirectStandardOutput = true, + RedirectStandardInput = false, + UseShellExecute = false, + CreateNoWindow = true, + }; + + using var process = Process.Start(startInfo); + process.WaitForExit(); + } } -#endif -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/src/Polyfill/GuidPolyfill.cs b/src/Polyfill/GuidPolyfill.cs index dded8785..44359433 100644 --- a/src/Polyfill/GuidPolyfill.cs +++ b/src/Polyfill/GuidPolyfill.cs @@ -1,121 +1,140 @@ // + + #pragma warning disable +#if !NET10_0_OR_GREATER + namespace Polyfills; +using System.Text; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class GuidPolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@) - public static bool TryParse(string? target, IFormatProvider? provider, out Guid result) => -#if NET7_0_OR_GREATER - Guid.TryParse(target, provider, out result); -#else - Guid.TryParse(target, out result); -#endif + extension(Guid) + { +#if !NET7_0_OR_GREATER - /// Creates a new according to RFC 9562, following the Version 7 format. - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7 - public static Guid CreateVersion7() => CreateVersion7(DateTimeOffset.UtcNow); + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-string-system-iformatprovider-system-guid@) + public static bool TryParse(string? s, IFormatProvider? provider, out Guid result) => + Guid.TryParse(s, out result); - /// Creates a new according to RFC 9562, following the Version 7 format. - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset) - public static Guid CreateVersion7(DateTimeOffset timestamp) - { -#if NET9_0_OR_GREATER - return Guid.CreateVersion7(timestamp); -#else - var unixMilliseconds = timestamp.ToUnixTimeMilliseconds(); +#endif - var timeBytes = BitConverter.GetBytes(unixMilliseconds); +#if !NET9_0_OR_GREATER - if (BitConverter.IsLittleEndian) + /// Creates a new according to RFC 9562, following the Version 7 format. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7 + public static Guid CreateVersion7() => CreateVersion7(DateTimeOffset.UtcNow); + + /// Creates a new according to RFC 9562, following the Version 7 format. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7?view=net-10.0#system-guid-createversion7(system-datetimeoffset) + public static Guid CreateVersion7(DateTimeOffset timestamp) { - Array.Reverse(timeBytes); - } + var unixMilliseconds = timestamp.ToUnixTimeMilliseconds(); + + var timeBytes = BitConverter.GetBytes(unixMilliseconds); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(timeBytes); + } #if NET8_0_OR_GREATER - var uuidBytes = new byte[16]; - timeBytes[2..8].CopyTo(uuidBytes, 0); + var uuidBytes = new byte[16]; + timeBytes[2..8].CopyTo(uuidBytes, 0); - var randomBytes = uuidBytes.AsSpan().Slice(6); + var randomBytes = uuidBytes.AsSpan().Slice(6); - RandomNumberGenerator.Fill(randomBytes); + RandomNumberGenerator.Fill(randomBytes); - uuidBytes[6] &= 0x0F; - uuidBytes[6] += 0x70; + uuidBytes[6] &= 0x0F; + uuidBytes[6] += 0x70; - return new(uuidBytes, true); + return new(uuidBytes, true); #else - var randomBytes = new byte[10]; + var randomBytes = new byte[10]; - using (var numberGenerator = RandomNumberGenerator.Create()) - { - numberGenerator.GetBytes(randomBytes); - } + using (var numberGenerator = RandomNumberGenerator.Create()) + { + numberGenerator.GetBytes(randomBytes); + } - var uuidBytes = new byte[16]; - Array.Copy(timeBytes, 2, uuidBytes, 0, 6); - Array.Copy(randomBytes, 0, uuidBytes, 6, 10); + var uuidBytes = new byte[16]; + Array.Copy(timeBytes, 2, uuidBytes, 0, 6); + Array.Copy(randomBytes, 0, uuidBytes, 6, 10); - uuidBytes[6] = (byte)((uuidBytes[6] & 0x0F) | 0x70); + uuidBytes[6] = (byte) ((uuidBytes[6] & 0x0F) | 0x70); - uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); + uuidBytes[8] = (byte) ((uuidBytes[8] & 0x3F) | 0x80); - return new(uuidBytes); + return new(uuidBytes); #endif + } + #endif - } #if FeatureMemory - /// - /// Converts span of characters representing the GUID to the equivalent Guid structure, provided that the string is in the specified format. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@) - public static bool TryParseExact(ReadOnlySpan target, ReadOnlySpan format, out Guid result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - Guid.TryParseExact(target, format, out result); -#else - Guid.TryParseExact(target.ToString(), format.ToString(), out result); +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts span of characters representing the GUID to the equivalent Guid structure, provided that the string is in the specified format. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact?view=net-10.0#system-guid-tryparseexact(system-readonlyspan((system-char))-system-readonlyspan((system-char))-system-guid@) + public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, out Guid result) => + Guid.TryParseExact(input.ToString(), format.ToString(), out result); + #endif - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out Guid result) => -#if NET7_0_OR_GREATER - Guid.TryParse(target, provider, out result); -#else - Guid.TryParse(target.ToString(), out result); +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-guid@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out Guid result) => + Guid.TryParse(s.ToString(), out result); + #endif - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@) - public static bool TryParse(ReadOnlySpan target, out Guid result) => -#if NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER - Guid.TryParse(target, out result); -#else - Guid.TryParse(target.ToString(), out result); +#if !(NETSTANDARD2_1 || NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER) + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-char))-system-guid@) + public static bool TryParse(ReadOnlySpan input, out Guid result) => + Guid.TryParse(input.ToString(), out result); + #endif +#if !NET10_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 bytes into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse?view=net-10.0#system-guid-tryparse(system-readonlyspan((system-byte))-system-guid@) + public static bool TryParse(ReadOnlySpan utf8Text, out Guid result) => + Guid.TryParse(Encoding.UTF8.GetString(utf8Text), out result); + + /// + /// Parse a span of UTF-8 bytes into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.parse?view=net-10.0#system-guid-parse(system-readonlyspan((system-byte))) + public static Guid Parse(ReadOnlySpan utf8Text) => + Guid.Parse(Encoding.UTF8.GetString(utf8Text)); #endif -} \ No newline at end of file + +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/IndexRange/Index.cs b/src/Polyfill/IndexRange/Index.cs index 8dbe4abc..58ff727a 100644 --- a/src/Polyfill/IndexRange/Index.cs +++ b/src/Polyfill/IndexRange/Index.cs @@ -13,6 +13,9 @@ namespace System; /// Represent a type can be used to index a collection either from the start or the end. [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/IndexRange/Range.cs b/src/Polyfill/IndexRange/Range.cs index b43f37d1..7fb9c1bf 100644 --- a/src/Polyfill/IndexRange/Range.cs +++ b/src/Polyfill/IndexRange/Range.cs @@ -13,6 +13,9 @@ namespace System; /// Represent a range has start and end indexes. [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/IsExternalInit.cs b/src/Polyfill/IsExternalInit.cs index 7c41fdde..14ca5aa1 100644 --- a/src/Polyfill/IsExternalInit.cs +++ b/src/Polyfill/IsExternalInit.cs @@ -13,6 +13,9 @@ namespace System.Runtime.CompilerServices; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.isexternalinit?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/KeyValuePair.cs b/src/Polyfill/KeyValuePair.cs index 0e365290..c2bf34c4 100644 --- a/src/Polyfill/KeyValuePair.cs +++ b/src/Polyfill/KeyValuePair.cs @@ -11,6 +11,9 @@ namespace System.Collections.Generic; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif // Provides the Create factory method for KeyValuePair. // https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair?view=net-10.0 #if PolyPublic diff --git a/src/Polyfill/Lock.cs b/src/Polyfill/Lock.cs index ff47a784..a0c9352c 100644 --- a/src/Polyfill/Lock.cs +++ b/src/Polyfill/Lock.cs @@ -16,6 +16,9 @@ namespace System.Threading; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.lock?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/MathPolyfill.cs b/src/Polyfill/MathPolyfill.cs index 788bc72a..2df752ae 100644 --- a/src/Polyfill/MathPolyfill.cs +++ b/src/Polyfill/MathPolyfill.cs @@ -4,391 +4,339 @@ namespace Polyfills; using System; -using System.Runtime.CompilerServices; -using System.Diagnostics.CodeAnalysis; using System.Diagnostics; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class MathPolyfill +static partial class Polyfill { - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static float Clamp(float value, float min, float max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static nuint Clamp(nuint value, nuint min, nuint max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong Clamp(ulong value, ulong min, ulong max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint Clamp(uint value, uint min, uint max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ushort Clamp(ushort value, ushort min, ushort max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static sbyte Clamp(sbyte value, sbyte min, sbyte max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int Clamp(int value, int min, int max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static long Clamp(long value, long min, long max) + extension(Math) { #if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } - if (value < min) - { - return min; - } - - if (value > max) - { - return max; - } - - return value; -#else - return Math.Clamp(value, min, max); -#endif - } - - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static short Clamp(short value, short min, short max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Clamp(float value, float min, float max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } - if (value < min) - { - return min; - } + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static nuint Clamp(nuint value, nuint min, nuint max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } - if (value > max) + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong Clamp(ulong value, ulong min, ulong max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint Clamp(uint value, uint min, uint max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort Clamp(ushort value, ushort min, ushort max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static sbyte Clamp(sbyte value, sbyte min, sbyte max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int Clamp(int value, int min, int max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Clamp(long value, long min, long max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static short Clamp(short value, short min, short max) + { + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } + + if (value < min) + { + return min; + } + + if (value > max) + { + return max; + } + + return value; + } + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp(double value, double min, double max) { - return max; - } + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } - return value; -#else - return Math.Clamp(value, min, max); -#endif - } + if (value < min) + { + return min; + } - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static double Clamp(double value, double min, double max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } + if (value > max) + { + return max; + } - if (value < min) - { - return min; + return value; } - - if (value > max) + + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static decimal Clamp(decimal value, decimal min, decimal max) { - return max; - } + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } - return value; -#else - return Math.Clamp(value, min, max); -#endif - } + if (value < min) + { + return min; + } - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static decimal Clamp(decimal value, decimal min, decimal max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } + if (value > max) + { + return max; + } - if (value < min) - { - return min; + return value; } - if (value > max) + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte Clamp(byte value, byte min, byte max) { - return max; - } + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } - return value; -#else - return Math.Clamp(value, min, max); -#endif - } + if (value < min) + { + return min; + } - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static byte Clamp(byte value, byte min, byte max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } + if (value > max) + { + return max; + } - if (value < min) - { - return min; + return value; } - if (value > max) + /// + /// Returns value clamped to the inclusive range of min and max. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 + //[MethodImpl(MethodImplOptions.AggressiveInlining)] + public static nint Clamp(nint value, nint min, nint max) { - return max; - } + if (min > max) + { + throw new ArgumentException($"'{min}' cannot be greater than {max}."); + } - return value; -#else - return Math.Clamp(value, min, max); -#endif - } + if (value < min) + { + return min; + } - /// - /// Returns value clamped to the inclusive range of min and max. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-10.0 - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static nint Clamp(nint value, nint min, nint max) - { -#if !NET6_0_OR_GREATER - if (min > max) - { - throw new ArgumentException($"'{min}' cannot be greater than {max}."); - } + if (value > max) + { + return max; + } - if (value < min) - { - return min; - } - - if (value > max) - { - return max; + return value; } - return value; -#else - return Math.Clamp(value, min, max); #endif } } \ No newline at end of file diff --git a/src/Polyfill/ModuleInitializerAttribute.cs b/src/Polyfill/ModuleInitializerAttribute.cs index 253f6cdb..1f837529 100644 --- a/src/Polyfill/ModuleInitializerAttribute.cs +++ b/src/Polyfill/ModuleInitializerAttribute.cs @@ -18,6 +18,9 @@ namespace System.Runtime.CompilerServices; [AttributeUsage( validOn: AttributeTargets.Method, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullability/NullabilityInfo.cs b/src/Polyfill/Nullability/NullabilityInfo.cs index a6317015..fd64095d 100644 --- a/src/Polyfill/Nullability/NullabilityInfo.cs +++ b/src/Polyfill/Nullability/NullabilityInfo.cs @@ -18,6 +18,9 @@ namespace System.Reflection; /// [DebuggerNonUserCode] [ExcludeFromCodeCoverage] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.nullabilityinfo #if PolyPublic public @@ -59,6 +62,9 @@ internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState /// /// An enum that represents nullability state /// +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullability/NullabilityInfoContext.cs b/src/Polyfill/Nullability/NullabilityInfoContext.cs index bcc605da..8eefdd73 100644 --- a/src/Polyfill/Nullability/NullabilityInfoContext.cs +++ b/src/Polyfill/Nullability/NullabilityInfoContext.cs @@ -22,6 +22,9 @@ namespace System.Reflection; /// [DebuggerNonUserCode] [ExcludeFromCodeCoverage] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullability/NullabilityInfoExtensions.cs b/src/Polyfill/Nullability/Polyfill_Nullability.cs similarity index 97% rename from src/Polyfill/Nullability/NullabilityInfoExtensions.cs rename to src/Polyfill/Nullability/Polyfill_Nullability.cs index ec0cc0c7..fc3a3003 100644 --- a/src/Polyfill/Nullability/NullabilityInfoExtensions.cs +++ b/src/Polyfill/Nullability/Polyfill_Nullability.cs @@ -8,12 +8,6 @@ namespace Polyfills; using System.Collections.Concurrent; using System.Reflection; -/// -/// Static and thread safe wrapper around NullabilityInfoContext. -/// -#if PolyPublic -public -#endif static partial class Polyfill { static ConcurrentDictionary parameters = []; diff --git a/src/Polyfill/Nullable/AllowNullAttribute.cs b/src/Polyfill/Nullable/AllowNullAttribute.cs index 20b2645a..0ad5da97 100644 --- a/src/Polyfill/Nullable/AllowNullAttribute.cs +++ b/src/Polyfill/Nullable/AllowNullAttribute.cs @@ -17,6 +17,9 @@ namespace System.Diagnostics.CodeAnalysis; validOn: Targets.Field | Targets.Parameter | Targets.Property)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/DisallowNullAttribute.cs b/src/Polyfill/Nullable/DisallowNullAttribute.cs index be3c8269..cdf06e91 100644 --- a/src/Polyfill/Nullable/DisallowNullAttribute.cs +++ b/src/Polyfill/Nullable/DisallowNullAttribute.cs @@ -17,6 +17,9 @@ namespace System.Diagnostics.CodeAnalysis; validOn: Targets.Field | Targets.Parameter | Targets.Property)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/DoesNotReturnAttribute.cs b/src/Polyfill/Nullable/DoesNotReturnAttribute.cs index acc74c42..8e83d696 100644 --- a/src/Polyfill/Nullable/DoesNotReturnAttribute.cs +++ b/src/Polyfill/Nullable/DoesNotReturnAttribute.cs @@ -13,6 +13,9 @@ namespace System.Diagnostics.CodeAnalysis; [AttributeUsage( validOn: AttributeTargets.Method, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/DoesNotReturnIfAttribute.cs b/src/Polyfill/Nullable/DoesNotReturnIfAttribute.cs index 22a9e604..af7d06ce 100644 --- a/src/Polyfill/Nullable/DoesNotReturnIfAttribute.cs +++ b/src/Polyfill/Nullable/DoesNotReturnIfAttribute.cs @@ -12,6 +12,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/MaybeNullAttribute.cs b/src/Polyfill/Nullable/MaybeNullAttribute.cs index 769d9f24..947f3be4 100644 --- a/src/Polyfill/Nullable/MaybeNullAttribute.cs +++ b/src/Polyfill/Nullable/MaybeNullAttribute.cs @@ -18,6 +18,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Parameter | Targets.Property | Targets.ReturnValue)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/MaybeNullWhenAttribute.cs b/src/Polyfill/Nullable/MaybeNullWhenAttribute.cs index 155a9998..26014299 100644 --- a/src/Polyfill/Nullable/MaybeNullWhenAttribute.cs +++ b/src/Polyfill/Nullable/MaybeNullWhenAttribute.cs @@ -12,6 +12,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/MemberNotNullAttribute.cs b/src/Polyfill/Nullable/MemberNotNullAttribute.cs index f6fe927b..555ed241 100644 --- a/src/Polyfill/Nullable/MemberNotNullAttribute.cs +++ b/src/Polyfill/Nullable/MemberNotNullAttribute.cs @@ -18,6 +18,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Property, Inherited = false, AllowMultiple = true)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/MemberNotNullWhenAttribute.cs b/src/Polyfill/Nullable/MemberNotNullWhenAttribute.cs index 37068686..907439a7 100644 --- a/src/Polyfill/Nullable/MemberNotNullWhenAttribute.cs +++ b/src/Polyfill/Nullable/MemberNotNullWhenAttribute.cs @@ -18,6 +18,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Property, Inherited = false, AllowMultiple = true)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/NotNullAttribute.cs b/src/Polyfill/Nullable/NotNullAttribute.cs index 1e7f898b..2b7c7113 100644 --- a/src/Polyfill/Nullable/NotNullAttribute.cs +++ b/src/Polyfill/Nullable/NotNullAttribute.cs @@ -18,6 +18,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Parameter | Targets.Property | Targets.ReturnValue)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/NotNullIfNotNullAttribute.cs b/src/Polyfill/Nullable/NotNullIfNotNullAttribute.cs index 83fae675..977da882 100644 --- a/src/Polyfill/Nullable/NotNullIfNotNullAttribute.cs +++ b/src/Polyfill/Nullable/NotNullIfNotNullAttribute.cs @@ -14,6 +14,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Property | Targets.ReturnValue, AllowMultiple = true)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Nullable/NotNullWhenAttribute.cs b/src/Polyfill/Nullable/NotNullWhenAttribute.cs index ef072971..c34f7c46 100644 --- a/src/Polyfill/Nullable/NotNullWhenAttribute.cs +++ b/src/Polyfill/Nullable/NotNullWhenAttribute.cs @@ -12,6 +12,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Numbers/BytePolyfill.cs b/src/Polyfill/Numbers/BytePolyfill.cs index 9b01e838..72f24560 100644 --- a/src/Polyfill/Numbers/BytePolyfill.cs +++ b/src/Polyfill/Numbers/BytePolyfill.cs @@ -3,96 +3,85 @@ #nullable enable +#if !NET8_0_OR_GREATER + namespace Polyfills; + using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class BytePolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@) - public static bool TryParse(string? target, IFormatProvider? provider, out byte result) => -#if NET7_0_OR_GREATER - byte.TryParse(target, provider, out result); -#else - byte.TryParse(target, NumberStyles.Integer, provider, out result); + extension(Byte) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-string-system-iformatprovider-system-byte@) + public static bool TryParse(string? s, IFormatProvider? provider, out byte result) => + byte.TryParse(s, NumberStyles.Integer, provider, out result); + #endif #if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out byte result) => -#if NET8_0_OR_GREATER - byte.TryParse(target, provider, out result); -#else - byte.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its byte equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@) - public static bool TryParse(ReadOnlySpan target, out byte result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - byte.TryParse(target, out result); -#else - byte.TryParse(target.ToString(), out result); -#endif +#if !NET7_0_OR_GREATER - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out byte result) => -#if NET7_0_OR_GREATER - byte.TryParse(target, provider, out result); -#else - byte.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-byte@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out byte result) => + byte.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out byte result) => -#if NET8_0_OR_GREATER - byte.TryParse(target, style, provider, out result); -#else - byte.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); #endif - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its byte equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@) - public static bool TryParse(ReadOnlySpan target, out byte result) => -#if NET8_0_OR_GREATER - byte.TryParse(target, out result); -#else - byte.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-byte@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out byte result) => + byte.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-byte@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out byte result) => + byte.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its byte equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@) + public static bool TryParse(ReadOnlySpan utf8Text, out byte result) => + byte.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + #endif - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its byte equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out byte result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - byte.TryParse(target, style, provider, out result); -#else - byte.TryParse(target.ToString(), style, provider, out result); +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its byte equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@) + public static bool TryParse(ReadOnlySpan s, out byte result) => + byte.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its byte equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse?view=net-10.0#system-byte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-byte@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out byte result) => + byte.TryParse(s.ToString(), style, provider, out result); + #endif #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/DoublePolyfill.cs b/src/Polyfill/Numbers/DoublePolyfill.cs index 86ae0841..c5b2d7a4 100644 --- a/src/Polyfill/Numbers/DoublePolyfill.cs +++ b/src/Polyfill/Numbers/DoublePolyfill.cs @@ -1,97 +1,85 @@ // #pragma warning disable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class DoublePolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@) - public static bool TryParse(string? target, IFormatProvider? provider, out double result) => -#if NET7_0_OR_GREATER - double.TryParse(target, provider, out result); -#else - double.TryParse(target, NumberStyles.Float, provider, out result); + extension(double) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-string-system-iformatprovider-system-double@) + public static bool TryParse(string? s, IFormatProvider? provider, out double result) => + double.TryParse(s, NumberStyles.Float, provider, out result); + #endif #if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out double result) => -#if NET8_0_OR_GREATER - double.TryParse(target, provider, out result); -#else - double.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Float, provider, out result); -#endif +#if !NET8_0_OR_GREATER - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@) - public static bool TryParse(ReadOnlySpan target, out double result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - double.TryParse(target, out result); -#else - double.TryParse(target.ToString(), out result); -#endif + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-double@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out double result) => + double.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Float, provider, out result); - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out double result) => -#if NET7_0_OR_GREATER - double.TryParse(target, provider, out result); -#else - double.TryParse(target.ToString(), NumberStyles.Float, provider, out result); -#endif + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out double result) => + double.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its double-precision floating-point number equivalent.. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@) + public static bool TryParse(ReadOnlySpan utf8Text, out double result) => + double.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Float, null, out result); - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-double@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out double result) => -#if NET8_0_OR_GREATER - double.TryParse(target, style, provider, out result); -#else - double.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); #endif - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its double-precision floating-point number equivalent.. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-byte))-system-double@) - public static bool TryParse(ReadOnlySpan target, out double result) => -#if NET8_0_OR_GREATER - double.TryParse(target, out result); -#else - double.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Float, null, out result); +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-double@) + public static bool TryParse(ReadOnlySpan s, out double result) => + double.TryParse(s.ToString(), out result); + + /// + /// Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out double result) => + double.TryParse(s.ToString(), style, provider, out result); + #endif - /// - /// Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-double@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out double result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - double.TryParse(target, style, provider, out result); -#else - double.TryParse(target.ToString(), style, provider, out result); +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-10.0#system-double-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-double@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out double result) => + double.TryParse(s.ToString(), NumberStyles.Float, provider, out result); + #endif + #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/Int16Polyfill.cs b/src/Polyfill/Numbers/Int16Polyfill.cs new file mode 100644 index 00000000..3b6e73e9 --- /dev/null +++ b/src/Polyfill/Numbers/Int16Polyfill.cs @@ -0,0 +1,94 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif +#if PolyPublic +public +#endif +static partial class Int16Polyfill +{ + extension(short) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@) + public static bool TryParse(string? s, IFormatProvider? provider, out short result) => + short.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out short result) => + short.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out short result) => + short.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its short equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@) + public static bool TryParse(ReadOnlySpan utf8Text, out short result) => + short.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its short equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@) + public static bool TryParse(ReadOnlySpan s, out short result) => + short.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its short equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out short result) => + short.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out short result) => + short.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/Int32Polyfill.cs b/src/Polyfill/Numbers/Int32Polyfill.cs new file mode 100644 index 00000000..23570933 --- /dev/null +++ b/src/Polyfill/Numbers/Int32Polyfill.cs @@ -0,0 +1,96 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif +#if PolyPublic +public +#endif +static partial class Int32Polyfill +{ + extension(int) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@) + public static bool TryParse(string? s, IFormatProvider? provider, out int result) => + int.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory + +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out int result) => + int.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out int result) => + int.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its 32-bit signed integer equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@) + public static bool TryParse(ReadOnlySpan utf8Text, out int result) => + int.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@) + public static bool TryParse(ReadOnlySpan s, out int result) => + int.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out int result) => + int.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out int result) => + int.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif + +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/Int64Polyfill.cs b/src/Polyfill/Numbers/Int64Polyfill.cs new file mode 100644 index 00000000..b8725334 --- /dev/null +++ b/src/Polyfill/Numbers/Int64Polyfill.cs @@ -0,0 +1,86 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Globalization; +using System.Text; + +static partial class Polyfill +{ + extension(long) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@) + public static bool TryParse(string? s, IFormatProvider? provider, out long result) => + long.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory + +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out long result) => + long.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out long result) => + long.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its 64-bit signed integer equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@) + public static bool TryParse(ReadOnlySpan utf8Text, out long result) => + long.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@) + public static bool TryParse(ReadOnlySpan s, out long result) => + long.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its 64-bit signed integer equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out long result) => + long.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out long result) => + long.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif + +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/IntPolyfill.cs b/src/Polyfill/Numbers/IntPolyfill.cs deleted file mode 100644 index ec516785..00000000 --- a/src/Polyfill/Numbers/IntPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class IntPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-string-system-iformatprovider-system-int32@) - public static bool TryParse(string? target, IFormatProvider? provider, out int result) => -#if NET7_0_OR_GREATER - int.TryParse(target, provider, out result); -#else - int.TryParse(target, NumberStyles.Integer, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int32@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out int result) => -#if NET8_0_OR_GREATER - int.TryParse(target, provider, out result); -#else - int.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@) - public static bool TryParse(ReadOnlySpan target, out int result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - int.TryParse(target, out result); -#else - int.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int32@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out int result) => -#if NET7_0_OR_GREATER - int.TryParse(target, provider, out result); -#else - int.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int32@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out int result) => -#if NET8_0_OR_GREATER - int.TryParse(target, style, provider, out result); -#else - int.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its 32-bit signed integer equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@) - public static bool TryParse(ReadOnlySpan target, out int result) => -#if NET8_0_OR_GREATER - int.TryParse(target, out result); -#else - int.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-10.0#system-int32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int32@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out int result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - int.TryParse(target, style, provider, out result); -#else - int.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/Numbers/LongPolyfill.cs b/src/Polyfill/Numbers/LongPolyfill.cs deleted file mode 100644 index 2f0abfce..00000000 --- a/src/Polyfill/Numbers/LongPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class LongPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-string-system-iformatprovider-system-int64@) - public static bool TryParse(string? target, IFormatProvider? provider, out long result) => -#if NET7_0_OR_GREATER - long.TryParse(target, provider, out result); -#else - long.TryParse(target, NumberStyles.Integer, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int64@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out long result) => -#if NET8_0_OR_GREATER - long.TryParse(target, provider, out result); -#else - long.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@) - public static bool TryParse(ReadOnlySpan target, out long result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - long.TryParse(target, out result); -#else - long.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int64@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out long result) => -#if NET7_0_OR_GREATER - long.TryParse(target, provider, out result); -#else - long.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int64@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out long result) => -#if NET8_0_OR_GREATER - long.TryParse(target, style, provider, out result); -#else - long.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its 64-bit signed integer equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@) - public static bool TryParse(ReadOnlySpan target, out long result) => -#if NET8_0_OR_GREATER - long.TryParse(target, out result); -#else - long.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its 64-bit signed integer equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse?view=net-10.0#system-int64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int64@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out long result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - long.TryParse(target, style, provider, out result); -#else - long.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/Numbers/SBytePolyfill.cs b/src/Polyfill/Numbers/SBytePolyfill.cs index b18c7eb3..44a37817 100644 --- a/src/Polyfill/Numbers/SBytePolyfill.cs +++ b/src/Polyfill/Numbers/SBytePolyfill.cs @@ -1,97 +1,86 @@ // #pragma warning disable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class SBytePolyfill +static partial class Polyfill { - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@) - public static bool TryParse(string? target, IFormatProvider? provider, out sbyte result) => -#if NET7_0_OR_GREATER - sbyte.TryParse(target, provider, out result); -#else - sbyte.TryParse(target, NumberStyles.Integer, provider, out result); + extension(sbyte) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-string-system-iformatprovider-system-sbyte@) + public static bool TryParse(string? s, IFormatProvider? provider, out sbyte result) => + sbyte.TryParse(s, NumberStyles.Integer, provider, out result); + #endif #if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out sbyte result) => -#if NET8_0_OR_GREATER - sbyte.TryParse(target, provider, out result); -#else - sbyte.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its sbyte equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, out sbyte result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - sbyte.TryParse(target, out result); -#else - sbyte.TryParse(target.ToString(), out result); -#endif +#if !NET8_0_OR_GREATER - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out sbyte result) => -#if NET7_0_OR_GREATER - sbyte.TryParse(target, provider, out result); -#else - sbyte.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-sbyte@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out sbyte result) => + sbyte.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out sbyte result) => + sbyte.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its sbyte equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) + public static bool TryParse(ReadOnlySpan utf8Text, out sbyte result) => + sbyte.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out sbyte result) => -#if NET8_0_OR_GREATER - sbyte.TryParse(target, style, provider, out result); -#else - sbyte.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); #endif - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its sbyte equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, out sbyte result) => -#if NET8_0_OR_GREATER - sbyte.TryParse(target, out result); -#else - sbyte.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its sbyte equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@) + public static bool TryParse(ReadOnlySpan s, out sbyte result) => + sbyte.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its sbyte equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out sbyte result) => + sbyte.TryParse(s.ToString(), style, provider, out result); + #endif - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its sbyte equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-sbyte@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out sbyte result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - sbyte.TryParse(target, style, provider, out result); -#else - sbyte.TryParse(target.ToString(), style, provider, out result); +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse?view=net-10.0#system-sbyte-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-sbyte@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out sbyte result) => + sbyte.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + #endif + #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/ShortPolyfill.cs b/src/Polyfill/Numbers/ShortPolyfill.cs deleted file mode 100644 index e0ea5375..00000000 --- a/src/Polyfill/Numbers/ShortPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class ShortPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-string-system-iformatprovider-system-int16@) - public static bool TryParse(string? target, IFormatProvider? provider, out short result) => -#if NET7_0_OR_GREATER - short.TryParse(target, provider, out result); -#else - short.TryParse(target, NumberStyles.Integer, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-int16@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out short result) => -#if NET8_0_OR_GREATER - short.TryParse(target, provider, out result); -#else - short.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its short equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@) - public static bool TryParse(ReadOnlySpan target, out short result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - short.TryParse(target, out result); -#else - short.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-int16@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out short result) => -#if NET7_0_OR_GREATER - short.TryParse(target, provider, out result); -#else - short.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-int16@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out short result) => -#if NET8_0_OR_GREATER - short.TryParse(target, style, provider, out result); -#else - short.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its short equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@) - public static bool TryParse(ReadOnlySpan target, out short result) => -#if NET8_0_OR_GREATER - short.TryParse(target, out result); -#else - short.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its short equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryparse?view=net-10.0#system-int16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-int16@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out short result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - short.TryParse(target, style, provider, out result); -#else - short.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/Numbers/UInt16Polyfill.cs b/src/Polyfill/Numbers/UInt16Polyfill.cs new file mode 100644 index 00000000..f94d9a89 --- /dev/null +++ b/src/Polyfill/Numbers/UInt16Polyfill.cs @@ -0,0 +1,86 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Globalization; +using System.Text; + +static partial class Polyfill +{ + extension(ushort) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@) + public static bool TryParse(string? s, IFormatProvider? provider, out ushort result) => + ushort.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory + +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out ushort result) => + ushort.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out ushort result) => + ushort.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its ushort equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) + public static bool TryParse(ReadOnlySpan utf8Text, out ushort result) => + ushort.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its ushort equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@) + public static bool TryParse(ReadOnlySpan s, out ushort result) => + ushort.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its ushort equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out ushort result) => + ushort.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out ushort result) => + ushort.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif + +#endif + } +} + +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/UInt32Polyfill.cs b/src/Polyfill/Numbers/UInt32Polyfill.cs new file mode 100644 index 00000000..0587f0b6 --- /dev/null +++ b/src/Polyfill/Numbers/UInt32Polyfill.cs @@ -0,0 +1,86 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Globalization; +using System.Text; + +static partial class Polyfill +{ + extension(uint) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@) + public static bool TryParse(string? s, IFormatProvider? provider, out uint result) => + uint.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory + +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out uint result) => + uint.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) + public static bool TryParse(ReadOnlySpan utf8Text, NumberStyles style, IFormatProvider? provider, out uint result) => + uint.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its uint equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) + public static bool TryParse(ReadOnlySpan utf8Text, out uint result) => + uint.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its uint equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@) + public static bool TryParse(ReadOnlySpan s, out uint result) => + uint.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its uint equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out uint result) => + uint.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out uint result) => + uint.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif + +#endif + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/UInt64Polyfill.cs b/src/Polyfill/Numbers/UInt64Polyfill.cs new file mode 100644 index 00000000..b9dd142f --- /dev/null +++ b/src/Polyfill/Numbers/UInt64Polyfill.cs @@ -0,0 +1,87 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Globalization; +using System.Text; + +static partial class Polyfill +{ + extension(ulong) + { +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@) + public static bool TryParse(string? s, IFormatProvider? provider, out ulong result) => + ulong.TryParse(s, NumberStyles.Integer, provider, out result); + +#endif + +#if FeatureMemory + +#if !NET8_0_OR_GREATER + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@) + public static bool TryParse(ReadOnlySpan utf8Text, IFormatProvider? provider, out ulong result) => + ulong.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, provider, out result); + + /// + /// Tries to parse a span of UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) + public static bool TryParse(ReadOnlySpanutf8Text, NumberStyles style, IFormatProvider? provider, out ulong result) => + ulong.TryParse(Encoding.UTF8.GetString(utf8Text), style, provider, out result); + + /// + /// Tries to convert a UTF-8 character span containing the string representation of a number to its ulong equivalent. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) + public static bool TryParse(ReadOnlySpan utf8Text, out ulong result) => + ulong.TryParse(Encoding.UTF8.GetString(utf8Text), NumberStyles.Integer, null, out result); + +#endif + +#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its ulong equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@) + public static bool TryParse(ReadOnlySpan s, out ulong result) => + ulong.TryParse(s.ToString(), out result); + + /// + /// Converts the span representation of a number in a specified style and culture-specific format to its ulong equivalent. A return value indicates whether the conversion succeeded. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out ulong result) => + ulong.TryParse(s.ToString(), style, provider, out result); + +#endif + +#if !NET7_0_OR_GREATER + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@) + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out ulong result) => + ulong.TryParse(s.ToString(), NumberStyles.Integer, provider, out result); + +#endif + +#endif + } +} + +#endif \ No newline at end of file diff --git a/src/Polyfill/Numbers/UIntPolyfill.cs b/src/Polyfill/Numbers/UIntPolyfill.cs deleted file mode 100644 index e2dcb451..00000000 --- a/src/Polyfill/Numbers/UIntPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class UIntPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-string-system-iformatprovider-system-uint32@) - public static bool TryParse(string? target, IFormatProvider? provider, out uint result) => -#if NET7_0_OR_GREATER - uint.TryParse(target, provider, out result); -#else - uint.TryParse(target, NumberStyles.Integer, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint32@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out uint result) => -#if NET8_0_OR_GREATER - uint.TryParse(target, provider, out result); -#else - uint.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its uint equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@) - public static bool TryParse(ReadOnlySpan target, out uint result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - uint.TryParse(target, out result); -#else - uint.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint32@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out uint result) => -#if NET7_0_OR_GREATER - uint.TryParse(target, provider, out result); -#else - uint.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out uint result) => -#if NET8_0_OR_GREATER - uint.TryParse(target, style, provider, out result); -#else - uint.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its uint equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) - public static bool TryParse(ReadOnlySpan target, out uint result) => -#if NET8_0_OR_GREATER - uint.TryParse(target, out result); -#else - uint.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its uint equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryparse?view=net-10.0#system-uint32-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint32@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out uint result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - uint.TryParse(target, style, provider, out result); -#else - uint.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/Numbers/ULongPolyfill.cs b/src/Polyfill/Numbers/ULongPolyfill.cs deleted file mode 100644 index 01e8fbfb..00000000 --- a/src/Polyfill/Numbers/ULongPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class ULongPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-string-system-iformatprovider-system-uint64@) - public static bool TryParse(string? target, IFormatProvider? provider, out ulong result) => -#if NET7_0_OR_GREATER - ulong.TryParse(target, provider, out result); -#else - ulong.TryParse(target, NumberStyles.Integer, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint64@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out ulong result) => -#if NET8_0_OR_GREATER - ulong.TryParse(target, provider, out result); -#else - ulong.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its ulong equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@) - public static bool TryParse(ReadOnlySpan target, out ulong result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - ulong.TryParse(target, out result); -#else - ulong.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint64@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out ulong result) => -#if NET7_0_OR_GREATER - ulong.TryParse(target, provider, out result); -#else - ulong.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out ulong result) => -#if NET8_0_OR_GREATER - ulong.TryParse(target, style, provider, out result); -#else - ulong.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its ulong equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) - public static bool TryParse(ReadOnlySpan target, out ulong result) => -#if NET8_0_OR_GREATER - ulong.TryParse(target, out result); -#else - ulong.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its ulong equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryparse?view=net-10.0#system-uint64-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint64@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out ulong result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - ulong.TryParse(target, style, provider, out result); -#else - ulong.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/Numbers/UShortPolyfill.cs b/src/Polyfill/Numbers/UShortPolyfill.cs deleted file mode 100644 index dc1e4d23..00000000 --- a/src/Polyfill/Numbers/UShortPolyfill.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Text; - -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class UShortPolyfill -{ - /// - /// Tries to parse a string into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-string-system-iformatprovider-system-uint16@) - public static bool TryParse(string? target, IFormatProvider? provider, out ushort result) => -#if !NET7_0_OR_GREATER - ushort.TryParse(target, NumberStyles.Integer, provider, out result); -#else - ushort.TryParse(target, provider, out result); -#endif - -#if FeatureMemory - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-iformatprovider-system-uint16@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out ushort result) => -#if NET8_0_OR_GREATER - ushort.TryParse(target, provider, out result); -#else - ushort.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its ushort equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@) - public static bool TryParse(ReadOnlySpan target, out ushort result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - ushort.TryParse(target, out result); -#else - ushort.TryParse(target.ToString(), out result); -#endif - - /// - /// Tries to parse a span of characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-iformatprovider-system-uint16@) - public static bool TryParse(ReadOnlySpan target, IFormatProvider? provider, out ushort result) => -#if NET7_0_OR_GREATER - ushort.TryParse(target, provider, out result); -#else - ushort.TryParse(target.ToString(), NumberStyles.Integer, provider, out result); -#endif - - /// - /// Tries to parse a span of UTF-8 characters into a value. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-byte))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out ushort result) => -#if NET8_0_OR_GREATER - ushort.TryParse(target, style, provider, out result); -#else - ushort.TryParse(Encoding.UTF8.GetString(target), style, provider, out result); -#endif - - /// - /// Tries to convert a UTF-8 character span containing the string representation of a number to its ushort equivalent. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) - public static bool TryParse(ReadOnlySpan target, out ushort result) => -#if NET8_0_OR_GREATER - ushort.TryParse(target, out result); -#else - ushort.TryParse(Encoding.UTF8.GetString(target), NumberStyles.Integer, null, out result); -#endif - - /// - /// Converts the span representation of a number in a specified style and culture-specific format to its ushort equivalent. A return value indicates whether the conversion succeeded. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryparse?view=net-10.0#system-uint16-tryparse(system-readonlyspan((system-char))-system-globalization-numberstyles-system-iformatprovider-system-uint16@) - public static bool TryParse(ReadOnlySpan target, NumberStyles style, IFormatProvider? provider, out ushort result) => -#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - ushort.TryParse(target, style, provider, out result); -#else - ushort.TryParse(target.ToString(), style, provider, out result); -#endif -#endif -} \ No newline at end of file diff --git a/src/Polyfill/OperatingSystemCache.cs b/src/Polyfill/OperatingSystemCache.cs new file mode 100644 index 00000000..8fdae3ab --- /dev/null +++ b/src/Polyfill/OperatingSystemCache.cs @@ -0,0 +1,144 @@ +// +#pragma warning disable + +namespace Polyfills; + +#if FeatureRuntimeInformation && !NET + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif +static class OperatingSystemCache +{ + static Version? windowsVersion; + static Version? freeBsdVersion; + static Version? androidVersion; + static bool? isAndroid; + static Version? macOSVersion; + + static string RunProcess(string name, string arguments) + { + using var process = new Process() + { + StartInfo = new() + { + FileName = name, + Arguments = arguments, + RedirectStandardInput = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + process.Start(); + process.WaitForExit(); + + return process.StandardOutput.ReadToEnd(); + } + + public static bool IsMacOSVersionAtLeast(int major, int minor = 0, int build = 0) + { + if (!OperatingSystem.IsMacOS()) + { + return false; + } + + if (macOSVersion == null) + { + var versionString = RunProcess("/usr/bin/sw_vers", "") + .Replace("ProductVersion:", string.Empty) + .Replace(" ", string.Empty); + + macOSVersion = Version.Parse(versionString.Split(Environment.NewLine.ToCharArray())[0]); + } + + return macOSVersion >= new Version(major, minor, build); + } + + public static bool IsFreeBSDVersionAtLeast(int major, int minor, int build = 0, int revision = 0) + { + if (!OperatingSystem.IsFreeBSD()) + { + return false; + } + + if (freeBsdVersion == null) + { + var versionString = Environment.OSVersion.VersionString + .Replace("Unix", string.Empty) + .Replace("FreeBSD", string.Empty) + .Replace("-release", string.Empty) + .Replace(" ", string.Empty); + + freeBsdVersion = Version.Parse(versionString); + } + + return freeBsdVersion >= new Version(major, minor, build, revision); + } + + public static bool IsWindowsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + if (windowsVersion == null) + { + var input = RuntimeInformation.OSDescription + .Replace("Microsoft Windows", string.Empty) + .Replace(" ", string.Empty); + windowsVersion = Version.Parse(input); + } + + return windowsVersion >= new Version(major, minor, build, revision); + } + + public static bool IsAndroid() + { + if (!isAndroid.HasValue) + { + try + { + isAndroid = RunProcess("uname", "-o") + .Replace(" ", string.Empty) + .ToLower() + .Equals("android"); + } + catch + { + isAndroid = false; + } + } + + return isAndroid.Value; + } + + public static bool IsAndroidVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) + { + if (!IsAndroid()) + { + return false; + } + + if (androidVersion == null) + { + var result = RunProcess("getprop", "ro.build.version.release") + .Replace(" ", string.Empty); + + androidVersion = Version.Parse(result); + } + + return androidVersion >= new Version(major, minor, build, revision); + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/OperatingSystemPolyfill.cs b/src/Polyfill/OperatingSystemPolyfill.cs index 85e8170a..0911c465 100644 --- a/src/Polyfill/OperatingSystemPolyfill.cs +++ b/src/Polyfill/OperatingSystemPolyfill.cs @@ -1,396 +1,193 @@ // #pragma warning disable -namespace Polyfills; +#if !NET8_0_OR_GREATER && FeatureRuntimeInformation -#if FeatureRuntimeInformation +namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Runtime.Versioning; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] - -#if PolyPublic -public -#endif -static class OperatingSystemPolyfill +static partial class Polyfill { - #if !NET - - static string RunProcess(string name, string arguments) - { - using var process = new Process() - { - StartInfo = new() - { - FileName = name, - Arguments = arguments, - RedirectStandardInput = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true - } - }; - process.Start(); - process.WaitForExit(); - - return process.StandardOutput.ReadToEnd(); - } -#endif - - /// - /// Indicates whether the current application is running on the specified platform. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0 - public static bool IsOSPlatform(string platform) => -#if NET - OperatingSystem.IsOSPlatform(platform); -#else - RuntimeInformation.IsOSPlatform(OSPlatform.Create(platform)); -#endif - - /// - /// Checks if the operating system version is greater than or equal to the specified platform version. This method can be used to guard APIs that were added in the specified OS version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0 - public static bool IsOSPlatformVersionAtLeast(string platform, int major, int minor = 0, int build = 0, int revision = 0) => -#if NET - OperatingSystem.IsOSPlatformVersionAtLeast(platform, major, minor, build, revision); -#else - IsOSPlatform(platform) && - IsOsVersionAtLeast(major, minor, build, revision); -#endif - - /// - /// Indicates whether the current application is running on Windows. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0 - public static bool IsWindows() => -#if NET - OperatingSystem.IsWindows(); -#else - RuntimeInformation.IsOSPlatform(OSPlatform.Windows); -#endif - - /// - /// Checks if the Windows version (returned by RtlGetVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified Windows version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0 - public static bool IsWindowsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) - { -#if NET - return OperatingSystem.IsWindowsVersionAtLeast(major, minor, build, revision); -#else - if (!IsWindows()) - { - return false; - } - - if (windowsVersion == null) - { - var input = RuntimeInformation.OSDescription - .Replace("Microsoft Windows", string.Empty) - .Replace(" ", string.Empty); - windowsVersion = Version.Parse(input); - } - - return windowsVersion >= new Version(major, minor, build, revision); -#endif - } - -#if !NET - static Version? windowsVersion; -#endif - - /// - /// Indicates whether the current application is running on macOS. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0 - public static bool IsMacOS() => -#if NET - OperatingSystem.IsMacOS(); -#else - RuntimeInformation.IsOSPlatform(OSPlatform.OSX); -#endif - - /// - /// Indicates whether the current application is running on Mac Catalyst. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0 - public static bool IsMacCatalyst() => -#if NET6_0_OR_GREATER - OperatingSystem.IsMacCatalyst(); -#else - IsMacOS() || - IsIOS(); -#endif - - /// - /// Checks if the macOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified macOS version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0 - public static bool IsMacOSVersionAtLeast(int major, int minor = 0, int build = 0) - { -#if NET - return OperatingSystem.IsMacOSVersionAtLeast(major, minor, build); -#else - if (!IsMacOS()) - { - return false; - } - - if (macOSVersion == null) - { - var versionString = RunProcess("/usr/bin/sw_vers", "") - .Replace("ProductVersion:", string.Empty) - .Replace(" ", string.Empty); - - macOSVersion = Version.Parse(versionString.Split(Environment.NewLine.ToCharArray())[0]); - } - - return macOSVersion >= new Version(major, minor, build); -#endif - } - -#if !NET - static Version? macOSVersion; -#endif - - /// - /// Check for the Mac Catalyst version (iOS version as presented in Apple documentation) with a ≤ version comparison. Used to guard APIs that were added in the given Mac Catalyst release. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0 - public static bool IsMacCatalystVersionAtLeast(int major, int minor = 0, int build = 0) => -#if NET6_0_OR_GREATER - OperatingSystem.IsMacCatalystVersionAtLeast(major, minor, build); -#else - IsMacCatalyst() && - IsOsVersionAtLeast(major, minor, build); -#endif - - /// - /// Indicates whether the current application is running on Linux. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0 - public static bool IsLinux() => -#if NET - OperatingSystem.IsLinux(); -#else - RuntimeInformation.IsOSPlatform(OSPlatform.Linux); -#endif - - /// - /// Indicates whether the current application is running on FreeBSD. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0 - public static bool IsFreeBSD() => -#if NET - OperatingSystem.IsFreeBSD(); -#else - RuntimeInformation.OSDescription.ToLower().Contains("freebsd"); -#endif + static bool IsOsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) => + Environment.OSVersion.Version >= new Version(major, minor, build, revision); - /// - /// Checks if the FreeBSD version (returned by the Linux command uname) is greater than or equal to the specified version. - /// This method can be used to guard APIs that were added in the specified version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0 - public static bool IsFreeBSDVersionAtLeast(int major, int minor, int build = 0, int revision = 0) + extension(OperatingSystem) { -#if NET - return OperatingSystem.IsFreeBSDVersionAtLeast(major, minor, build, revision); -#else - if (!IsFreeBSD()) - { - return false; - } - - if (freeBsdVersion == null) - { - var versionString = Environment.OSVersion.VersionString - .Replace("Unix", string.Empty) - .Replace("FreeBSD", string.Empty) - .Replace("-release", string.Empty) - .Replace(" ", string.Empty); - - freeBsdVersion = Version.Parse(versionString); - } - - return freeBsdVersion >= new Version(major, minor, build, revision); -#endif - } - -#if !NET - static Version? freeBsdVersion; -#endif +#if !NET8_0_OR_GREATER - /// - /// Indicates whether the current application is running on iOS or MacCatalyst. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0 - public static bool IsIOS() - { -#if NET - return OperatingSystem.IsIOS(); -#else - var description = RuntimeInformation.OSDescription.ToLower(); - return description.Contains("ios") || - description.Contains("ipados") || - (description.Contains("iphone") && - description.Contains("os")); -#endif - } + /// + /// Indicates whether the current application is running as WASI. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0 + public static bool IsWasi() => + RuntimeInformation.FrameworkDescription.ToLower().Contains("wasi"); - /// - /// Checks if the iOS/MacCatalyst version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified iOS version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0 - public static bool IsIOSVersionAtLeast(int major, int minor = 0, int build = 0) => -#if NET - OperatingSystem.IsIOSVersionAtLeast(major, minor, build); -#else - IsIOS() && - IsOsVersionAtLeast(major, minor, build); #endif - /// - /// Indicates whether the current application is running on tvOS. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0 - public static bool IsTvOS() => -#if NET - OperatingSystem.IsTvOS(); -#else - RuntimeInformation.OSDescription.ToLower().Contains("tvos"); -#endif +#if !NET6_0_OR_GREATER - /// - /// Checks if the tvOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified tvOS version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0 - public static bool IsTvOSVersionAtLeast(int major, int minor = 0, int build = 0) => -#if NET - OperatingSystem.IsTvOSVersionAtLeast(major, minor, build); -#else - IsTvOS() && - IsOsVersionAtLeast(major, minor, build); -#endif + /// + /// Indicates whether the current application is running on Mac Catalyst. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalyst?view=net-10.0 + public static bool IsMacCatalyst() => + OperatingSystem.IsMacOS() || + OperatingSystem.IsIOS(); - /// - /// Indicates whether the current application is running on Android. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0 - public static bool IsAndroid() - { -#if NET - return OperatingSystem.IsAndroid(); -#else - if (!isAndroid.HasValue) - { - try - { - isAndroid = RunProcess("uname", "-o") - .Replace(" ", string.Empty) - .ToLower() - .Equals("android"); - } - catch - { - isAndroid = false; - } - } + /// + /// Check for the Mac Catalyst version (iOS version as presented in Apple documentation) with a ≤ version comparison. Used to guard APIs that were added in the given Mac Catalyst release. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismaccatalystversionatleast?view=net-10.0 + public static bool IsMacCatalystVersionAtLeast(int major, int minor = 0, int build = 0) => + IsMacCatalyst() && + IsOsVersionAtLeast(major, minor, build); - return isAndroid.Value; #endif - } #if !NET - static bool? isAndroid; -#endif - /// - /// Checks if the Android version (returned by the Linux command uname) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0 - public static bool IsAndroidVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) - { -#if NET - return OperatingSystem.IsAndroidVersionAtLeast(major, minor, build, revision); -#else - if (!IsAndroid()) + /// + /// Checks if the macOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified macOS version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacosversionatleast?view=net-10.0 + public static bool IsMacOSVersionAtLeast(int major, int minor = 0, int build = 0) => + OperatingSystemCache.IsMacOSVersionAtLeast(major, minor, build); + + /// + /// Checks if the FreeBSD version (returned by the Linux command uname) is greater than or equal to the specified version. + /// This method can be used to guard APIs that were added in the specified version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsdversionatleast?view=net-10.0 + public static bool IsFreeBSDVersionAtLeast(int major, int minor, int build = 0, int revision = 0) => + OperatingSystemCache.IsFreeBSDVersionAtLeast(major, minor, build, revision); + + /// + /// Indicates whether the current application is running on Android. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroid?view=net-10.0 + public static bool IsAndroid() => + OperatingSystemCache.IsAndroid(); + + /// + /// Checks if the Android version (returned by the Linux command uname) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isandroidversionatleast?view=net-10.0 + public static bool IsAndroidVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) => + OperatingSystemCache.IsAndroidVersionAtLeast(major, minor, build, revision); + + /// + /// Checks if the Windows version (returned by RtlGetVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified Windows version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindowsversionatleast?view=net-10.0 + public static bool IsWindowsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) => + OperatingSystemCache.IsWindowsVersionAtLeast(major, minor, build, revision); + + /// + /// Indicates whether the current application is running on the specified platform. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatform?view=net-10.0 + public static bool IsOSPlatform(string platform) => + RuntimeInformation.IsOSPlatform(OSPlatform.Create(platform)); + + /// + /// Checks if the operating system version is greater than or equal to the specified platform version. This method can be used to guard APIs that were added in the specified OS version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isosplatformversionatleast?view=net-10.0 + public static bool IsOSPlatformVersionAtLeast(string platform, int major, int minor = 0, int build = 0, int revision = 0) => + IsOSPlatform(platform) && + IsOsVersionAtLeast(major, minor, build, revision); + + /// + /// Indicates whether the current application is running on Windows. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswindows?view=net-10.0 + public static bool IsWindows() => + RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + + /// + /// Indicates whether the current application is running on macOS. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.ismacos?view=net-10.0 + public static bool IsMacOS() => + RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + + /// + /// Indicates whether the current application is running on iOS or MacCatalyst. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isios?view=net-10.0 + public static bool IsIOS() { - return false; + var description = RuntimeInformation.OSDescription.ToLower(); + return description.Contains("ios") || + description.Contains("ipados") || + (description.Contains("iphone") && + description.Contains("os")); } - if (androidVersion == null) - { - var result = RunProcess("getprop", "ro.build.version.release") - .Replace(" ", string.Empty); - - androidVersion = Version.Parse(result); - } + /// + /// Indicates whether the current application is running on Linux. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.islinux?view=net-10.0 + public static bool IsLinux() => + RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + + /// + /// Indicates whether the current application is running on FreeBSD. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isfreebsd?view=net-10.0 + public static bool IsFreeBSD() => + RuntimeInformation.OSDescription.ToLower().Contains("freebsd"); + + /// + /// Checks if the iOS/MacCatalyst version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified iOS version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isiosversionatleast?view=net-10.0 + public static bool IsIOSVersionAtLeast(int major, int minor = 0, int build = 0) => + IsIOS() && + IsOsVersionAtLeast(major, minor, build); + + /// + /// Checks if the tvOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified tvOS version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvosversionatleast?view=net-10.0 + public static bool IsTvOSVersionAtLeast(int major, int minor = 0, int build = 0) => + IsTvOS() && + IsOsVersionAtLeast(major, minor, build); + + /// + /// Indicates whether the current application is running on tvOS. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.istvos?view=net-10.0 + public static bool IsTvOS() => + RuntimeInformation.OSDescription.ToLower().Contains("tvos"); + + /// + /// Indicates whether the current application is running on watchOS. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0 + public static bool IsWatchOS() => + IsIOS() || + RuntimeInformation.OSDescription.ToLower().Contains("watchos"); + + /// + /// Checks if the watchOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified watchOS version. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0 + public static bool IsWatchOSVersionAtLeast(int major, int minor = 0, int build = 0) => + IsWatchOS() && + IsOsVersionAtLeast(major, minor, build); + + /// + /// Indicates whether the current application is running as WASM in a browser. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0 + public static bool IsBrowser() => + RuntimeInformation.FrameworkDescription.Contains(".NET WebAssembly"); - return androidVersion >= new Version(major, minor, build, revision); #endif } - -#if !NET - static Version? androidVersion; -#endif - - /// - /// Indicates whether the current application is running on watchOS. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchos?view=net-10.0 - public static bool IsWatchOS() => -#if NET - OperatingSystem.IsWatchOS(); -#else - IsIOS() || - RuntimeInformation.OSDescription.ToLower().Contains("watchos"); -#endif - - /// - /// Checks if the watchOS version (returned by libobjc.get_operatingSystemVersion) is greater than or equal to the specified version. This method can be used to guard APIs that were added in the specified watchOS version. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswatchosversionatleast?view=net-10.0 - public static bool IsWatchOSVersionAtLeast(int major, int minor = 0, int build = 0) => -#if NET - OperatingSystem.IsWatchOSVersionAtLeast(major, minor, build); -#else - IsWatchOS() && - IsOsVersionAtLeast(major, minor, build); -#endif - - /// - /// Indicates whether the current application is running as WASI. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.iswasi?view=net-10.0 - public static bool IsWasi() => -#if NET8_0_OR_GREATER - OperatingSystem.IsWasi(); -#else - RuntimeInformation.FrameworkDescription.ToLower().Contains("wasi"); -#endif - - /// - /// Indicates whether the current application is running as WASM in a browser. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.operatingsystem.isbrowser?view=net-10.0 - public static bool IsBrowser() => -#if NET - OperatingSystem.IsBrowser(); -#else - RuntimeInformation.FrameworkDescription.Contains(".NET WebAssembly"); -#endif - - static bool IsOsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) => - Environment.OSVersion.Version >= new Version(major, minor, build, revision); } - #endif \ No newline at end of file diff --git a/src/Polyfill/OverloadResolutionPriorityAttribute.cs b/src/Polyfill/OverloadResolutionPriorityAttribute.cs index f94dc26d..8c131126 100644 --- a/src/Polyfill/OverloadResolutionPriorityAttribute.cs +++ b/src/Polyfill/OverloadResolutionPriorityAttribute.cs @@ -18,6 +18,9 @@ namespace System.Runtime.CompilerServices; AttributeTargets.Constructor | AttributeTargets.Property, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.overloadresolutionpriorityattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/ParamCollectionAttribute.cs b/src/Polyfill/ParamCollectionAttribute.cs index 348b92f5..6d182246 100644 --- a/src/Polyfill/ParamCollectionAttribute.cs +++ b/src/Polyfill/ParamCollectionAttribute.cs @@ -14,6 +14,9 @@ namespace System.Runtime.CompilerServices; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.paramcollectionattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/PathPolyfill.cs b/src/Polyfill/PathPolyfill.cs index 84c2014b..2492593b 100644 --- a/src/Polyfill/PathPolyfill.cs +++ b/src/Polyfill/PathPolyfill.cs @@ -1,183 +1,146 @@ // #pragma warning disable +#if !NET9_0_OR_GREATER + namespace Polyfills; using System; using System.IO; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class PathPolyfill +static partial class Polyfill { + extension(Path) + { #if FeatureMemory - /// - /// Returns the directory information for the specified path represented by a character span. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char))) - public static ReadOnlySpan GetDirectoryName(ReadOnlySpan path) => -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - Path.GetDirectoryName(path); -#else - Path.GetDirectoryName(path.ToString()).AsSpan(); -#endif - - /// - /// Returns the file name and extension of a file path that is represented by a read-only character span. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char))) - public static ReadOnlySpan GetFileName(ReadOnlySpan path) => -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - Path.GetFileName(path); -#else - Path.GetFileName(path.ToString()).AsSpan(); -#endif - - /// - /// Returns the file name without the extension of a file path that is represented by a read-only character span. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char))) - public static ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path) => -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - Path.GetFileNameWithoutExtension(path); -#else - Path.GetFileNameWithoutExtension(path.ToString()).AsSpan(); -#endif - - /// - /// Determines whether the path represented by the specified character span includes a file name extension. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char))) - public static bool HasExtension(ReadOnlySpan path) => -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - Path.HasExtension(path); -#else - Path.HasExtension(path.ToString()); -#endif - - /// - /// Returns the extension of the given path. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char))) - public static ReadOnlySpan GetExtension(ReadOnlySpan path) => -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - Path.GetExtension(path); -#else - Path.GetExtension(path.ToString()).AsSpan(); -#endif - - /// - /// Combines a span of strings into a path. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string))) - public static string Combine(scoped ReadOnlySpan paths) => -#if NET9_0_OR_GREATER - Path.Combine(paths); -#else - Path.Combine(paths.ToArray()); +#if !NETSTANDARD2_1_OR_GREATER && !NETCOREAPP2_1_OR_GREATER + /// + /// Returns the directory information for the specified path represented by a character span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-10.0#system-io-path-getdirectoryname(system-readonlyspan((system-char))) + public static ReadOnlySpan GetDirectoryName(ReadOnlySpan path) => + Path.GetDirectoryName(path.ToString()).AsSpan(); + + /// + /// Returns the file name and extension of a file path that is represented by a read-only character span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-10.0#system-io-path-getfilename(system-readonlyspan((system-char))) + public static ReadOnlySpan GetFileName(ReadOnlySpan path) => + Path.GetFileName(path.ToString()).AsSpan(); + + /// + /// Returns the file name without the extension of a file path that is represented by a read-only character span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char))) + public static ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan path) => + Path.GetFileNameWithoutExtension(path.ToString()).AsSpan(); + + /// + /// Determines whether the path represented by the specified character span includes a file name extension. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension?view=net-10.0#system-io-path-getfilenamewithoutextension(system-readonlyspan((system-char))) + public static bool HasExtension(ReadOnlySpan path) => + Path.HasExtension(path.ToString()); + + /// + /// Returns the extension of the given path. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getextension?view=net-10.0#system-io-path-getextension(system-readonlyspan((system-char))) + public static ReadOnlySpan GetExtension(ReadOnlySpan path) => + Path.GetExtension(path.ToString()).AsSpan(); #endif - /// - /// Returns a value that indicates whether the path, specified as a read-only span, ends in a directory separator. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char))) - public static bool EndsInDirectorySeparator (ReadOnlySpan path) => -#if NETCOREAPP3_0_OR_GREATER - Path.EndsInDirectorySeparator(path); -#else - EndsInDirectorySeparator(path.ToString()); +#if !NET9_0_OR_GREATER + /// + /// Combines a span of strings into a path. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine?view=net-10.0#system-io-path-combine(system-readonlyspan((system-string))) + public static string Combine(scoped ReadOnlySpan paths) => + Path.Combine(paths.ToArray()); #endif - /// - /// Trims one trailing directory separator beyond the root of the specified path. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char))) - public static ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path) => -#if NETCOREAPP3_0_OR_GREATER - Path.TrimEndingDirectorySeparator(path); -#else - TrimEndingDirectorySeparator(path.ToString()).AsSpan(); +#if !NETCOREAPP3_0_OR_GREATER + /// + /// Returns a value that indicates whether the path, specified as a read-only span, ends in a directory separator. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-readonlyspan((system-char))) + public static bool EndsInDirectorySeparator (ReadOnlySpan path) => + EndsInDirectorySeparator(path.ToString()); + + /// + /// Trims one trailing directory separator beyond the root of the specified path. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-readonlyspan((system-char))) + public static ReadOnlySpan TrimEndingDirectorySeparator(ReadOnlySpan path) => + TrimEndingDirectorySeparator(path.ToString()).AsSpan(); #endif #endif - /// - /// Returns a value that indicates whether the specified path ends in a directory separator. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string) -#if NETCOREAPP3_0_OR_GREATER - public static bool EndsInDirectorySeparator(string path) => - Path.EndsInDirectorySeparator(path); -#else - public static bool EndsInDirectorySeparator(string path) - { - if (string.IsNullOrEmpty(path)) +#if !NETCOREAPP3_0_OR_GREATER + /// + /// Returns a value that indicates whether the specified path ends in a directory separator. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.endsindirectoryseparator?view=net-10.0#system-io-path-endsindirectoryseparator(system-string) + public static bool EndsInDirectorySeparator(string path) { - return false; - } + if (string.IsNullOrEmpty(path)) + { + return false; + } - return IsDirectorySeparator(path[path.Length-1]); - } -#endif + return IsDirectorySeparator(path[path.Length - 1]); + } - /// - /// Trims one trailing directory separator beyond the root of the specified path. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string) -#if NETCOREAPP3_0_OR_GREATER - public static string TrimEndingDirectorySeparator(string path) => - Path.TrimEndingDirectorySeparator(path); -#else - public static string TrimEndingDirectorySeparator(string path) - { - if (EndsInDirectorySeparator(path) && - !Path.IsPathRooted(path)) + /// + /// Trims one trailing directory separator beyond the root of the specified path. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.trimendingdirectoryseparator?view=net-10.0#system-io-path-trimendingdirectoryseparator(system-string) + public static string TrimEndingDirectorySeparator(string path) { - return path!.Substring(0, path.Length - 1); - } + if (EndsInDirectorySeparator(path) && + !Path.IsPathRooted(path)) + { + return path!.Substring(0, path.Length - 1); + } - return path; - } + return path; + } #endif - static bool IsDirectorySeparator(char c) => - c == Path.DirectorySeparatorChar || - c == Path.AltDirectorySeparatorChar; - - /// - /// Determines whether the specified file or directory exists. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0 -#if NET7_0_OR_GREATER - public static bool Exists(string? path) => - Path.Exists(path); -#else - public static bool Exists(string? path) - { - if (string.IsNullOrEmpty(path)) - { - return false; - } + static bool IsDirectorySeparator(char c) => + c == Path.DirectorySeparatorChar || + c == Path.AltDirectorySeparatorChar; - string? fullPath; - try - { - fullPath = Path.GetFullPath(path); - } - catch (Exception ex) - when (ex is ArgumentException or - IOException or - UnauthorizedAccessException) +#if !NET7_0_OR_GREATER + /// + /// Determines whether the specified file or directory exists. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.exists?view=net-10.0 + public static bool Exists(string? path) { - return false; + if (string.IsNullOrEmpty(path)) + { + return false; + } + + string? fullPath; + try + { + fullPath = Path.GetFullPath(path); + } + catch (Exception ex) + when (ex is ArgumentException or + IOException or + UnauthorizedAccessException) + { + return false; + } + + return File.Exists(fullPath) || Directory.Exists(fullPath); } - - return File.Exists(fullPath) || Directory.Exists(fullPath); - } #endif -} \ No newline at end of file + } +} + +#endif \ No newline at end of file diff --git a/src/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs b/src/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs index 5e22a5c1..196f060f 100644 --- a/src/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs @@ -13,6 +13,9 @@ namespace System.Runtime.Versioning; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs b/src/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs index 59c83b9f..ca51d51a 100644 --- a/src/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs @@ -33,6 +33,9 @@ namespace System.Runtime.Versioning; Targets.Struct, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs b/src/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs index 543b2b98..a47be488 100644 --- a/src/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs @@ -30,6 +30,9 @@ namespace System.Runtime.Versioning; Targets.Struct, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs b/src/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs index e32cb1ec..e3e4be1b 100644 --- a/src/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs @@ -23,6 +23,9 @@ namespace System.Runtime.Versioning; Targets.Property, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs b/src/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs index d2d21254..a50a81dc 100644 --- a/src/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs @@ -14,6 +14,9 @@ namespace System.Runtime.Versioning; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Assembly)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs b/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs index 603c9c2e..cf7812b0 100644 --- a/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs @@ -31,6 +31,9 @@ namespace System.Runtime.Versioning; Targets.Struct, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs b/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs index f5f1528d..bef4f576 100644 --- a/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs +++ b/src/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs @@ -25,6 +25,9 @@ namespace System.Runtime.Versioning; Targets.Property, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Polyfill.cs b/src/Polyfill/Polyfill.cs index 2c683a93..6116d60f 100644 --- a/src/Polyfill/Polyfill.cs +++ b/src/Polyfill/Polyfill.cs @@ -11,6 +11,9 @@ namespace Polyfills; [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Polyfill.nuspec b/src/Polyfill/Polyfill.nuspec index 672cfd56..1fd6e4db 100644 --- a/src/Polyfill/Polyfill.nuspec +++ b/src/Polyfill/Polyfill.nuspec @@ -17,8 +17,8 @@ - + $(DefineConstants);PolyPublic + + $(DefineConstants);PolyUseEmbeddedAttribute + $(DefineConstants);NETCOREAPP2X @@ -121,11 +124,17 @@ For example: $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask;FeatureRuntimeInformation;FeatureCompression $(DefineConstants);FeatureValueTuple;FeatureRuntimeInformation;FeatureCompression + + + + + + - + diff --git a/src/Polyfill/Polyfill_Delegate.cs b/src/Polyfill/Polyfill_Delegate.cs deleted file mode 100644 index c169847a..00000000 --- a/src/Polyfill/Polyfill_Delegate.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -#pragma warning disable - -namespace Polyfills; - -using System; -using System.Collections.Concurrent; -using System.Runtime.CompilerServices; - -static partial class Polyfill -{ - /// - /// Gets a value that indicates whether the Delegate has a single invocation target. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.hassingletarget?view=net-10.0 - public static bool HasSingleTarget(this Delegate target) => -#if NET9_0_OR_GREATER - target.HasSingleTarget; -#else - target.GetInvocationList().Length == 1; -#endif -} diff --git a/src/Polyfill/RandomNumberGeneratorPolyfill.cs b/src/Polyfill/RandomNumberGeneratorPolyfill.cs index ab3a78ab..5f4ab389 100644 --- a/src/Polyfill/RandomNumberGeneratorPolyfill.cs +++ b/src/Polyfill/RandomNumberGeneratorPolyfill.cs @@ -2,276 +2,245 @@ #pragma warning disable +#if !NET8_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class RandomNumberGeneratorPolyfill +static partial class Polyfill { - /// - ///Generates a random integer between a specified inclusive lower bound and a specified exclusive upper bound using a cryptographically strong random number generator. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32) - public static int GetInt32(int fromInclusive, int toExclusive) + extension(RandomNumberGenerator) { -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_0_OR_GREATER - return RandomNumberGenerator.GetInt32(fromInclusive, toExclusive); -#else - - if (fromInclusive >= toExclusive) +#if !NETSTANDARD2_1_OR_GREATER && !NETCOREAPP3_0_OR_GREATER + /// + ///Generates a random integer between a specified inclusive lower bound and a specified exclusive upper bound using a cryptographically strong random number generator. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32-system-int32) + public static int GetInt32(int fromInclusive, int toExclusive) { - throw new ArgumentException("toExclusive must be greater than fromInclusive."); - } + if (fromInclusive >= toExclusive) + { + throw new ArgumentException("toExclusive must be greater than fromInclusive."); + } - // The total possible range is [0, 4,294,967,295). - // Subtract one to account for zero being an actual possibility. - var range = (uint)toExclusive - (uint)fromInclusive - 1; + // The total possible range is [0, 4,294,967,295). + // Subtract one to account for zero being an actual possibility. + var range = (uint) toExclusive - (uint) fromInclusive - 1; - // If there is only one possible choice, nothing random will actually happen, so return - // the only possibility. - if (range == 0) - { - return fromInclusive; - } + // If there is only one possible choice, nothing random will actually happen, so return + // the only possibility. + if (range == 0) + { + return fromInclusive; + } - // Create a mask for the bits that we care about for the range. The other bits will be - // masked away. - uint mask = range; - mask |= mask >> 1; - mask |= mask >> 2; - mask |= mask >> 4; - mask |= mask >> 8; - mask |= mask >> 16; + // Create a mask for the bits that we care about for the range. The other bits will be + // masked away. + uint mask = range; + mask |= mask >> 1; + mask |= mask >> 2; + mask |= mask >> 4; + mask |= mask >> 8; + mask |= mask >> 16; - uint value; - var bytes = new byte[4]; + uint value; + var bytes = new byte[4]; - using var generator = RandomNumberGenerator.Create(); - do - { - generator.GetBytes(bytes); - value = BitConverter.ToUInt32(bytes, 0) & mask; - } while (value >= range); + using var generator = RandomNumberGenerator.Create(); + do + { + generator.GetBytes(bytes); + value = BitConverter.ToUInt32(bytes, 0) & mask; + } while (value >= range); - return (int)(fromInclusive + value); -#endif - } + return (int) (fromInclusive + value); + } - /// - /// Generates a random integer between 0 (inclusive) and a specified exclusive upper bound using a cryptographically strong random number generator. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32) - public static int GetInt32(int toExclusive) - { -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_0_OR_GREATER - return RandomNumberGenerator.GetInt32(toExclusive); -#else - if (toExclusive <= 0) + /// + /// Generates a random integer between 0 (inclusive) and a specified exclusive upper bound using a cryptographically strong random number generator. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getint32?view=net-10.0#system-security-cryptography-randomnumbergenerator-getint32(system-int32) + public static int GetInt32(int toExclusive) { - throw new ArgumentOutOfRangeException(nameof(toExclusive), "Value must be positive and non-zero."); - } + if (toExclusive <= 0) + { + throw new ArgumentOutOfRangeException(nameof(toExclusive), "Value must be positive and non-zero."); + } - return GetInt32(0, toExclusive); + return GetInt32(0, toExclusive); + } #endif - } - /// - /// Creates an array of bytes with a cryptographically strong random sequence of values. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32) - public static byte[] GetBytes(int count) - { -#if NET6_0_OR_GREATER - return RandomNumberGenerator.GetBytes(count); -#else - if (count < 0) +#if !NET6_0_OR_GREATER + /// + /// Creates an array of bytes with a cryptographically strong random sequence of values. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getbytes?view=net-10.0#system-security-cryptography-randomnumbergenerator-getbytes(system-int32) + public static byte[] GetBytes(int count) { - throw new ArgumentOutOfRangeException(nameof(count), "Value is negative."); - } + if (count < 0) + { + throw new ArgumentOutOfRangeException(nameof(count), "Value is negative."); + } - using var generator = RandomNumberGenerator.Create(); - var bytes = new byte[count]; - generator.GetBytes(bytes); - return bytes; + using var generator = RandomNumberGenerator.Create(); + var bytes = new byte[count]; + generator.GetBytes(bytes); + return bytes; + } #endif - } #if FeatureMemory - /// - /// Fills a span with cryptographically strong random bytes. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0 - public static void Fill(Span data) - { -#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER - RandomNumberGenerator.Fill(data); -#else - using var generator = RandomNumberGenerator.Create(); - var bytes = new byte[data.Length]; - generator.GetBytes(bytes); - bytes.CopyTo(data); +#if !NETSTANDARD2_1_OR_GREATER && !NETCOREAPP2_1_OR_GREATER + /// + /// Fills a span with cryptographically strong random bytes. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.fill?view=net-10.0 + public static void Fill(Span data) + { + using var generator = RandomNumberGenerator.Create(); + var bytes = new byte[data.Length]; + generator.GetBytes(bytes); + bytes.CopyTo(data); + } #endif - } - /// - /// Fills the elements of a specified span with items chosen at random from the provided set of choices. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0))) - public static void GetItems(ReadOnlySpan choices, Span destination) - { -#if NET8_0_OR_GREATER - RandomNumberGenerator.GetItems(choices, destination); -#else - if (choices.IsEmpty) +#if !NET8_0_OR_GREATER + /// + /// Fills the elements of a specified span with items chosen at random from the provided set of choices. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-span((-0))) + public static void GetItems(ReadOnlySpan choices, Span destination) { - throw new ArgumentException("Empty span", nameof(choices)); + if (choices.IsEmpty) + { + throw new ArgumentException("Empty span", nameof(choices)); + } + + for (var i = 0; i < destination.Length; i++) + { + destination[i] = choices[RandomNumberGenerator.GetInt32(choices.Length)]; + } } - for (var i = 0; i < destination.Length; i++) + /// + /// Creates an array populated with items chosen at random from choices. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32) + public static T[] GetItems(ReadOnlySpan choices, int length) { - destination[i] = choices[GetInt32(choices.Length)]; + var result = new T[length]; + GetItems(choices, result); + return result; } -#endif - } - - /// - /// Creates an array populated with items chosen at random from choices. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getitems?view=net-10.0#system-security-cryptography-randomnumbergenerator-getitems-1(system-readonlyspan((-0))-system-int32) - public static T[] GetItems(ReadOnlySpan choices, int length) - { -#if NET8_0_OR_GREATER - return RandomNumberGenerator.GetItems(choices, length); -#else - var result = new T[length]; - GetItems(choices, result); - return result; -#endif - } - /// - /// Creates a string populated with characters chosen at random from choices. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0 - public static string GetString(ReadOnlySpan choices, int length) - { -#if NET8_0_OR_GREATER - return RandomNumberGenerator.GetString(choices, length); -#else - var result = new char[length]; - GetItems(choices, result); - return new(result); -#endif - } - - /// - /// Fills a buffer with cryptographically random hexadecimal characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0 - public static void GetHexString(Span destination, bool lowercase = false) - { -#if NET8_0_OR_GREATER - RandomNumberGenerator.GetHexString(destination, lowercase); -#else - if (destination.IsEmpty) + /// + /// Creates a string populated with characters chosen at random from choices. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0 + public static string GetString(ReadOnlySpan choices, int length) { - return; + var result = new char[length]; + GetItems(choices, result); + return new(result); } - // Each byte gives two hex chars - var byteCount = (destination.Length + 1) / 2; - Span bytes = stackalloc byte[byteCount]; - Fill(bytes); + /// + /// Fills a buffer with cryptographically random hexadecimal characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.getstring?view=net-10.0 + public static void GetHexString(Span destination, bool lowercase = false) + { + if (destination.IsEmpty) + { + return; + } - ReadOnlySpan hex = lowercase - ? "0123456789abcdef".AsSpan() - : "0123456789ABCDEF".AsSpan(); + // Each byte gives two hex chars + var byteCount = (destination.Length + 1) / 2; + Span bytes = stackalloc byte[byteCount]; + RandomNumberGenerator.Fill(bytes); - var charIndex = 0; - for (var i = 0; i < bytes.Length && charIndex < destination.Length; i++) - { - var b = bytes[i]; - destination[charIndex++] = hex[b >> 4]; - if (charIndex < destination.Length) + ReadOnlySpan hex = lowercase + ? "0123456789abcdef".AsSpan() + : "0123456789ABCDEF".AsSpan(); + + var charIndex = 0; + for (var i = 0; i < bytes.Length && charIndex < destination.Length; i++) { - destination[charIndex++] = hex[b & 0xF]; + var b = bytes[i]; + destination[charIndex++] = hex[b >> 4]; + if (charIndex < destination.Length) + { + destination[charIndex++] = hex[b & 0xF]; + } } } -#endif - } - - /// - /// Performs an in-place shuffle of a span using cryptographically random number generation. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0 - public static void Shuffle(Span values) - { -#if NET8_0_OR_GREATER - RandomNumberGenerator.Shuffle(values); -#else - var n = values.Length; - for (int i = 0; i < n - 1; i++) + /// + /// Performs an in-place shuffle of a span using cryptographically random number generation. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.shuffle?view=net-10.0 + public static void Shuffle(Span values) { - var j = GetInt32(i, n); + var n = values.Length; - if (i != j) + for (int i = 0; i < n - 1; i++) { - var temp = values[i]; - values[i] = values[j]; - values[j] = temp; + var j = RandomNumberGenerator.GetInt32(i, n); + + if (i != j) + { + var temp = values[i]; + values[i] = values[j]; + values[j] = temp; + } } } #endif - } #endif - /// - /// Creates a string filled with cryptographically random hexadecimal characters. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean) - public static string GetHexString(int stringLength, bool lowercase = false) - { -#if NET8_0_OR_GREATER - return RandomNumberGenerator.GetHexString(stringLength, lowercase); -#else - if (stringLength == 0) +#if !NET8_0_OR_GREATER + /// + /// Creates a string filled with cryptographically random hexadecimal characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator.gethexstring?view=net-10.0#system-security-cryptography-randomnumbergenerator-gethexstring(system-int32-system-boolean) + public static string GetHexString(int stringLength, bool lowercase = false) { - return string.Empty; - } + if (stringLength == 0) + { + return string.Empty; + } - if (stringLength < 0) - { - throw new ArgumentOutOfRangeException(nameof(stringLength), "Value is negative."); - } + if (stringLength < 0) + { + throw new ArgumentOutOfRangeException(nameof(stringLength), "Value is negative."); + } - var byteCount = (stringLength + 1) / 2; - var bytes = GetBytes(byteCount); + var byteCount = (stringLength + 1) / 2; + var bytes = RandomNumberGenerator.GetBytes(byteCount); - var hexChars = new char[stringLength]; - var hexAlphabet = lowercase ? "0123456789abcdef" : "0123456789ABCDEF"; - var charIndex = 0; - for (var i = 0; i < bytes.Length && charIndex < stringLength; i++) - { - var b = bytes[i]; - hexChars[charIndex++] = hexAlphabet[b >> 4]; - if (charIndex < stringLength) + var hexChars = new char[stringLength]; + var hexAlphabet = lowercase ? "0123456789abcdef" : "0123456789ABCDEF"; + var charIndex = 0; + for (var i = 0; i < bytes.Length && charIndex < stringLength; i++) { - hexChars[charIndex++] = hexAlphabet[b & 0xF]; + var b = bytes[i]; + hexChars[charIndex++] = hexAlphabet[b >> 4]; + if (charIndex < stringLength) + { + hexChars[charIndex++] = hexAlphabet[b & 0xF]; + } } - } - return new(hexChars); + return new(hexChars); + } #endif } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/src/Polyfill/RandomPolyfill.cs b/src/Polyfill/RandomPolyfill.cs index 78091503..9202b5c8 100644 --- a/src/Polyfill/RandomPolyfill.cs +++ b/src/Polyfill/RandomPolyfill.cs @@ -1,30 +1,17 @@ // #pragma warning disable +#if !NET6_0_OR_GREATER + namespace Polyfills; using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class RandomPolyfill +static partial class Polyfill { - /// - /// Provides a thread-safe Random instance that may be used concurrently from any thread. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-10.0 - public static Random Shared { get; } = -#if NET6_0_OR_GREATER - Random.Shared; -#else - new ThreadSafeRandom(); + static ThreadSafeRandom threadSafeRandom = new ThreadSafeRandom(); sealed class ThreadSafeRandom : Random { @@ -43,5 +30,14 @@ sealed class ThreadSafeRandom : Random public override double NextDouble() => LocalRandom.NextDouble(); protected override double Sample() => throw new NotSupportedException(); } -#endif -} \ No newline at end of file + + extension(Random) + { + /// + /// Provides a thread-safe Random instance that may be used concurrently from any thread. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-10.0 + public static Random Shared => threadSafeRandom; + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/Regex/Polyfill_Regex.cs b/src/Polyfill/Regex/Polyfill_Regex.cs index 6ccdc590..e216a764 100644 --- a/src/Polyfill/Regex/Polyfill_Regex.cs +++ b/src/Polyfill/Regex/Polyfill_Regex.cs @@ -28,14 +28,14 @@ public static bool IsMatch(this Regex target, ReadOnlySpan input) => /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. /// //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))) - public static ValueMatchEnumerator EnumerateMatches (this Regex target, ReadOnlySpan input) => + public static ValueMatchEnumerator EnumerateMatches(this Regex target, ReadOnlySpan input) => new(target, input, target.RightToLeft ? input.Length : 0); /// /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. /// //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-int32) - public static ValueMatchEnumerator EnumerateMatches (this Regex target, ReadOnlySpan input, int startat) => + public static ValueMatchEnumerator EnumerateMatches(this Regex target, ReadOnlySpan input, int startat) => new(target, input, startat); } #endif \ No newline at end of file diff --git a/src/Polyfill/Regex/RegexCache.cs b/src/Polyfill/Regex/RegexCache.cs index 3f5252cc..110a4f2d 100644 --- a/src/Polyfill/Regex/RegexCache.cs +++ b/src/Polyfill/Regex/RegexCache.cs @@ -16,6 +16,9 @@ namespace System.Text.RegularExpressions; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif // https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Cache.cs /// Cache used to store Regex instances used by the static methods on Regex. internal sealed class RegexCache diff --git a/src/Polyfill/Regex/RegexPolyfill.cs b/src/Polyfill/Regex/RegexPolyfill.cs index ee6fccb0..1004e395 100644 --- a/src/Polyfill/Regex/RegexPolyfill.cs +++ b/src/Polyfill/Regex/RegexPolyfill.cs @@ -1,6 +1,7 @@ // #pragma warning disable +#if !NET7_0_OR_GREATER namespace Polyfills; using System; @@ -16,78 +17,55 @@ namespace Polyfills; #endif #endif -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif - static class RegexPolyfill +static partial class Polyfill { + extension(Regex) + { #if FeatureMemory - /// - /// Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options and time-out interval. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan) - public static bool IsMatch(ReadOnlySpan input, string pattern, RegexOptions options, TimeSpan timeout) => -#if NET7_0_OR_GREATER - Regex.IsMatch(input, pattern, options, timeout); -#else - Regex.IsMatch(input.ToString(), pattern, options, timeout); -#endif +#if !NET7_0_OR_GREATER + /// + /// Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options and time-out interval. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan) + public static bool IsMatch(ReadOnlySpan input, string pattern, RegexOptions options, TimeSpan timeout) => + Regex.IsMatch(input.ToString(), pattern, options, timeout); - /// - /// Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions) - public static bool IsMatch(ReadOnlySpan input, string pattern, RegexOptions options) => -#if NET7_0_OR_GREATER - Regex.IsMatch(input, pattern, options); -#else - Regex.IsMatch(input.ToString(), pattern, options); -#endif + /// + /// Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions) + public static bool IsMatch(ReadOnlySpan input, string pattern, RegexOptions options) => + Regex.IsMatch(input.ToString(), pattern, options); - /// - /// Indicates whether the specified regular expression finds a match in the specified input span. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string) - public static bool IsMatch(ReadOnlySpan input, string pattern) => -#if NET7_0_OR_GREATER - Regex.IsMatch(input, pattern); -#else - Regex.IsMatch(input.ToString(), pattern); -#endif + /// + /// Indicates whether the specified regular expression finds a match in the specified input span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch?view=net-10.0#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string) + public static bool IsMatch(ReadOnlySpan input, string pattern) => + Regex.IsMatch(input.ToString(), pattern); - /// - /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string) - public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern) => -#if NET7_0_OR_GREATER - Regex.EnumerateMatches(input, pattern); -#else - RegexCache.GetOrAdd(pattern).EnumerateMatches(input); -#endif + /// + /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string) + public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern) => + RegexCache.GetOrAdd(pattern).EnumerateMatches(input); - /// - /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan) - public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern, RegexOptions options, TimeSpan timeout) => -#if NET7_0_OR_GREATER - Regex.EnumerateMatches(input, pattern, options, timeout); -#else - RegexCache.GetOrAdd(pattern, options, timeout).EnumerateMatches(input); -#endif + /// + /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions-system-timespan) + public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern, RegexOptions options, TimeSpan timeout) => + RegexCache.GetOrAdd(pattern, options, timeout).EnumerateMatches(input); - /// - /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions) - public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern, RegexOptions options) => -#if NET7_0_OR_GREATER - Regex.EnumerateMatches(input, pattern, options); -#else - RegexCache.GetOrAdd(pattern, options, TimeSpan.MaxValue).EnumerateMatches(input); + /// + /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches?view=net-10.0#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string-system-text-regularexpressions-regexoptions) + public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern, RegexOptions options) => + RegexCache.GetOrAdd(pattern, options, TimeSpan.MaxValue).EnumerateMatches(input); #endif #endif + } } +#endif \ No newline at end of file diff --git a/src/Polyfill/Regex/ValueMatch.cs b/src/Polyfill/Regex/ValueMatch.cs index c3a8569c..f669588a 100644 --- a/src/Polyfill/Regex/ValueMatch.cs +++ b/src/Polyfill/Regex/ValueMatch.cs @@ -16,6 +16,9 @@ namespace System.Text.RegularExpressions; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Regex/ValueMatchEnumerator.cs b/src/Polyfill/Regex/ValueMatchEnumerator.cs index 4f06af5e..dd091a33 100644 --- a/src/Polyfill/Regex/ValueMatchEnumerator.cs +++ b/src/Polyfill/Regex/ValueMatchEnumerator.cs @@ -17,6 +17,9 @@ namespace System.Text.RegularExpressions; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/RequiredMemberAttribute.cs b/src/Polyfill/RequiredMemberAttribute.cs index 7d25b392..e11f2c5f 100644 --- a/src/Polyfill/RequiredMemberAttribute.cs +++ b/src/Polyfill/RequiredMemberAttribute.cs @@ -21,6 +21,9 @@ namespace System.Runtime.CompilerServices; Targets.Field | Targets.Property, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif @@ -30,4 +33,4 @@ sealed class RequiredMemberAttribute : #else using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(RequiredMemberAttribute))] -#endif \ No newline at end of file +#endif diff --git a/src/Polyfill/RequiresPreviewFeaturesAttribute.cs b/src/Polyfill/RequiresPreviewFeaturesAttribute.cs index 355f59c4..bbae4f37 100644 --- a/src/Polyfill/RequiresPreviewFeaturesAttribute.cs +++ b/src/Polyfill/RequiresPreviewFeaturesAttribute.cs @@ -23,6 +23,9 @@ namespace System.Runtime.Versioning; AttributeTargets.Field | AttributeTargets.Event, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif [ExcludeFromCodeCoverage] [DebuggerNonUserCode] //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.requirespreviewfeaturesattribute?view=net-10.0 diff --git a/src/Polyfill/SHA256Polyfill.cs b/src/Polyfill/SHA256Polyfill.cs index 0e0bc2de..5a75c252 100644 --- a/src/Polyfill/SHA256Polyfill.cs +++ b/src/Polyfill/SHA256Polyfill.cs @@ -1,6 +1,8 @@ // #pragma warning disable +#if !NET7_0_OR_GREATER + namespace Polyfills; using System.Threading.Tasks; @@ -13,141 +15,138 @@ namespace Polyfills; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif static class SHA256Polyfill { - /// - /// Computes the hash of data using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte()) - public static byte[] HashData(byte[] source) + extension(SHA256) { -#if NET - return SHA256.HashData(source); -#else - using var hasher = SHA256.Create(); - return hasher.ComputeHash(source); -#endif - } +#if !NET + + /// + /// Computes the hash of data using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0#system-security-cryptography-sha256-hashdata(system-byte()) + public static byte[] HashData(byte[] source) + { + using var hasher = SHA256.Create(); + return hasher.ComputeHash(source); + } - /// - /// Computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream) - public static byte[] HashData(Stream source) - { -#if NET7_0_OR_GREATER - return SHA256.HashData(source); -#else - using var hasher = SHA256.Create(); - return hasher.ComputeHash(source); #endif - } -#if FeatureValueTask - /// - /// Asynchronously computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken) - public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) - { -#if NET7_0_OR_GREATER - return SHA256.HashDataAsync(source, cancellationToken); -#else - using var hasher = SHA256.Create(); - return new(hasher.ComputeHash(source)); +#if !NET7_0_OR_GREATER + + /// + /// Computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream) + public static byte[] HashData(Stream source) + { + using var hasher = SHA256.Create(); + return hasher.ComputeHash(source); + } + #endif - } + +#if FeatureValueTask && !NET7_0_OR_GREATER + /// + /// Asynchronously computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-threading-cancellationtoken) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) + { + using var hasher = SHA256.Create(); + return new(hasher.ComputeHash(source)); + } #endif #if FeatureMemory - /// - /// Computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))) - public static byte[] HashData(ReadOnlySpan source) - { -#if NET - return SHA256.HashData(source); -#else - using var hasher = SHA256.Create(); - return hasher.ComputeHash(source.ToArray()); -#endif - } - /// - /// Computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte))) - public static int HashData(Stream source, Span destination) - { -#if NET7_0_OR_GREATER - return SHA256.HashData(source, destination); -#else - var hash = HashData(source); - hash.CopyTo(destination); - return hash.Length; -#endif - } +#if !NET7_0_OR_GREATER + + /// + /// Computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-io-stream-system-span((system-byte))) + public static int HashData(Stream source, Span destination) + { + var hash = HashData(source); + hash.CopyTo(destination); + return hash.Length; + } -#if FeatureValueTask - /// - /// Asynchronously computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken) - public static ValueTask HashDataAsync(Stream source, Memory destination, CancellationToken cancellationToken = default) - { -#if NET7_0_OR_GREATER - return SHA256.HashDataAsync(source, destination, cancellationToken); -#else - cancellationToken.ThrowIfCancellationRequested(); - var hash = HashData(source); - hash.CopyTo(destination); - return new(hash.Length); -#endif - } #endif - /// - /// Computes the hash of a stream using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte))) - public static int HashData(ReadOnlySpan source, Span destination) - { -#if NET - return SHA256.HashData(source, destination); -#else - var hash = HashData(source); - hash.CopyTo(destination); - return hash.Length; +#if !NET + + /// + /// Computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))) + public static byte[] HashData(ReadOnlySpan source) + { + using var hasher = SHA256.Create(); + return hasher.ComputeHash(source.ToArray()); + } + #endif - } - /// - /// Attempts to compute the hash of data using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0 - public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) - { -#if NET - return SHA256.TryHashData(source, destination, out bytesWritten); -#else - using var hasher = SHA256.Create(); - var hash = hasher.ComputeHash(source.ToArray()); +#if FeatureValueTask && !NET7_0_OR_GREATER - if (destination.Length < hash.Length) + /// + /// Asynchronously computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdataasync?view=net-10.0?system-security-cryptography-sha256-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken) + public static ValueTask HashDataAsync(Stream source, Memory destination, CancellationToken cancellationToken = default) { - bytesWritten = 0; - return false; + cancellationToken.ThrowIfCancellationRequested(); + var hash = HashData(source); + hash.CopyTo(destination); + return new(hash.Length); } - hash.CopyTo(destination); - bytesWritten = hash.Length; - return true; #endif - } +#if !NET + + /// + /// Computes the hash of a stream using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-10.0?system-security-cryptography-sha256-hashdata(system-readonlyspan((system-byte))-system-span((system-byte))) + public static int HashData(ReadOnlySpan source, Span destination) + { + var hash = HashData(source); + hash.CopyTo(destination); + return hash.Length; + } + + /// + /// Attempts to compute the hash of data using the SHA-256 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.tryhashdata?view=net-10.0 + public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) + { + using var hasher = SHA256.Create(); + var hash = hasher.ComputeHash(source.ToArray()); + + if (destination.Length < hash.Length) + { + bytesWritten = 0; + return false; + } + + hash.CopyTo(destination); + bytesWritten = hash.Length; + return true; + } + +#endif #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/SHA512Polyfill.cs b/src/Polyfill/SHA512Polyfill.cs index 578db47c..7562b924 100644 --- a/src/Polyfill/SHA512Polyfill.cs +++ b/src/Polyfill/SHA512Polyfill.cs @@ -1,154 +1,143 @@ // #pragma warning disable +#if !NET7_0_OR_GREATER + namespace Polyfills; using System.Threading.Tasks; using System.Threading; using System; using System.IO; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static class SHA512Polyfill +static partial class Polyfill { - /// - /// Computes the hash of data using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte()) - public static byte[] HashData(byte[] source) + extension(SHA512) { -#if NET - return SHA512.HashData(source); -#else - using var hasher = SHA512.Create(); - return hasher.ComputeHash(source); -#endif - } +#if !NET + + /// + /// Computes the hash of data using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0#system-security-cryptography-sha512-hashdata(system-byte()) + public static byte[] HashData(byte[] source) + { + using var hasher = SHA512.Create(); + return hasher.ComputeHash(source); + } - /// - /// Computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream) - public static byte[] HashData(Stream source) - { -#if NET7_0_OR_GREATER - return SHA512.HashData(source); -#else - using var hasher = SHA512.Create(); - return hasher.ComputeHash(source); #endif - } -#if FeatureValueTask - /// - /// Asynchronously computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken) - public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) - { -#if NET7_0_OR_GREATER - return SHA512.HashDataAsync(source, cancellationToken); -#else - cancellationToken.ThrowIfCancellationRequested(); - using var hasher = SHA512.Create(); - return new(hasher.ComputeHash(source)); +#if !NET7_0_OR_GREATER + + /// + /// Computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream) + public static byte[] HashData(Stream source) + { + using var hasher = SHA512.Create(); + return hasher.ComputeHash(source); + } + #endif - } + +#if FeatureValueTask && !NET7_0_OR_GREATER + + /// + /// Asynchronously computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-threading-cancellationtoken) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + using var hasher = SHA512.Create(); + return new(hasher.ComputeHash(source)); + } + #endif #if FeatureMemory - /// - /// Computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))) - public static byte[] HashData(ReadOnlySpan source) - { -#if NET - return SHA512.HashData(source); -#else - using var hasher = SHA512.Create(); - return hasher.ComputeHash(source.ToArray()); -#endif - } - /// - /// Computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte))) - public static int HashData(Stream source, Span destination) - { -#if NET7_0_OR_GREATER - return SHA512.HashData(source, destination); -#else - var hash = HashData(source); - hash.CopyTo(destination); - return hash.Length; -#endif - } +#if !NET + + /// + /// Computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))) + public static byte[] HashData(ReadOnlySpan source) + { + using var hasher = SHA512.Create(); + return hasher.ComputeHash(source.ToArray()); + } + + /// + /// Attempts to compute the hash of data using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0 + public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) + { + using var hasher = SHA512.Create(); + var hash = hasher.ComputeHash(source.ToArray()); + + if (destination.Length < hash.Length) + { + bytesWritten = 0; + return false; + } + + hash.CopyTo(destination); + bytesWritten = hash.Length; + return true; + } + + /// + /// Computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte))) + public static int HashData(ReadOnlySpan source, Span destination) + { + var hash = HashData(source); + hash.CopyTo(destination); + return hash.Length; + } -#if FeatureValueTask - /// - /// Asynchronously computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken) - public static ValueTask HashDataAsync(Stream source, Memory destination, CancellationToken cancellationToken = default) - { -#if NET7_0_OR_GREATER - return SHA512.HashDataAsync(source, destination, cancellationToken); -#else - cancellationToken.ThrowIfCancellationRequested(); - var hash = HashData(source); - hash.CopyTo(destination); - return new(hash.Length); -#endif - } #endif - /// - /// Computes the hash of a stream using the SHA-512 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-readonlyspan((system-byte))-system-span((system-byte))) - public static int HashData(ReadOnlySpan source, Span destination) - { -#if NET - return SHA512.HashData(source, destination); -#else - var hash = HashData(source); - hash.CopyTo(destination); - return hash.Length; +#if !NET7_0_OR_GREATER + + /// + /// Computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdata?view=net-10.0?system-security-cryptography-sha512-hashdata(system-io-stream-system-span((system-byte))) + public static int HashData(Stream source, Span destination) + { + var hash = HashData(source); + hash.CopyTo(destination); + return hash.Length; + } + #endif - } - /// - /// Attempts to compute the hash of data using the SHA-256 algorithm. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.tryhashdata?view=net-10.0 - public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) - { -#if NET - return SHA512.TryHashData(source, destination, out bytesWritten); -#else - using var hasher = SHA512.Create(); - var hash = hasher.ComputeHash(source.ToArray()); +#if FeatureValueTask && !NET7_0_OR_GREATER - if (destination.Length < hash.Length) + /// + /// Asynchronously computes the hash of a stream using the SHA-512 algorithm. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha512.hashdataasync?view=net-10.0?system-security-cryptography-sha512-hashdataasync(system-io-stream-system-memory((system-byte))-system-threading-cancellationtoken) + public static ValueTask HashDataAsync(Stream source, Memory destination, CancellationToken cancellationToken = default) { - bytesWritten = 0; - return false; + cancellationToken.ThrowIfCancellationRequested(); + var hash = HashData(source); + hash.CopyTo(destination); + return new(hash.Length); + } - hash.CopyTo(destination); - bytesWritten = hash.Length; - return true; #endif - } #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/SetsRequiredMembersAttribute.cs b/src/Polyfill/SetsRequiredMembersAttribute.cs index 3c9a6927..2c0c7eda 100644 --- a/src/Polyfill/SetsRequiredMembersAttribute.cs +++ b/src/Polyfill/SetsRequiredMembersAttribute.cs @@ -12,6 +12,9 @@ namespace System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Constructor)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif @@ -20,4 +23,4 @@ sealed class SetsRequiredMembersAttribute : #else using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute))] -#endif \ No newline at end of file +#endif diff --git a/src/Polyfill/SkipLocalsInitAttribute.cs b/src/Polyfill/SkipLocalsInitAttribute.cs index df8a6347..9a9cc0fe 100644 --- a/src/Polyfill/SkipLocalsInitAttribute.cs +++ b/src/Polyfill/SkipLocalsInitAttribute.cs @@ -26,6 +26,9 @@ namespace System.Runtime.CompilerServices; Targets.Property | Targets.Event, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.skiplocalsinitattribute?view=net-10.0 #if PolyPublic public @@ -35,4 +38,4 @@ sealed class SkipLocalsInitAttribute : #else using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(SkipLocalsInitAttribute))] -#endif \ No newline at end of file +#endif diff --git a/src/Polyfill/SpanLineEnumerator.cs b/src/Polyfill/SpanLineEnumerator.cs index 7e5a6589..d07d26b5 100644 --- a/src/Polyfill/SpanLineEnumerator.cs +++ b/src/Polyfill/SpanLineEnumerator.cs @@ -17,6 +17,9 @@ namespace System.Text; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.spanlineenumerator?view=net-10.0 +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/StackTraceHiddenAttribute.cs b/src/Polyfill/StackTraceHiddenAttribute.cs index 1f1ceec0..34746e47 100644 --- a/src/Polyfill/StackTraceHiddenAttribute.cs +++ b/src/Polyfill/StackTraceHiddenAttribute.cs @@ -20,6 +20,9 @@ namespace System.Diagnostics; Targets.Constructor | Targets.Struct, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs b/src/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs index 56927bbd..e49ada18 100644 --- a/src/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs +++ b/src/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs @@ -18,6 +18,9 @@ namespace System.Text; [InterpolatedStringHandler] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs b/src/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs index 48783cbe..98b21e14 100644 --- a/src/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs +++ b/src/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs @@ -18,6 +18,9 @@ namespace System.Runtime.CompilerServices; [InterpolatedStringHandler] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.defaultinterpolatedstringhandler?view=net-10.0 #if PolyPublic @@ -136,7 +139,7 @@ public void AppendFormatted(T value) if (typeof(T).IsEnum) { int charsWritten; - while (!EnumPolyfill.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten)) + while (!Enum.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten)) { Grow(); } @@ -187,7 +190,7 @@ public void AppendFormatted(T value, string? format) if (typeof(T).IsEnum) { int charsWritten; - while (!EnumPolyfill.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten, formatSpan)) + while (!Enum.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten, formatSpan)) { Grow(); } @@ -431,7 +434,7 @@ void GrowThenCopySpan(scoped ReadOnlySpan value) void GrowCore(uint requiredMinCapacity) { uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint) _chars.Length * 2, StringMaxLength)); - int arraySize = (int) MathPolyfill.Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue); + int arraySize = (int) Math.Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue); char[] newArray = ArrayPool.Shared.Rent(arraySize); _chars.Slice(0, _pos).CopyTo(newArray); diff --git a/src/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs b/src/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs index e0a032a6..5cc33493 100644 --- a/src/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs +++ b/src/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs @@ -14,6 +14,9 @@ namespace System.Runtime.CompilerServices; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.interpolatedstringhandlerargumentattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs b/src/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs index 31ffee14..01345ef7 100644 --- a/src/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs +++ b/src/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs @@ -19,6 +19,9 @@ namespace System.Runtime.CompilerServices; validOn: Targets.Class | Targets.Struct, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/StringPolyfill.cs b/src/Polyfill/StringPolyfill.cs index 39034fa7..b095e26e 100644 --- a/src/Polyfill/StringPolyfill.cs +++ b/src/Polyfill/StringPolyfill.cs @@ -1,227 +1,223 @@ // #pragma warning disable +#if !NET9_0_OR_GREATER + namespace Polyfills; using System; using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -[ExcludeFromCodeCoverage] -[DebuggerNonUserCode] -#if PolyPublic -public -#endif -static partial class StringPolyfill +static partial class Polyfill { - /// - /// Concatenates an array of strings, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()) - public static string Join(char separator, params string?[] values) => -#if NETSTANDARD2_0 || NETFRAMEWORK -#if AllowUnsafeBlocks && FeatureMemory - Join(separator, new ReadOnlySpan(values)); -#else - string.Join(new(separator, 1), values); -#endif -#else - string.Join(separator, values); -#endif + extension(string) + { +#if FeatureMemory - /// - /// Concatenates the string representations of an array of objects, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object()) - public static string Join(char separator, params object?[] values) => -#if NETSTANDARD2_0 || NETFRAMEWORK - string.Join(new(separator, 1), values); -#else - string.Join(separator, values); -#endif +#if !NET9_0_OR_GREATER -#if FeatureMemory - /// - /// Concatenates the string representations of a span of objects, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object))) - public static string Join(char separator, scoped ReadOnlySpan values) => -#if NET9_0_OR_GREATER - string.Join(separator, values); -#else - Join(separator, values.ToArray()); -#endif + /// + /// Concatenates the string representations of a span of objects, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-object))) + public static string Join(char separator, scoped ReadOnlySpan values) => + Join(separator, values.ToArray()); - /// - /// Concatenates a span of strings, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string))) - public static string Join(char separator, scoped ReadOnlySpan values) - { - if (values.Length == 0) + /// + /// Concatenates a span of strings, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-readonlyspan((system-string))) + public static string Join(char separator, scoped ReadOnlySpan values) { - return string.Empty; - } + if (values.Length == 0) + { + return string.Empty; + } - if (values.Length == 1) - { - return values[0] ?? string.Empty; - } + if (values.Length == 1) + { + return values[0] ?? string.Empty; + } -#if NET9_0_OR_GREATER - return string.Join(separator, values); -#elif AllowUnsafeBlocks - var length = 0; +#if AllowUnsafeBlocks + var length = 0; - foreach (var value in values) - { - length += 1; - if (value != null) + foreach (var value in values) { - length += value.Length; + length += 1; + if (value != null) + { + length += value.Length; + } } - } - length -= 1; + length -= 1; - var result = new string(separator, length); + var result = new string(separator, length); - unsafe - { - fixed (char* strPtr = result) + unsafe { - var span = new Span(strPtr, length); - - for (var index = 0; index < values.Length; index++) + fixed (char* strPtr = result) { - if (index > 0) + var span = new Span(strPtr, length); + + for (var index = 0; index < values.Length; index++) { - span = span.Slice(1); - } + if (index > 0) + { + span = span.Slice(1); + } - var value = values[index]; + var value = values[index]; - value.CopyTo(span); + value.CopyTo(span); - span = span.Slice(value.Length); + span = span.Slice(value.Length); + } } } - } - - return result; -#else - return Join(separator, values.ToArray()); -#endif - } - /// - /// Concatenates the string representations of a span of objects, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object))) - public static string Join(string? separator, scoped ReadOnlySpan values) => -#if NET9_0_OR_GREATER - string.Join(separator, values); + return result; #else - string.Join(separator, values.ToArray()); + return Join(separator, values.ToArray()); #endif - - /// - /// Concatenates a span of strings, using the specified separator between each member. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string))) - public static string Join(string? separator, scoped ReadOnlySpan values) - { - if (values.Length == 0) - { - return string.Empty; } - if (values.Length == 1) + /// + /// Concatenates a span of strings, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-string))) + public static string Join(string? separator, scoped ReadOnlySpan values) { - return values[0] ?? string.Empty; - } + if (values.Length == 0) + { + return string.Empty; + } + + if (values.Length == 1) + { + return values[0] ?? string.Empty; + } -#if NET9_0_OR_GREATER - return string.Join(separator, values); -#elif AllowUnsafeBlocks - separator ??= string.Empty; +#if AllowUnsafeBlocks + separator ??= string.Empty; - var length = 0; + var length = 0; - foreach (var value in values) - { - length += separator.Length; - if (value != null) + foreach (var value in values) { - length += value.Length; + length += separator.Length; + if (value != null) + { + length += value.Length; + } } - } - length -= separator.Length; + length -= separator.Length; - var result = new string('\0', length); + var result = new string('\0', length); - unsafe - { - fixed (char* strPtr = result) + unsafe { - var span = new Span(strPtr, length); - - for (var index = 0; index < values.Length; index++) + fixed (char* strPtr = result) { - if (index > 0 && - separator.Length > 0) + var span = new Span(strPtr, length); + + for (var index = 0; index < values.Length; index++) { - separator.CopyTo(span); + if (index > 0 && + separator.Length > 0) + { + separator.CopyTo(span); - span = span.Slice(separator.Length); - } + span = span.Slice(separator.Length); + } - var value = values[index]; + var value = values[index]; - if (value is null) - { - continue; - } + if (value is null) + { + continue; + } - value.CopyTo(span); + value.CopyTo(span); - span = span.Slice(value.Length); + span = span.Slice(value.Length); + } } } - } - return result; + return result; #else - return string.Join(separator, values.ToArray()); + return string.Join(separator, values.ToArray()); #endif - } + } +#endif + +#if !NETCOREAPP3_0_OR_GREATER + /// + /// Returns the hash code for the provided read-only character span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char))) + public static int GetHashCode(ReadOnlySpan value) => + value.ToString().GetHashCode(); + + /// + /// Returns the hash code for the provided read-only character span using the specified rules. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode?view=net-10.0#system-string-gethashcode(system-readonlyspan((system-char))-system-stringcomparison) + public static int GetHashCode(ReadOnlySpan value,StringComparison comparisonType) => + value.ToString().GetHashCode(comparisonType); +#endif +#endif + +#if !NET9_0_OR_GREATER && FeatureMemory + /// + /// Concatenates the string representations of a span of objects, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-string-system-readonlyspan((system-object))) + public static string Join(string? separator, scoped ReadOnlySpan values) => + string.Join(separator, values.ToArray()); #endif - /// - /// Concatenates the specified elements of a string array, using the specified separator between each element. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32) - public static string Join(char separator, string?[] value, int startIndex, int count) => #if NETSTANDARD2_0 || NETFRAMEWORK + + /// + /// Concatenates an array of strings, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()) + public static string Join(char separator, params string?[] values) => #if AllowUnsafeBlocks && FeatureMemory - Join(separator, new ReadOnlySpan(value, startIndex, count)); + Join(separator, new ReadOnlySpan(values)); #else - string.Join(new(separator, 1), value, startIndex, count); + string.Join(new(separator, 1), values); #endif + + /// + /// Concatenates the string representations of an array of objects, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-object()) + public static string Join(char separator, params object?[] values) => + string.Join(new(separator, 1), values); + + /// + /// Concatenates the specified elements of a string array, using the specified separator between each element. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join(system-char-system-string()-system-int32-system-int32) + public static string Join(char separator, string?[] value, int startIndex, int count) => +#if AllowUnsafeBlocks && FeatureMemory + Join(separator, new ReadOnlySpan(value, startIndex, count)); #else - string.Join(separator, value, startIndex, count); + string.Join(new(separator, 1), value, startIndex, count); #endif - /// - /// Concatenates the specified elements of a string array, using the specified separator between each element. - /// - //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0))) - public static string Join(char separator, IEnumerable values) => -#if NETSTANDARD2_0 || NETFRAMEWORK - string.Join(new(separator, 1), values); -#else - string.Join(separator, values); + /// + /// Concatenates the specified elements of a string array, using the specified separator between each element. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=net-10.0#system-string-join-1(system-char-system-collections-generic-ienumerable((-0))) + public static string Join(char separator, IEnumerable values) => + string.Join(new(separator, 1), values); #endif -} \ No newline at end of file + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/StringSyntaxAttribute.cs b/src/Polyfill/StringSyntaxAttribute.cs index 304cd882..dd0bfbf9 100644 --- a/src/Polyfill/StringSyntaxAttribute.cs +++ b/src/Polyfill/StringSyntaxAttribute.cs @@ -17,6 +17,9 @@ namespace System.Diagnostics.CodeAnalysis; validOn: Targets.Parameter | Targets.Field | Targets.Property)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/SuppressGCTransitionAttribute.cs b/src/Polyfill/SuppressGCTransitionAttribute.cs index e371ca37..9c40d121 100644 --- a/src/Polyfill/SuppressGCTransitionAttribute.cs +++ b/src/Polyfill/SuppressGCTransitionAttribute.cs @@ -17,6 +17,9 @@ namespace System.Runtime.InteropServices; validOn: AttributeTargets.Method, Inherited = false)] //Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.suppressgctransitionattribute?view=net-10.0 +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/TaskCompletionSource.cs b/src/Polyfill/TaskCompletionSource.cs index 5b60c35f..8e88844b 100644 --- a/src/Polyfill/TaskCompletionSource.cs +++ b/src/Polyfill/TaskCompletionSource.cs @@ -20,6 +20,9 @@ namespace System.Diagnostics; [ExcludeFromCodeCoverage] [DebuggerNonUserCode] //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource?view=net-10.0 +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Trimming/DynamicDependencyAttribute.cs b/src/Polyfill/Trimming/DynamicDependencyAttribute.cs index 8ebbef41..85720365 100644 --- a/src/Polyfill/Trimming/DynamicDependencyAttribute.cs +++ b/src/Polyfill/Trimming/DynamicDependencyAttribute.cs @@ -19,6 +19,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Field | Targets.Method, AllowMultiple = true, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs b/src/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs index 9d7ed510..99cc794b 100644 --- a/src/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs +++ b/src/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs @@ -12,6 +12,9 @@ namespace System.Diagnostics.CodeAnalysis; /// bitwise combination of its member values. /// [Flags] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs b/src/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs index 2775dfec..07cd2e44 100644 --- a/src/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs +++ b/src/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs @@ -24,6 +24,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.ReturnValue | Targets.Struct, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.dynamicallyaccessedmembersattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs b/src/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs index bbf3e441..47ca0351 100644 --- a/src/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs +++ b/src/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs @@ -20,6 +20,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Constructor | Targets.Class, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif @@ -33,6 +36,11 @@ sealed class RequiresDynamicCodeAttribute : public RequiresDynamicCodeAttribute(string message) => Message = message; + /// + /// When set to true, indicates that the annotation should not apply to static members. + /// + public bool ExcludeStatics { get; set; } + /// /// Gets a message that contains information about the usage of dynamic code. /// diff --git a/src/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs b/src/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs index c8d7bb7f..9c937f04 100644 --- a/src/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs +++ b/src/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs @@ -20,6 +20,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Constructor | Targets.Class, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.requiresunreferencedcodeattribute #if PolyPublic public @@ -33,6 +36,11 @@ sealed class RequiresUnreferencedCodeAttribute : public RequiresUnreferencedCodeAttribute(string message) => Message = message; + /// + /// When set to true, indicates that the annotation should not apply to static members. + /// + public bool ExcludeStatics { get; set; } + /// /// Gets a message that contains information about the usage of unreferenced code. /// diff --git a/src/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs b/src/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs index 32a6ed0d..e6908bcd 100644 --- a/src/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs +++ b/src/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs @@ -17,6 +17,9 @@ namespace System.Diagnostics.CodeAnalysis; validOn: AttributeTargets.All, Inherited = false, AllowMultiple = true)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.unconditionalsuppressmessageattribute?view=net-10.0 #if PolyPublic public diff --git a/src/Polyfill/UnixFileMode.cs b/src/Polyfill/UnixFileMode.cs index a22f03ae..0841b0d1 100644 --- a/src/Polyfill/UnixFileMode.cs +++ b/src/Polyfill/UnixFileMode.cs @@ -13,6 +13,9 @@ namespace System.IO; /// This enumeration supports a bitwise combination of its member values. /// [Flags] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/UnmanagedCallersOnlyAttribute.cs b/src/Polyfill/UnmanagedCallersOnlyAttribute.cs index dd4c2af3..1e56bbc6 100644 --- a/src/Polyfill/UnmanagedCallersOnlyAttribute.cs +++ b/src/Polyfill/UnmanagedCallersOnlyAttribute.cs @@ -20,6 +20,9 @@ namespace System.Runtime.InteropServices; [AttributeUsage( AttributeTargets.Method, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/UnreachableException.cs b/src/Polyfill/UnreachableException.cs index 500f04be..22e926d5 100644 --- a/src/Polyfill/UnreachableException.cs +++ b/src/Polyfill/UnreachableException.cs @@ -17,6 +17,9 @@ namespace System.Diagnostics; /// [ExcludeFromCodeCoverage] [DebuggerNonUserCode] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/UnscopedRefAttribute.cs b/src/Polyfill/UnscopedRefAttribute.cs index 2ec4cd16..23868576 100644 --- a/src/Polyfill/UnscopedRefAttribute.cs +++ b/src/Polyfill/UnscopedRefAttribute.cs @@ -19,6 +19,9 @@ namespace System.Diagnostics.CodeAnalysis; Targets.Property | Targets.Parameter, Inherited = false)] +#if PolyUseEmbeddedAttribute +[global::Microsoft.CodeAnalysis.EmbeddedAttribute] +#endif #if PolyPublic public #endif diff --git a/src/Polyfill/XDocumentPolyfill.cs b/src/Polyfill/XDocumentPolyfill.cs new file mode 100644 index 00000000..3d7ea977 --- /dev/null +++ b/src/Polyfill/XDocumentPolyfill.cs @@ -0,0 +1,59 @@ +// + +#pragma warning disable + +#if !NETCOREAPP2_0_OR_GREATER && !NETSTANDARD2 + +namespace Polyfills; + +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System; +using System.IO; +using System.Diagnostics; +using System.Xml.Linq; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static partial class XDocumentPolyfill +{ + extension(XDocument) + { + /// + /// Asynchronously creates a new XDocument and initializes its underlying XML tree using the specified stream, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XDocument.Load(stream, options)); + } + + /// + /// Asynchronously creates a new XDocument and initializes its underlying XML tree using the specified text reader, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XDocument.Load(textReader, options)); + } + + /// + /// Asynchronously creates a new XDocument and initializes its underlying XML tree using the specified text reader, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.loadasync?view=net-10.0#system-xml-linq-xdocument-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XDocument.Load(reader, options)); + } + + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/XElementPolyfill.cs b/src/Polyfill/XElementPolyfill.cs new file mode 100644 index 00000000..2398290f --- /dev/null +++ b/src/Polyfill/XElementPolyfill.cs @@ -0,0 +1,51 @@ +// + +#pragma warning disable + +#if !NETCOREAPP2_0_OR_GREATER && !NETSTANDARD2 + +namespace Polyfills; + +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System; +using System.IO; +using System.Xml.Linq; + +static partial class Polyfill +{ + extension(XElement) + { + /// + /// Asynchronously creates a new XElement and initializes its underlying XML tree using the specified stream, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-stream-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XElement.Load(stream, options)); + } + + /// + /// Asynchronously creates a new XElement and initializes its underlying XML tree using the specified text reader, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-io-textreader-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XElement.Load(textReader, options)); + } + + /// + /// Asynchronously creates a new XElement and initializes its underlying XML tree using the specified text reader, optionally preserving white space. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement.loadasync?view=net-10.0#system-xml-linq-xelement-loadasync(system-xml-xmlreader-system-xml-linq-loadoptions-system-threading-cancellationtoken) + public static Task LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(XElement.Load(reader, options)); + } + } +} +#endif \ No newline at end of file diff --git a/src/Polyfill/ZipArchiveEntryPolyfill.cs b/src/Polyfill/ZipArchiveEntryPolyfill.cs new file mode 100644 index 00000000..e82f8845 --- /dev/null +++ b/src/Polyfill/ZipArchiveEntryPolyfill.cs @@ -0,0 +1,34 @@ +// + +using System.IO.Compression; + +#pragma warning disable + +#if FeatureCompression && ((NETFRAMEWORK && !NET472_OR_GREATER) || NETSTANDARD2_0) +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static partial class ZipArchiveEntryPolyfill +{ + extension(ZipArchiveEntry target) + { + /// + /// OS and application specific file attributes. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.externalattributes?view=net-10.0 + public int ExternalAttributes + { + get => 0; + set { } + } + } +} +#endif \ No newline at end of file diff --git a/src/PolyfillTrimmed.slnf b/src/PolyfillTrimmed.slnf index c45c2605..96a85d22 100644 --- a/src/PolyfillTrimmed.slnf +++ b/src/PolyfillTrimmed.slnf @@ -1,6 +1,6 @@ { "solution": { - "path": "Polyfill.sln", + "path": "Polyfill.slnx", "projects": [ "ConsumeTrimmed\\ConsumeTrimmed.csproj" ] diff --git a/src/PolyfillUwp.sln b/src/PolyfillUwp.sln deleted file mode 100644 index 70e6855c..00000000 --- a/src/PolyfillUwp.sln +++ /dev/null @@ -1,44 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.1.32120.378 -MinimumVisualStudioVersion = 16.0.29201.188 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9A6C4741-C83D-4E05-A62F-8049F65B9B6C}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .gitattributes = .gitattributes - ..\.gitignore = ..\.gitignore - appveyor.yml = appveyor.yml - Directory.Build.props = Directory.Build.props - Directory.Packages.props = Directory.Packages.props - global.json = global.json - mdsnippets.json = mdsnippets.json - ..\readme.md = ..\readme.md - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Polyfill", "Polyfill\Polyfill.csproj", "{698FB675-3480-4107-8CAE-51452C6138CE}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumeUwp", "ConsumeUwp\ConsumeUwp.csproj", "{1F7D9DD0-A69C-40FB-B578-655679FF3143}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {698FB675-3480-4107-8CAE-51452C6138CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {698FB675-3480-4107-8CAE-51452C6138CE}.Release|Any CPU.Build.0 = Release|Any CPU - {1F7D9DD0-A69C-40FB-B578-655679FF3143}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1F7D9DD0-A69C-40FB-B578-655679FF3143}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1F7D9DD0-A69C-40FB-B578-655679FF3143}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1F7D9DD0-A69C-40FB-B578-655679FF3143}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {B0B94980-5385-4EC6-A0EE-C9A191DDFC05} - EndGlobalSection -EndGlobal diff --git a/src/PolyfillUwp.slnx b/src/PolyfillUwp.slnx new file mode 100644 index 00000000..f2bd404e --- /dev/null +++ b/src/PolyfillUwp.slnx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/src/PolyfillUwp.sln.DotSettings b/src/PolyfillUwp.slnx.DotSettings similarity index 100% rename from src/PolyfillUwp.sln.DotSettings rename to src/PolyfillUwp.slnx.DotSettings diff --git a/src/PublicTests/XDocumentPolyfillTests.cs b/src/PublicTests/XDocumentPolyfillTests.cs new file mode 100644 index 00000000..ba8b1477 --- /dev/null +++ b/src/PublicTests/XDocumentPolyfillTests.cs @@ -0,0 +1,57 @@ +[TestFixture] +public class XDocumentPolyfillTests +{ + const string XmlContent = "value"; + + [Test] + public async Task LoadAsync_Stream_ReturnsXDocument() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(XmlContent)); + var result = await XDocument.LoadAsync(stream, LoadOptions.None, CancellationToken.None); + Assert.AreEqual("root", result.Root?.Name.LocalName); + Assert.AreEqual("value", result.Root?.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_TextReader_ReturnsXDocument() + { + using var reader = new StringReader(XmlContent); + var result = await XDocument.LoadAsync(reader, LoadOptions.None, CancellationToken.None); + Assert.AreEqual("root", result.Root?.Name.LocalName); + Assert.AreEqual("value", result.Root?.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_XmlReader_ReturnsXDocument() + { + using var stringReader = new StringReader(XmlContent); + using var xmlReader = XmlReader.Create( + stringReader, + new() + { + Async = true + }); + var result = await XDocument.LoadAsync(xmlReader, LoadOptions.None, CancellationToken.None); + Assert.AreEqual("root", result.Root?.Name.LocalName); + Assert.AreEqual("value", result.Root?.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_Stream_CancellationRequested_Throws() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(XmlContent)); + var tokenSource = new CancelSource(); + tokenSource.Cancel(); + Exception? exception = null; + try + { + await XDocument.LoadAsync(stream, LoadOptions.None, tokenSource.Token); + } + catch (Exception e) + { + exception = e; + } + + Assert.IsNotNull(exception); + } +} \ No newline at end of file diff --git a/src/TestIncludes.targets b/src/TestIncludes.targets index 2297e3a8..0de54486 100644 --- a/src/TestIncludes.targets +++ b/src/TestIncludes.targets @@ -1,33 +1,33 @@ - + Pollyfill\%(Filename).cs - - Pollyfill\Guard\%(RecursiveDir)%(Filename).cs + + Pollyfill\Ensure\%(RecursiveDir)%(Filename).cs - + Pollyfill\Nullable\%(RecursiveDir)%(Filename).cs - + Pollyfill\Nullability\%(RecursiveDir)%(Filename).cs - + Pollyfill\IndexRange\%(RecursiveDir)%(Filename).cs - + Pollyfill\StringInterpolation\%(RecursiveDir)%(Filename).cs - + Pollyfill\Trimming\%(RecursiveDir)%(Filename).cs - + Pollyfill\PlatformCompatibility\%(RecursiveDir)%(Filename).cs - + Pollyfill\Numbers\%(RecursiveDir)%(Filename).cs - + Pollyfill\Regex\%(RecursiveDir)%(Filename).cs diff --git a/src/Tests/CallerArgumentExpressionUsage.cs b/src/Tests/CallerArgumentExpressionUsage.cs index 59af5459..7a71e376 100644 --- a/src/Tests/CallerArgumentExpressionUsage.cs +++ b/src/Tests/CallerArgumentExpressionUsage.cs @@ -2,11 +2,11 @@ static class FileUtil { - public static void FileExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + public static void FileExists(string path, [CallerArgumentExpression("path")] string name = "") { if (!File.Exists(path)) { - throw new ArgumentException($"File not found. Path: {path}", argumentName); + throw new ArgumentException($"File not found. Path: {path}", name); } } } diff --git a/src/Tests/CollectionBuilderAttributeTests.cs b/src/Tests/CollectionBuilderAttributeTests.cs index 47b5e62e..9a031688 100644 --- a/src/Tests/CollectionBuilderAttributeTests.cs +++ b/src/Tests/CollectionBuilderAttributeTests.cs @@ -15,4 +15,4 @@ public class MyCollection(ReadOnlySpan initValues) public static MyCollection Create(ReadOnlySpan values) => new(values); } -} +} \ No newline at end of file diff --git a/src/Tests/ConstantExpectedTests.cs b/src/Tests/ConstantExpectedTests.cs index 651aa91c..ce614b2d 100644 --- a/src/Tests/ConstantExpectedTests.cs +++ b/src/Tests/ConstantExpectedTests.cs @@ -1,3 +1,5 @@ +// ReSharper disable IncorrectConstantExpectedAnnotation +#pragma warning disable CA1856 [TestFixture] public class ConstantExpectedTests { diff --git a/src/Tests/ConvertPolyfillTests.cs b/src/Tests/ConvertPolyfillTests.cs index 9eeaf718..11edb6f4 100644 --- a/src/Tests/ConvertPolyfillTests.cs +++ b/src/Tests/ConvertPolyfillTests.cs @@ -5,12 +5,12 @@ public class ConvertPolyfillTests public void ToHexString_ValidInput() { byte[] input = [0x0F, 0xA3, 0x5C]; - var result = ConvertPolyfill.ToHexString(input, 0, input.Length); + var result = Convert.ToHexString(input, 0, input.Length); Assert.AreEqual("0FA35C", result); - result = ConvertPolyfill.ToHexString(input); + result = Convert.ToHexString(input); Assert.AreEqual("0FA35C", result); #if FeatureMemory - result = ConvertPolyfill.ToHexString(input.AsSpan()); + result = Convert.ToHexString(input.AsSpan()); Assert.AreEqual("0FA35C", result); #endif } @@ -19,7 +19,7 @@ public void ToHexString_ValidInput() public void ToHexString_OffsetAndLength() { byte[] input = [0x0F, 0xA3, 0x5C, 0x7E]; - var result = ConvertPolyfill.ToHexString(input, 1, 2); + var result = Convert.ToHexString(input, 1, 2); Assert.AreEqual("A35C", result); } @@ -27,33 +27,33 @@ public void ToHexString_OffsetAndLength() public void ToHexString_NegativeLength_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexString(input, 0, -1)); + Assert.Throws(() => Convert.ToHexString(input, 0, -1)); } [Test] public void ToHexString_NegativeOffset_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexString(input, -1, 2)); + Assert.Throws(() => Convert.ToHexString(input, -1, 2)); } [Test] public void ToHexString_OffsetPlusLengthExceedsArray_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexString(input, 2, 2)); + Assert.Throws(() => Convert.ToHexString(input, 2, 2)); } [Test] public void ToHexStringLower_ValidInput() { byte[] input = [0x0F, 0xA3, 0x5C]; - var result = ConvertPolyfill.ToHexString(input, 0, input.Length); + var result = Convert.ToHexString(input, 0, input.Length); Assert.AreEqual("0FA35C", result); - result = ConvertPolyfill.ToHexStringLower(input); + result = Convert.ToHexStringLower(input); Assert.AreEqual("0fa35c", result); #if FeatureMemory - result = ConvertPolyfill.ToHexStringLower(input.AsSpan()); + result = Convert.ToHexStringLower(input.AsSpan()); Assert.AreEqual("0fa35c", result); #endif } @@ -62,7 +62,7 @@ public void ToHexStringLower_ValidInput() public void ToHexStringLower_OffsetAndLength() { byte[] input = [0x0F, 0xA3, 0x5C, 0x7E]; - var result = ConvertPolyfill.ToHexStringLower(input, 1, 2); + var result = Convert.ToHexStringLower(input, 1, 2); Assert.AreEqual("a35c", result); } @@ -70,21 +70,21 @@ public void ToHexStringLower_OffsetAndLength() public void ToHexStringLower_NegativeLength_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexStringLower(input, 0, -1)); + Assert.Throws(() => Convert.ToHexStringLower(input, 0, -1)); } [Test] public void ToHexStringLower_NegativeOffset_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexStringLower(input, -1, 2)); + Assert.Throws(() => Convert.ToHexStringLower(input, -1, 2)); } [Test] public void ToHexStringLower_OffsetPlusLengthExceedsArray_ThrowsException() { byte[] input = [0x0F, 0xA3, 0x5C]; - Assert.Throws(() => ConvertPolyfill.ToHexStringLower(input, 2, 2)); + Assert.Throws(() => Convert.ToHexStringLower(input, 2, 2)); } #if FeatureMemory @@ -94,7 +94,7 @@ public void TryToHexString_ValidInput() { ReadOnlySpan source = [0x0F, 0xA3, 0x5C]; Span destination = stackalloc char[6]; - var result = ConvertPolyfill.TryToHexString(source, destination, out var charsWritten); + var result = Convert.TryToHexString(source, destination, out var charsWritten); Assert.IsTrue(result); Assert.AreEqual(6, charsWritten); Assert.AreEqual("0FA35C", destination.Slice(0, charsWritten).ToString()); @@ -105,7 +105,7 @@ public void TryToHexString_BufferTooSmall() { ReadOnlySpan source = [0x0F, 0xA3, 0x5C]; Span destination = stackalloc char[4]; - var result = ConvertPolyfill.TryToHexString(source, destination, out var charsWritten); + var result = Convert.TryToHexString(source, destination, out var charsWritten); Assert.IsFalse(result); Assert.AreEqual(0, charsWritten); } @@ -115,7 +115,7 @@ public void TryToHexString_EmptySource() { var source = ReadOnlySpan.Empty; Span destination = []; - var result = ConvertPolyfill.TryToHexString(source, destination, out var charsWritten); + var result = Convert.TryToHexString(source, destination, out var charsWritten); Assert.IsTrue(result); Assert.AreEqual(0, charsWritten); } @@ -125,7 +125,7 @@ public void TryToHexStringLower_ValidInput() { ReadOnlySpan source = [0x0F, 0xA3, 0x5C]; Span destination = stackalloc char[6]; - var result = ConvertPolyfill.TryToHexStringLower(source, destination, out var charsWritten); + var result = Convert.TryToHexStringLower(source, destination, out var charsWritten); Assert.IsTrue(result); Assert.AreEqual(6, charsWritten); Assert.AreEqual("0fa35c", destination.Slice(0, charsWritten).ToString()); @@ -136,7 +136,7 @@ public void TryToHexStringLower_BufferTooSmall() { ReadOnlySpan source = [0x0F, 0xA3, 0x5C]; Span destination = stackalloc char[4]; - var result = ConvertPolyfill.TryToHexStringLower(source, destination, out var charsWritten); + var result = Convert.TryToHexStringLower(source, destination, out var charsWritten); Assert.IsFalse(result); Assert.AreEqual(0, charsWritten); } @@ -146,7 +146,7 @@ public void TryToHexStringLower_EmptySource() { var source = ReadOnlySpan.Empty; Span destination = []; - var result = ConvertPolyfill.TryToHexStringLower(source, destination, out var charsWritten); + var result = Convert.TryToHexStringLower(source, destination, out var charsWritten); Assert.IsTrue(result); Assert.AreEqual(0, charsWritten); } @@ -157,7 +157,7 @@ public void TryToHexStringLower_EmptySource() public void FromHexString_ValidInput() { var hexString = "0FA35C"; - var result = ConvertPolyfill.FromHexString(hexString); + var result = Convert.FromHexString(hexString); CollectionAssert.AreEqual(new byte[] { 0x0F, 0xA3, 0x5C }, result); } @@ -165,7 +165,7 @@ public void FromHexString_ValidInput() public void FromHexString_EmptyString() { var hexString = string.Empty; - var result = ConvertPolyfill.FromHexString(hexString); + var result = Convert.FromHexString(hexString); CollectionAssert.AreEqual(Array.Empty(), result); } @@ -173,21 +173,21 @@ public void FromHexString_EmptyString() public void FromHexString_InvalidCharacter_ThrowsFormatException() { var hexString = "0FA3ZC"; - Assert.Throws(() => ConvertPolyfill.FromHexString(hexString)); + Assert.Throws(() => Convert.FromHexString(hexString)); } [Test] public void FromHexString_OddLength_ThrowsFormatException() { var hexString = "0FA3C"; - Assert.Throws(() => ConvertPolyfill.FromHexString(hexString)); + Assert.Throws(() => Convert.FromHexString(hexString)); } [Test] public void FromHexString_LowercaseInput() { var hexString = "0fa35c"; - var result = ConvertPolyfill.FromHexString(hexString); + var result = Convert.FromHexString(hexString); CollectionAssert.AreEqual(new byte[] { 0x0F, 0xA3, 0x5C }, result); } } \ No newline at end of file diff --git a/src/Tests/EnsureTests.cs b/src/Tests/EnsureTests.cs new file mode 100644 index 00000000..925a93e9 --- /dev/null +++ b/src/Tests/EnsureTests.cs @@ -0,0 +1,326 @@ +[TestFixture] +public class EnsureTests +{ + static string nullString = null!; + static List nullList = null!; + static IList nullIList = null!; + static IReadOnlyList nullIReadOnlyList = null!; + static ICollection nullICollection = null!; + static IReadOnlyCollection nullIReadOnlyCollection = null!; + static IEnumerable nullEnumerable = null!; + static string[] nullArray = null!; + static Dictionary nullDictionary = null!; + static IDictionary nullIDictionary = null!; + static IReadOnlyDictionary nullIReadOnlyDictionary = null!; + static object nullObject = null!; + + static string emptyString = string.Empty; + static List emptyList = []; + static IList emptyIList = []; + static IReadOnlyList emptyIReadOnlyList = []; + static ICollection emptyICollection = []; + static IReadOnlyCollection emptyIReadOnlyCollection = []; + static IEnumerable emptyEnumerable = []; + static Dictionary emptyDictionary = []; + static IDictionary emptyIDictionary = new Dictionary(); + static IReadOnlyDictionary emptyIReadOnlyDictionary = new Dictionary(); + static string[] emptyArray = []; + static string[] nonEmptyArray = ["value"]; + static List nonEmptyList = ["value"]; + static IEnumerable nonEmptyEnumerable = nonEmptyList.Select(x => x); + + [Test] + public void NotNull() + { + Assert.Throws(() => Ensure.NotNull(nullArray)); + Assert.Throws(() => Ensure.NotNull(nullString)); + Assert.Throws(() => Ensure.NotNull(nullObject)); + Assert.Throws(() => Ensure.NotNull(nullList)); + Assert.Throws(() => Ensure.NotNull(nullICollection)); + Assert.Throws(() => Ensure.NotNull(nullIList)); + Assert.Throws(() => Ensure.NotNull(nullIReadOnlyList)); + Assert.Throws(() => Ensure.NotNull(nullIReadOnlyCollection)); + Assert.Throws(() => Ensure.NotNull(nullEnumerable)); + Assert.Throws(() => Ensure.NotNull(nullDictionary)); + Assert.Throws(() => Ensure.NotNull(nullIDictionary)); + Assert.Throws(() => Ensure.NotNull(nullIReadOnlyDictionary)); + Ensure.NotNull(nonEmptyArray); + Ensure.NotNull(nonEmptyEnumerable); + Ensure.NotNull("value"); + Ensure.NotNull(nonEmptyEnumerable); + } + + [Test] + public void NotNullOrEmpty() + { +#if FeatureMemory + Assert.Throws(() => Ensure.NotNullOrEmpty(Memory.Empty)); + Assert.Throws(() => Ensure.NotNullOrEmpty((Memory?) null)); + Assert.Throws(() => Ensure.NotNullOrEmpty((ReadOnlyMemory?) null)); + Assert.Throws(() => Ensure.NotNullOrEmpty(ReadOnlyMemory.Empty)); +#endif + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyString)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyIList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyICollection)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyIReadOnlyList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyIReadOnlyCollection)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyArray)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyEnumerable)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyDictionary)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyIDictionary)); + Assert.Throws(() => Ensure.NotNullOrEmpty(emptyIReadOnlyDictionary)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullString)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullIList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullICollection)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullIReadOnlyList)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullIReadOnlyCollection)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullArray)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullEnumerable)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullDictionary)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullIDictionary)); + Assert.Throws(() => Ensure.NotNullOrEmpty(nullIReadOnlyDictionary)); + Ensure.NotNullOrEmpty(nonEmptyArray); + Ensure.NotNullOrEmpty(nonEmptyEnumerable); + Ensure.NotNullOrEmpty("value"); + Ensure.NotNullOrEmpty(nonEmptyEnumerable); + } + + [Test] + public void NotEmpty() + { + Assert.Throws(() => Ensure.NotEmpty(emptyString)); + Assert.Throws(() => Ensure.NotEmpty(emptyList)); + Assert.Throws(() => Ensure.NotEmpty(emptyIList)); + Assert.Throws(() => Ensure.NotEmpty(emptyICollection)); + Assert.Throws(() => Ensure.NotEmpty(emptyIReadOnlyList)); + Assert.Throws(() => Ensure.NotEmpty(emptyIReadOnlyCollection)); + Assert.Throws(() => Ensure.NotEmpty(emptyArray)); +#if FeatureMemory + Span buffer = []; + var spanCaught = false; + try + { + Ensure.NotEmpty(buffer); + } + catch (ArgumentException) + { + spanCaught = true; + } + + Assert.True(spanCaught); + Assert.Throws(() => Ensure.NotEmpty(Memory.Empty)); + Assert.Throws(() => Ensure.NotEmpty(Span.Empty)); + Assert.Throws(() => Ensure.NotEmpty(ReadOnlyMemory.Empty)); +#endif + Assert.Throws(() => Ensure.NotEmpty(emptyEnumerable)); + Assert.Throws(() => Ensure.NotEmpty(emptyDictionary)); + Assert.Throws(() => Ensure.NotEmpty(emptyIDictionary)); + Assert.Throws(() => Ensure.NotEmpty(emptyIReadOnlyDictionary)); + Ensure.NotEmpty(nullString); + Ensure.NotEmpty(nullList); + Ensure.NotEmpty(nullIList); + Ensure.NotEmpty(nullICollection); + Ensure.NotEmpty(nullIReadOnlyList); + Ensure.NotEmpty(nullIReadOnlyCollection); + Ensure.NotEmpty(nullArray); + Ensure.NotEmpty(nonEmptyArray); + Ensure.NotEmpty("value"); + Ensure.NotEmpty(nonEmptyList); + Ensure.NotEmpty(nullEnumerable); + Ensure.NotEmpty(nullDictionary); + Ensure.NotEmpty(nullIDictionary); + Ensure.NotEmpty(nullIReadOnlyDictionary); + } + + [Test] + public void NotWhiteSpace() + { + Assert.Throws(() => Ensure.NotWhiteSpace(" \t")); + Assert.Throws(() => Ensure.NotWhiteSpace(string.Empty)); +#if FeatureMemory + Span buffer = []; + var spanCaught = false; + try + { + Ensure.NotWhiteSpace(buffer); + } + catch (ArgumentException) + { + spanCaught = true; + } + + Assert.True(spanCaught); + Assert.Throws(() => Ensure.NotWhiteSpace(Memory.Empty)); + Assert.Throws(() => Ensure.NotWhiteSpace(Span.Empty)); + Assert.Throws(() => Ensure.NotWhiteSpace(ReadOnlyMemory.Empty)); + Ensure.NotWhiteSpace((Memory?) null!); + Ensure.NotWhiteSpace((ReadOnlyMemory?) null!); +#endif + // ReSharper disable once RedundantCast + Ensure.NotWhiteSpace((string) null!); + Ensure.NotWhiteSpace("value"); + } + + [Test] + public void NotNullOrWhiteSpace() + { +#if FeatureMemory + Assert.Throws(() => Ensure.NotNullOrWhiteSpace(Memory.Empty)); + Assert.Throws(() => Ensure.NotNullOrWhiteSpace((Memory?) null)); + Assert.Throws(() => Ensure.NotNullOrWhiteSpace((ReadOnlyMemory?) null)); + Assert.Throws(() => Ensure.NotNullOrWhiteSpace(ReadOnlyMemory.Empty)); +#endif + Assert.Throws(() => Ensure.NotNullOrWhiteSpace(" \t")); + Assert.Throws( + // ReSharper disable once RedundantCast + () => Ensure.NotNullOrWhiteSpace((string) null!)); + Assert.Throws(() => Ensure.NotNullOrWhiteSpace(string.Empty)); + Ensure.NotNullOrWhiteSpace("value"); + } + + [Test] + public void NotEqual_WhenValuesAreDifferent_DoesNotThrow() + { + Ensure.NotEqual(5, 10); + Ensure.NotEqual("hello", "world"); + Ensure.NotEqual(DateTime.Now, DateTime.MinValue); + } + + [Test] + public void NotEqual_WhenValuesAreEqual_ThrowsArgumentOutOfRangeException() + { + const int value = 42; + const int other = 42; + + var exception = Assert.Throws(() => Ensure.NotEqual(value, other))!; + + Assert.That(exception.ParamName, Is.EqualTo("value")); + Assert.That(exception.Message, Does.Contain("must not be equal to")); + Assert.That(exception.Message, Does.Contain("'42'")); + } + + [Test] + public void NotEqual_WhenStringsAreEqual_ThrowsArgumentOutOfRangeException() + { + const string value = "test"; + const string other = "test"; + + var exception = Assert.Throws(() => Ensure.NotEqual(value, other))!; + + Assert.That(exception.ParamName, Is.EqualTo("value")); + Assert.That(exception.Message, Does.Contain("'test'")); + } + + [Test] + public void NotEqual_WhenBothNull_ThrowsArgumentOutOfRangeException() + { + string? value = null; + string? other = null; + + var exception = Assert.Throws(() => Ensure.NotEqual(value, other))!; + + Assert.That(exception.ParamName, Is.EqualTo("value")); + Assert.That(exception.Message, Does.Contain("'null'")); + } + + [Test] + public void NotEqual_WhenOneIsNull_DoesNotThrow() + { + // Arrange & Act & Assert + Ensure.NotEqual("value", null); + Ensure.NotEqual(null, "value"); + } + + [Test] + public void NotEqual_WithCustomType_WhenEqual_ThrowsArgumentOutOfRangeException() + { + var value = new Person("John", 30); + var other = new Person("John", 30); + + Assert.Throws(() => Ensure.NotEqual(value, other)); + } + + [Test] + public void NotEqual_WithCustomType_WhenDifferent_DoesNotThrow() + { + var value = new Person("John", 30); + var other = new Person("Jane", 25); + + Ensure.NotEqual(value, other); + } + + [Test] + public void NotEqual_WithNullableValueType_WhenBothHaveSameValue_ThrowsArgumentOutOfRangeException() + { + int? value = 42; + int? other = 42; + + Assert.Throws(() => Ensure.NotEqual(value, other)); + } + + [Test] + public void NotEqual_WithNullableValueType_WhenBothNull_ThrowsArgumentOutOfRangeException() + { + int? value = null; + int? other = null; + + Assert.Throws(() => Ensure.NotEqual(value, other)); + } + + [Test] + public void NotEqual_WithNullableValueType_WhenDifferent_DoesNotThrow() + { + Ensure.NotEqual(42, 10); + Ensure.NotEqual((int?) 42, null); + Ensure.NotEqual(null, (int?) 42); + } + + [Test] + public void NotEqual_PreservesParameterName_WhenUsingCallerArgumentExpression() + { + var myVariable = 100; + var otherValue = 100; + + var exception = Assert.Throws(() => Ensure.NotEqual(myVariable, otherValue))!; + + Assert.That(exception.ParamName, Is.EqualTo("myVariable")); + } + + [TestCase(0, 1)] + [TestCase(-5, 5)] + [TestCase(int.MaxValue, int.MinValue)] + public void NotEqual_WithDifferentIntegers_DoesNotThrow(int value, int other) => + Ensure.NotEqual(value, other); + + [TestCase(5, 5)] + [TestCase(0, 0)] + [TestCase(-10, -10)] + public void NotEqual_WithEqualIntegers_ThrowsArgumentOutOfRangeException(int value, int other) => + Assert.Throws(() => Ensure.NotEqual(value, other)); + + private record Person(string Name, int Age) : IEquatable; + + #if NET10_0_OR_GREATER + public class User + { + int age; + string email; + decimal accountBalance; + string username; + + public User(string username, string email, int age, decimal accountBalance) + { + ArgumentException.ThrowIfNullOrWhiteSpace(username); + ArgumentNullException.ThrowIfNull(email); + ArgumentOutOfRangeException.ThrowIfNegative(age); + ArgumentOutOfRangeException.ThrowIfNegative(accountBalance); + this.username = username; + this.age = age; + this.email = email; + this.accountBalance = accountBalance; + } + } +#endif +} diff --git a/src/Tests/FilePolyfillTests.cs b/src/Tests/FilePolyfillTests.cs index 4eb38e6c..576576fd 100644 --- a/src/Tests/FilePolyfillTests.cs +++ b/src/Tests/FilePolyfillTests.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using System.Runtime.Versioning; +// ReSharper disable MethodHasAsyncOverload [TestFixture] [Parallelizable(ParallelScope.None)] @@ -31,9 +32,9 @@ public async Task AppendAllBytes() { var data = "Hello, World!"u8.ToArray(); // ReSharper disable once MethodHasAsyncOverload - FilePolyfill.AppendAllBytes(TestFilePath, data); + File.AppendAllBytes(TestFilePath, data); - var result = await FilePolyfill.ReadAllBytesAsync(TestFilePath); + var result = await File.ReadAllBytesAsync(TestFilePath); Assert.AreEqual(data, result); } @@ -41,20 +42,59 @@ public async Task AppendAllBytes() public async Task AppendAllBytesAsync() { var data = "Hello, Async World!"u8.ToArray(); - await FilePolyfill.AppendAllBytesAsync(TestFilePath, data); + await File.AppendAllBytesAsync(TestFilePath, data); - var result = await FilePolyfill.ReadAllBytesAsync(TestFilePath); + var result = await File.ReadAllBytesAsync(TestFilePath); Assert.AreEqual(data, result); } #endif + [Test] + public async Task ReadAllLinesAsync_ReadsAllLines() + { + var lines = new[] {"Line1", "Line2", "Line3"}; + File.WriteAllLines(TestFilePath, lines); + + var result = await File.ReadAllLinesAsync(TestFilePath); + + Assert.AreEqual(lines, result); + } + + [Test] + public void ReadAllLinesAsync_ThrowsIfFileNotFound() + { + var nonExistent = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + Assert.ThrowsAsync(async () => + await File.ReadAllLinesAsync(nonExistent)); + } + + [Test] + public async Task ReadAllLinesAsync_ThrowsIfCancelled() + { + File.WriteAllText(TestFilePath, "abc"); + var cancelSource = new CancelSource(); + cancelSource.Cancel(); + Exception? exception = null; + try + { + await File.ReadAllLinesAsync(TestFilePath, cancelSource.Token); + } + catch (Exception e) + { + exception = e; + } + + Assert.IsNotNull(exception); + Assert.IsTrue(exception is OperationCanceledException or TaskCanceledException); + } + [Test] public async Task AppendAllTextAsync() { var content = "Hello, Async Text!"; - await FilePolyfill.AppendAllTextAsync(TestFilePath, content, Encoding.UTF8); + await File.AppendAllTextAsync(TestFilePath, content, Encoding.UTF8); - var result = await FilePolyfill.ReadAllTextAsync(TestFilePath); + var result = await File.ReadAllTextAsync(TestFilePath); Assert.AreEqual(content, result); } @@ -72,7 +112,7 @@ public void GetUnixFileModeTest() var sourceContent = "Test content"; File.WriteAllText(TestFilePath, sourceContent); - var result = FilePolyfill.GetUnixFileMode(TestFilePath); + var result = File.GetUnixFileMode(TestFilePath); Assert.AreEqual(expected, result); } @@ -91,10 +131,9 @@ public void SetUnixFileModeTest() var expected = UnixFileMode.UserWrite | UnixFileMode.UserRead; - FilePolyfill.SetUnixFileMode(TestFilePath, - expected); + File.SetUnixFileMode(TestFilePath, expected); - var result = FilePolyfill.GetUnixFileMode(TestFilePath); + var result = File.GetUnixFileMode(TestFilePath); Assert.AreEqual(expected, result); } @@ -104,9 +143,9 @@ public void SetUnixFileModeTest() public async Task WriteAllBytesAsync() { var data = "Hello, Write Bytes!"u8.ToArray(); - await FilePolyfill.WriteAllBytesAsync(TestFilePath, data); + await File.WriteAllBytesAsync(TestFilePath, data); - var result = await FilePolyfill.ReadAllBytesAsync(TestFilePath); + var result = await File.ReadAllBytesAsync(TestFilePath); Assert.AreEqual(data, result); } #endif @@ -115,9 +154,9 @@ public async Task WriteAllBytesAsync() public async Task WriteAllTextAsync() { var content = "Hello, Write Text!"; - await FilePolyfill.WriteAllTextAsync(TestFilePath, content, Encoding.UTF8); + await File.WriteAllTextAsync(TestFilePath, content, Encoding.UTF8); - var result = await FilePolyfill.ReadAllTextAsync(TestFilePath); + var result = await File.ReadAllTextAsync(TestFilePath); Assert.AreEqual(content, result); } @@ -129,7 +168,7 @@ public void Move_ShouldMoveFileToNewLocation() File.WriteAllText(SourceFilePath, content); // Act - FilePolyfill.Move(SourceFilePath, DestinationFilePath, overwrite: true); + File.Move(SourceFilePath, DestinationFilePath, overwrite: true); // Assert Assert.IsFalse(File.Exists(SourceFilePath), "Source file should no longer exist."); @@ -148,7 +187,7 @@ public void Move_ShouldOverwriteDestinationFile_WhenOverwriteIsTrue() File.WriteAllText(DestinationFilePath, destinationContent); // Act - FilePolyfill.Move(SourceFilePath, DestinationFilePath, overwrite: true); + File.Move(SourceFilePath, DestinationFilePath, overwrite: true); // Assert Assert.IsFalse(File.Exists(SourceFilePath), "Source file should no longer exist."); @@ -168,6 +207,6 @@ public void Move_ShouldThrowIOException_WhenDestinationExistsAndOverwriteIsFalse // Act & Assert Assert.Throws(() => - FilePolyfill.Move(SourceFilePath, DestinationFilePath, overwrite: false)); + File.Move(SourceFilePath, DestinationFilePath, overwrite: false)); } } \ No newline at end of file diff --git a/src/Tests/GlobalUsings.cs b/src/Tests/GlobalUsings.cs index 22dcddfc..1e1c1a43 100644 --- a/src/Tests/GlobalUsings.cs +++ b/src/Tests/GlobalUsings.cs @@ -3,3 +3,5 @@ global using System.Diagnostics.CodeAnalysis; global using System.Globalization; global using System.Text.RegularExpressions; +global using System.Xml; +global using System.Xml.Linq; \ No newline at end of file diff --git a/src/Tests/GuardTests.cs b/src/Tests/GuardTests.cs deleted file mode 100644 index 300f0e1e..00000000 --- a/src/Tests/GuardTests.cs +++ /dev/null @@ -1,245 +0,0 @@ -[TestFixture] -public class GuardTests -{ - static string nullString = null!; - static List nullList = null!; - static IList nullIList = null!; - static IReadOnlyList nullIReadOnlyList = null!; - static ICollection nullICollection = null!; - static IReadOnlyCollection nullIReadOnlyCollection = null!; - static IEnumerable nullEnumerable = null!; - static string[] nullArray = null!; - static Dictionary nullDictionary = null!; - static IDictionary nullIDictionary = null!; - static IReadOnlyDictionary nullIReadOnlyDictionary = null!; - static object nullObject = null!; - - static string emptyString = string.Empty; - static List emptyList = []; - static IList emptyIList = []; - static IReadOnlyList emptyIReadOnlyList = []; - static ICollection emptyICollection = []; - static IReadOnlyCollection emptyIReadOnlyCollection = []; - static IEnumerable emptyEnumerable = []; - static Dictionary emptyDictionary = []; - static IDictionary emptyIDictionary = new Dictionary(); - static IReadOnlyDictionary emptyIReadOnlyDictionary = new Dictionary(); - static string[] emptyArray = []; - static string[] nonEmptyArray = ["value"]; - static List nonEmptyList = ["value"]; - static IEnumerable nonEmptyEnumerable = nonEmptyList.Select(x => x); - - [Test] - public void NotNull() - { - Assert.Throws( - () => Guard.NotNull(nullArray)); - Assert.Throws( - () => Guard.NotNull(nullString)); - Assert.Throws( - () => Guard.NotNull(nullObject)); - Assert.Throws( - () => Guard.NotNull(nullList)); - Assert.Throws( - () => Guard.NotNull(nullICollection)); - Assert.Throws( - () => Guard.NotNull(nullIList)); - Assert.Throws( - () => Guard.NotNull(nullIReadOnlyList)); - Assert.Throws( - () => Guard.NotNull(nullIReadOnlyCollection)); - Assert.Throws( - () => Guard.NotNull(nullEnumerable)); - Assert.Throws( - () => Guard.NotNull(nullDictionary)); - Assert.Throws( - () => Guard.NotNull(nullIDictionary)); - Assert.Throws( - () => Guard.NotNull(nullIReadOnlyDictionary)); - Guard.NotNull(nonEmptyArray); - Guard.NotNull(nonEmptyEnumerable); - Guard.NotNull("value"); - Guard.NotNull(nonEmptyEnumerable); - } - - [Test] - public void NotNullOrEmpty() - { -#if FeatureMemory - Assert.Throws( - () => Guard.NotNullOrEmpty(Memory.Empty)); - Assert.Throws( - () => Guard.NotNullOrEmpty((Memory?) null)); - Assert.Throws( - () => Guard.NotNullOrEmpty((ReadOnlyMemory?) null)); - Assert.Throws( - () => Guard.NotNullOrEmpty(ReadOnlyMemory.Empty)); -#endif - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyString)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyIList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyICollection)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyIReadOnlyList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyIReadOnlyCollection)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyArray)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyEnumerable)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyDictionary)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyIDictionary)); - Assert.Throws( - () => Guard.NotNullOrEmpty(emptyIReadOnlyDictionary)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullString)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullIList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullICollection)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullIReadOnlyList)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullIReadOnlyCollection)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullArray)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullEnumerable)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullDictionary)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullIDictionary)); - Assert.Throws( - () => Guard.NotNullOrEmpty(nullIReadOnlyDictionary)); - Guard.NotNullOrEmpty(nonEmptyArray); - Guard.NotNullOrEmpty(nonEmptyEnumerable); - Guard.NotNullOrEmpty("value"); - Guard.NotNullOrEmpty(nonEmptyEnumerable); - } - - [Test] - public void NotEmpty() - { - Assert.Throws( - () => Guard.NotEmpty(emptyString)); - Assert.Throws( - () => Guard.NotEmpty(emptyList)); - Assert.Throws( - () => Guard.NotEmpty(emptyIList)); - Assert.Throws( - () => Guard.NotEmpty(emptyICollection)); - Assert.Throws( - () => Guard.NotEmpty(emptyIReadOnlyList)); - Assert.Throws( - () => Guard.NotEmpty(emptyIReadOnlyCollection)); - Assert.Throws( - () => Guard.NotEmpty(emptyArray)); -#if FeatureMemory - Span buffer = []; - var spanCaught = false; - try - { - Guard.NotEmpty(buffer); - } - catch (ArgumentException) - { - spanCaught = true; - } - - Assert.True(spanCaught); - Assert.Throws( - () => Guard.NotEmpty(Memory.Empty)); - Assert.Throws( - () => Guard.NotEmpty(Span.Empty)); - Assert.Throws( - () => Guard.NotEmpty(ReadOnlyMemory.Empty)); -#endif - Assert.Throws( - () => Guard.NotEmpty(emptyEnumerable)); - Assert.Throws( - () => Guard.NotEmpty(emptyDictionary)); - Assert.Throws( - () => Guard.NotEmpty(emptyIDictionary)); - Assert.Throws( - () => Guard.NotEmpty(emptyIReadOnlyDictionary)); - Guard.NotEmpty(nullString); - Guard.NotEmpty(nullList); - Guard.NotEmpty(nullIList); - Guard.NotEmpty(nullICollection); - Guard.NotEmpty(nullIReadOnlyList); - Guard.NotEmpty(nullIReadOnlyCollection); - Guard.NotEmpty(nullArray); - Guard.NotEmpty(nonEmptyArray); - Guard.NotEmpty("value"); - Guard.NotEmpty(nonEmptyList); - Guard.NotEmpty(nullEnumerable); - Guard.NotEmpty(nullDictionary); - Guard.NotEmpty(nullIDictionary); - Guard.NotEmpty(nullIReadOnlyDictionary); - } - - [Test] - public void NotWhiteSpace() - { - Assert.Throws( - () => Guard.NotWhiteSpace(" \t")); - Assert.Throws( - () => Guard.NotWhiteSpace(string.Empty)); -#if FeatureMemory - Span buffer = []; - var spanCaught = false; - try - { - Guard.NotWhiteSpace(buffer); - } - catch (ArgumentException) - { - spanCaught = true; - } - - Assert.True(spanCaught); - Assert.Throws( - () => Guard.NotWhiteSpace(Memory.Empty)); - Assert.Throws( - () => Guard.NotWhiteSpace(Span.Empty)); - Assert.Throws( - () => Guard.NotWhiteSpace(ReadOnlyMemory.Empty)); - Guard.NotWhiteSpace((Memory?) null!); - Guard.NotWhiteSpace((ReadOnlyMemory?) null!); -#endif - // ReSharper disable once RedundantCast - Guard.NotWhiteSpace((string) null!); - Guard.NotWhiteSpace("value"); - } - - [Test] - public void NotNullOrWhiteSpace() - { -#if FeatureMemory - Assert.Throws( - () => Guard.NotNullOrWhiteSpace(Memory.Empty)); - Assert.Throws( - () => Guard.NotNullOrWhiteSpace((Memory?) null)); - Assert.Throws( - () => Guard.NotNullOrWhiteSpace((ReadOnlyMemory?) null)); - Assert.Throws( - () => Guard.NotNullOrWhiteSpace(ReadOnlyMemory.Empty)); -#endif - Assert.Throws( - () => Guard.NotNullOrWhiteSpace(" \t")); - Assert.Throws( - // ReSharper disable once RedundantCast - () => Guard.NotNullOrWhiteSpace((string) null!)); - Assert.Throws( - () => Guard.NotNullOrWhiteSpace(string.Empty)); - Guard.NotNullOrWhiteSpace("value"); - } -} \ No newline at end of file diff --git a/src/Tests/GuidPolyfillTests.cs b/src/Tests/GuidPolyfillTests.cs new file mode 100644 index 00000000..0625082e --- /dev/null +++ b/src/Tests/GuidPolyfillTests.cs @@ -0,0 +1,106 @@ +[TestFixture] +public class GuidPolyfillTests +{ + [Test] + public void TryParse_ReturnsTrue_ForValidGuid() + { + var guidString = Guid.NewGuid().ToString(); + var result = Guid.TryParse(guidString, null, out var guid); + Assert.IsTrue(result); + Assert.AreNotEqual(Guid.Empty, guid); + } + + [Test] + public void TryParse_ReturnsFalse_ForInvalidGuid() + { + var result = Guid.TryParse("not-a-guid", null, out var guid); + Assert.IsFalse(result); + Assert.AreEqual(Guid.Empty, guid); + } + +#if FeatureMemory + [Test] + public void TryParse_Span_ReturnsTrue_ForValidGuid() + { + var guid = Guid.NewGuid(); + var span = guid.ToString().AsSpan(); + var result = Guid.TryParse(span, null, out var parsed); + Assert.IsTrue(result); + Assert.AreEqual(guid, parsed); + } + + [Test] + public void TryParse_ReturnsTrue_ForValidUtf8Bytes() + { + var guid = Guid.NewGuid(); + var utf8Bytes = Encoding.UTF8.GetBytes(guid.ToString()); + var result = Guid.TryParse(utf8Bytes, out var parsed); + Assert.IsTrue(result); + Assert.AreEqual(guid, parsed); + } + + [Test] + public void Parse_ReturnsGuid_ForValidUtf8Bytes() + { + var guid = Guid.NewGuid(); + var utf8Bytes = Encoding.UTF8.GetBytes(guid.ToString()); + var parsed = Guid.Parse(utf8Bytes); + Assert.AreEqual(guid, parsed); + } + + [Test] + public void Parse_ThrowsFormatException_ForInvalidUtf8Bytes() + { + var utf8Bytes = "not-a-guid"u8.ToArray(); + Assert.Throws(() => Guid.Parse(utf8Bytes)); + } + + [Test] + public void TryParse_ReturnsFalse_ForInvalidUtf8Bytes() + { + var utf8Bytes = "not-a-guid"u8.ToArray(); + var result = Guid.TryParse(utf8Bytes, out var parsed); + Assert.IsFalse(result); + Assert.AreEqual(Guid.Empty, parsed); + } + + [Test] + public void TryParse_Span_ReturnsFalse_ForInvalidGuid() + { + var span = "invalid".AsSpan(); + var result = Guid.TryParse(span, null, out var parsed); + Assert.IsFalse(result); + Assert.AreEqual(Guid.Empty, parsed); + } + + [Test] + public void TryParseExact_Span_ReturnsTrue_ForExactFormat() + { + var guid = Guid.NewGuid(); + var span = guid.ToString("N").AsSpan(); + var format = "N".AsSpan(); + var result = Guid.TryParseExact(span, format, out var parsed); + Assert.IsTrue(result); + Assert.AreEqual(guid, parsed); + } +#endif + + [Test] + public void CreateVersion7_ReturnsUniqueGuids() + { + var guid1 = Guid.CreateVersion7(); + var guid2 = Guid.CreateVersion7(); + Assert.AreNotEqual(guid1, guid2); + } + + [Test] + public void CreateVersion7_WithTimestamp_ReturnsDeterministicPrefix() + { + var timestamp = DateTimeOffset.UtcNow; + var guid1 = Guid.CreateVersion7(timestamp); + var guid2 = Guid.CreateVersion7(timestamp); + // The time-based prefix should match, but random part will differ + Assert.AreNotEqual(guid1, guid2); + Assert.AreEqual(guid1.ToByteArray().Take(6), guid2.ToByteArray().Take(6)); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/BytePolyfillTests.cs b/src/Tests/Numbers/BytePolyfillTests.cs index f24360fa..d032fab9 100644 --- a/src/Tests/Numbers/BytePolyfillTests.cs +++ b/src/Tests/Numbers/BytePolyfillTests.cs @@ -4,25 +4,25 @@ public class BytePolyfillTest [Test] public void TryParse() { - Assert.True(BytePolyfill.TryParse("1"u8, null, out var value)); + Assert.True(Byte.TryParse("1"u8, null, out var value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse(['1'], out value)); + Assert.True(Byte.TryParse(['1'], out value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse(['1'], null, out value)); + Assert.True(Byte.TryParse(['1'], null, out value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse("1", null, out value)); + Assert.True(Byte.TryParse("1", null, out value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.True(Byte.TryParse("1"u8, NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse("1"u8, out value)); + Assert.True(Byte.TryParse("1"u8, out value)); Assert.AreEqual(1, value); - Assert.True(BytePolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.True(Byte.TryParse(['1'], NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); } } \ No newline at end of file diff --git a/src/Tests/Numbers/DoublePolyfillTests.cs b/src/Tests/Numbers/DoublePolyfillTests.cs index b8932422..a0e21468 100644 --- a/src/Tests/Numbers/DoublePolyfillTests.cs +++ b/src/Tests/Numbers/DoublePolyfillTests.cs @@ -4,25 +4,25 @@ public class DoublePolyfillTest [Test] public void TryParse() { - Assert.True(DoublePolyfill.TryParse("1"u8, null, out var value)); + Assert.True(double.TryParse("1"u8, null, out var value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse(['1'], out value)); + Assert.True(double.TryParse(['1'], out value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse(['1'], null, out value)); + Assert.True(double.TryParse(['1'], null, out value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse("1", null, out value)); + Assert.True(double.TryParse("1", null, out value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.True(double.TryParse("1"u8, NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse("1"u8, out value)); + Assert.True(double.TryParse("1"u8, out value)); Assert.AreEqual(1, value); - Assert.True(DoublePolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.True(double.TryParse(['1'], NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); } } \ No newline at end of file diff --git a/src/Tests/Numbers/Int16PolyfillTest.cs b/src/Tests/Numbers/Int16PolyfillTest.cs new file mode 100644 index 00000000..9884754b --- /dev/null +++ b/src/Tests/Numbers/Int16PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class Int16PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(short.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(short.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/Int32PolyfillTest.cs b/src/Tests/Numbers/Int32PolyfillTest.cs new file mode 100644 index 00000000..b9949523 --- /dev/null +++ b/src/Tests/Numbers/Int32PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class Int32PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(int.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(int.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/Int64PolyfillTest.cs b/src/Tests/Numbers/Int64PolyfillTest.cs new file mode 100644 index 00000000..7fc2f669 --- /dev/null +++ b/src/Tests/Numbers/Int64PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class Int64PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(long.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(long.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/IntPolyfillTests.cs b/src/Tests/Numbers/IntPolyfillTests.cs deleted file mode 100644 index 174a94eb..00000000 --- a/src/Tests/Numbers/IntPolyfillTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class IntPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(IntPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(IntPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/Numbers/LongPolyfillTests.cs b/src/Tests/Numbers/LongPolyfillTests.cs deleted file mode 100644 index a65d290d..00000000 --- a/src/Tests/Numbers/LongPolyfillTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class LongPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(LongPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(LongPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/Numbers/SBytePolyfillTests.cs b/src/Tests/Numbers/SBytePolyfillTests.cs index 963805d2..c3a48994 100644 --- a/src/Tests/Numbers/SBytePolyfillTests.cs +++ b/src/Tests/Numbers/SBytePolyfillTests.cs @@ -4,25 +4,25 @@ public class SBytePolyfillTest [Test] public void TryParse() { - Assert.True(SBytePolyfill.TryParse("1"u8, null, out var value)); + Assert.True(sbyte.TryParse("1"u8, null, out var value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse(['1'], out value)); + Assert.True(sbyte.TryParse(['1'], out value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse(['1'], null, out value)); + Assert.True(sbyte.TryParse(['1'], null, out value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse("1", null, out value)); + Assert.True(sbyte.TryParse("1", null, out value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.True(sbyte.TryParse("1"u8, NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse("1"u8, out value)); + Assert.True(sbyte.TryParse("1"u8, out value)); Assert.AreEqual(1, value); - Assert.True(SBytePolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.True(sbyte.TryParse(['1'], NumberStyles.Integer, null, out value)); Assert.AreEqual(1, value); } } \ No newline at end of file diff --git a/src/Tests/Numbers/ShortPolyfillTests.cs b/src/Tests/Numbers/ShortPolyfillTests.cs deleted file mode 100644 index d29a7cf9..00000000 --- a/src/Tests/Numbers/ShortPolyfillTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class ShortPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(ShortPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(ShortPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/Numbers/UInt16PolyfillTest.cs b/src/Tests/Numbers/UInt16PolyfillTest.cs new file mode 100644 index 00000000..478ca222 --- /dev/null +++ b/src/Tests/Numbers/UInt16PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class UInt16PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(ushort.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(ushort.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/UInt32PolyfillTest.cs b/src/Tests/Numbers/UInt32PolyfillTest.cs new file mode 100644 index 00000000..7b7b1d56 --- /dev/null +++ b/src/Tests/Numbers/UInt32PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class UInt32PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(uint.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(uint.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/UInt64PolyfillTest.cs b/src/Tests/Numbers/UInt64PolyfillTest.cs new file mode 100644 index 00000000..6897b81f --- /dev/null +++ b/src/Tests/Numbers/UInt64PolyfillTest.cs @@ -0,0 +1,28 @@ +[TestFixture] +public class UInt64PolyfillTest +{ + [Test] + public void TryParse() + { + Assert.True(ulong.TryParse("1"u8, null, out var value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse(['1'], out value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse(['1'], null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse("1", null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse("1"u8, NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse("1"u8, out value)); + Assert.AreEqual(1, value); + + Assert.True(ulong.TryParse(['1'], NumberStyles.Integer, null, out value)); + Assert.AreEqual(1, value); + } +} \ No newline at end of file diff --git a/src/Tests/Numbers/UIntPolyfillTests.cs b/src/Tests/Numbers/UIntPolyfillTests.cs deleted file mode 100644 index bcfbbe0f..00000000 --- a/src/Tests/Numbers/UIntPolyfillTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class UIntPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(UIntPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(UIntPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/Numbers/ULongPolyfill.cs b/src/Tests/Numbers/ULongPolyfill.cs deleted file mode 100644 index 8a860da6..00000000 --- a/src/Tests/Numbers/ULongPolyfill.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class ULongPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(ULongPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(ULongPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/Numbers/UShortPolyfillTests.cs b/src/Tests/Numbers/UShortPolyfillTests.cs deleted file mode 100644 index f4bf9f80..00000000 --- a/src/Tests/Numbers/UShortPolyfillTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -[TestFixture] -public class UShortPolyfillTest -{ - [Test] - public void TryParse() - { - Assert.True(UShortPolyfill.TryParse("1"u8, null, out var value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse(['1'], out value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse(['1'], null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse("1", null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse("1"u8, NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse("1"u8, out value)); - Assert.AreEqual(1, value); - - Assert.True(UShortPolyfill.TryParse(['1'], NumberStyles.Integer, null, out value)); - Assert.AreEqual(1, value); - } -} \ No newline at end of file diff --git a/src/Tests/PathTests.cs b/src/Tests/PathTests.cs index f3799a0d..ac93f431 100644 --- a/src/Tests/PathTests.cs +++ b/src/Tests/PathTests.cs @@ -4,26 +4,26 @@ public class PathTests #if FeatureMemory [Test] public void GetDirectoryName() => - Assert.AreEqual("dir", PathPolyfill.GetDirectoryName("dir/file.txt".AsSpan()).ToString()); + Assert.AreEqual("dir", Path.GetDirectoryName("dir/file.txt".AsSpan()).ToString()); [Test] public void GetFileName() => - Assert.AreEqual("file.txt", PathPolyfill.GetFileName("dir/file.txt".AsSpan()).ToString()); + Assert.AreEqual("file.txt", Path.GetFileName("dir/file.txt".AsSpan()).ToString()); [Test] public void GetFileNameWithoutExtension() => - Assert.AreEqual("file", PathPolyfill.GetFileNameWithoutExtension("dir/file.txt".AsSpan()).ToString()); + Assert.AreEqual("file", Path.GetFileNameWithoutExtension("dir/file.txt".AsSpan()).ToString()); [Test] public void HasExtension() { - Assert.True(PathPolyfill.HasExtension("file.txt".AsSpan())); - Assert.False(PathPolyfill.HasExtension("file".AsSpan())); + Assert.True(Path.HasExtension("file.txt".AsSpan())); + Assert.False(Path.HasExtension("file".AsSpan())); } [Test] public void GetExtension() => - Assert.AreEqual(".txt", PathPolyfill.GetExtension("file.txt".AsSpan()).ToString()); + Assert.AreEqual(".txt", Path.GetExtension("file.txt".AsSpan()).ToString()); [Test] public void Combine() @@ -35,7 +35,7 @@ public void Combine() "file.txt" ]; - var result = PathPolyfill.Combine(paths); + var result = Path.Combine(paths); Assert.AreEqual("folder1\\folder2\\file.txt", result.Replace('/','\\')); } @@ -45,19 +45,19 @@ public void Combine() public void EndsInDirectorySeparator() { #if FeatureMemory - Assert.False(PathPolyfill.EndsInDirectorySeparator("file.txt".AsSpan())); - Assert.True(PathPolyfill.EndsInDirectorySeparator("path/".AsSpan())); + Assert.False(Path.EndsInDirectorySeparator("file.txt".AsSpan())); + Assert.True(Path.EndsInDirectorySeparator("path/".AsSpan())); #endif - Assert.False(PathPolyfill.EndsInDirectorySeparator("file.txt")); - Assert.True(PathPolyfill.EndsInDirectorySeparator("path/")); + Assert.False(Path.EndsInDirectorySeparator("file.txt")); + Assert.True(Path.EndsInDirectorySeparator("path/")); } [Test] public void Exists() { - Assert.False(PathPolyfill.Exists(null)); - Assert.False(PathPolyfill.Exists("")); - Assert.False(PathPolyfill.Exists("file.txt")); - Assert.True(PathPolyfill.Exists(Environment.CurrentDirectory)); + Assert.False(Path.Exists(null)); + Assert.False(Path.Exists("")); + Assert.False(Path.Exists("file.txt")); + Assert.True(Path.Exists(Environment.CurrentDirectory)); } } \ No newline at end of file diff --git a/src/Tests/PolyfillTests_Delegate.cs b/src/Tests/PolyfillTests_Delegate.cs index 4f36f885..ba2c03d7 100644 --- a/src/Tests/PolyfillTests_Delegate.cs +++ b/src/Tests/PolyfillTests_Delegate.cs @@ -6,15 +6,15 @@ partial class PolyfillTests public void HasSingleTarget() { EventForHasSingleTarget += Handler; - Assert.IsTrue(EventForHasSingleTarget.HasSingleTarget()); + Assert.IsTrue(EventForHasSingleTarget.HasSingleTarget); EventForHasSingleTarget += Handler; - Assert.IsFalse(EventForHasSingleTarget.HasSingleTarget()); + Assert.IsFalse(EventForHasSingleTarget.HasSingleTarget); var action = () => { }; - Assert.IsTrue(action.HasSingleTarget()); + Assert.IsTrue(action.HasSingleTarget); action += action; - Assert.IsFalse(action.HasSingleTarget()); + Assert.IsFalse(action.HasSingleTarget); } static void Handler(object? sender, EventArgs e) @@ -30,7 +30,7 @@ public void EnumerateInvocationList() EventForEnumerateInvocationList += (_, _) => count++; - foreach (var item in DelegatePolyfill.EnumerateInvocationList(EventForEnumerateInvocationList)) + foreach (var item in Delegate.EnumerateInvocationList(EventForEnumerateInvocationList)) { item(this, EventArgs.Empty); } @@ -43,7 +43,7 @@ public void NullEnumerateInvocationList() { var count = 0; - foreach (var item in DelegatePolyfill.EnumerateInvocationList(null)) + foreach (var item in Delegate.EnumerateInvocationList(null)) { item(this, EventArgs.Empty); } diff --git a/src/Tests/PolyfillTests_Enum.cs b/src/Tests/PolyfillTests_Enum.cs index 601fa72d..a03cf239 100644 --- a/src/Tests/PolyfillTests_Enum.cs +++ b/src/Tests/PolyfillTests_Enum.cs @@ -3,41 +3,41 @@ partial class PolyfillTests [Test] public void EnumGetValues() { - var dayOfWeeks = EnumPolyfill.GetValues(); + var dayOfWeeks = Enum.GetValues(); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeeks[0]); } [Test] public void EnumGetNames() { - var dayOfWeeks = EnumPolyfill.GetNames(); + var dayOfWeeks = Enum.GetNames(); Assert.AreEqual("Sunday", dayOfWeeks[0]); } [Test] public void Parse() { - var dayOfWeek = EnumPolyfill.Parse("Sunday"); + var dayOfWeek = Enum.Parse("Sunday"); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); - Assert.Throws(() => EnumPolyfill.Parse("a")); + Assert.Throws(() => Enum.Parse("a")); - dayOfWeek = EnumPolyfill.Parse("sunday", true); + dayOfWeek = Enum.Parse("sunday", true); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); - Assert.Throws(() => EnumPolyfill.Parse("a", true)); + Assert.Throws(() => Enum.Parse("a", true)); #if FeatureMemory - dayOfWeek = EnumPolyfill.Parse("Sunday".AsSpan()); + dayOfWeek = Enum.Parse("Sunday".AsSpan()); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); - Assert.Throws(() => EnumPolyfill.Parse("a".AsSpan())); + Assert.Throws(() => Enum.Parse("a".AsSpan())); - dayOfWeek = EnumPolyfill.Parse("sunday".AsSpan(), true); + dayOfWeek = Enum.Parse("sunday".AsSpan(), true); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); - Assert.Throws(() => EnumPolyfill.Parse("a".AsSpan(), true)); + Assert.Throws(() => Enum.Parse("a".AsSpan(), true)); #endif } @@ -47,11 +47,11 @@ public void Parse() [Test] public void TryParse() { - var result = EnumPolyfill.TryParse("Sunday".AsSpan(), out var dayOfWeek); + var result = Enum.TryParse("Sunday".AsSpan(), out var dayOfWeek); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); Assert.True(result); - result = EnumPolyfill.TryParse("sunday".AsSpan(), true, out dayOfWeek); + result = Enum.TryParse("sunday".AsSpan(), true, out dayOfWeek); Assert.AreEqual(DayOfWeek.Sunday, dayOfWeek); Assert.True(result); } @@ -62,7 +62,7 @@ enum Colors { Red, Green, Blue } public void EnumTryFormat_ValidValue() { Span buffer = stackalloc char[10]; - var result = EnumPolyfill.TryFormat(Colors.Green, buffer, out var charsWritten); + var result = Enum.TryFormat(Colors.Green, buffer, out var charsWritten); Assert.IsTrue(result); Assert.AreEqual("Green", buffer[..charsWritten].ToString()); } @@ -71,7 +71,7 @@ public void EnumTryFormat_ValidValue() public void EnumTryFormat_BufferTooSmall() { Span buffer = stackalloc char[3]; - var result = EnumPolyfill.TryFormat(Colors.Blue, buffer, out var charsWritten); + var result = Enum.TryFormat(Colors.Blue, buffer, out var charsWritten); Assert.IsFalse(result); Assert.AreEqual(0, charsWritten); } @@ -80,7 +80,7 @@ public void EnumTryFormat_BufferTooSmall() public void EnumTryFormat_WithFormatSpecifier() { Span buffer = stackalloc char[10]; - var result = EnumPolyfill.TryFormat(Colors.Red, buffer, out var charsWritten, "G"); + var result = Enum.TryFormat(Colors.Red, buffer, out var charsWritten, "G"); Assert.IsTrue(result); Assert.AreEqual("Red", buffer[..charsWritten].ToString()); } diff --git a/src/Tests/PolyfillTests_Guid.cs b/src/Tests/PolyfillTests_Guid.cs index 21e9d0d8..8d78bb74 100644 --- a/src/Tests/PolyfillTests_Guid.cs +++ b/src/Tests/PolyfillTests_Guid.cs @@ -5,7 +5,7 @@ partial class PolyfillTests [Test] public void GuidCreate7() { - var guid = GuidPolyfill.CreateVersion7(); + var guid = Guid.CreateVersion7(); Assert.IsTrue(guidV7Regex.IsMatch(guid.ToString())); } } \ No newline at end of file diff --git a/src/Tests/PolyfillTests_IEnumerable.cs b/src/Tests/PolyfillTests_IEnumerable.cs index c6d698eb..53ac484b 100644 --- a/src/Tests/PolyfillTests_IEnumerable.cs +++ b/src/Tests/PolyfillTests_IEnumerable.cs @@ -189,9 +189,9 @@ public void ToHashSet() [Test] public void Zip3() { - var numbers = new List { 1 }; - var words = new List { "one" }; - var letters = new List { "a" }; + var numbers = new List {1}; + var words = new List {"one"}; + var letters = new List {"a"}; var result = numbers.Zip(words, letters).Single(); @@ -204,7 +204,7 @@ public void Zip3() public void ElementAtIndex() { #pragma warning disable IDE0028 - IEnumerable list = new List { 1, 2 }; + IEnumerable list = new List {1, 2}; #pragma warning restore IDE0028 // ReSharper disable ArrangeObjectCreationWhenTypeNotEvident @@ -244,8 +244,8 @@ public void FirstOrDefault() [Test] public void Zip2() { - var numbers = new List { 1 }; - var words = new List { "one" }; + var numbers = new List {1}; + var words = new List {"one"}; var result = numbers.Zip(words).Single(); @@ -260,10 +260,10 @@ public void Chunk_SizeOf3() var chunks = enumerable.Chunk(3).ToList(); - Assert.AreEqual(new[] { 1, 2, 3 }, chunks[0]); - Assert.AreEqual(new[] { 4, 5, 6 }, chunks[1]); - Assert.AreEqual(new[] { 7, 8, 9 }, chunks[2]); - Assert.AreEqual(new[] { 10, 11 }, chunks[3]); + Assert.AreEqual(new[] {1, 2, 3}, chunks[0]); + Assert.AreEqual(new[] {4, 5, 6}, chunks[1]); + Assert.AreEqual(new[] {7, 8, 9}, chunks[2]); + Assert.AreEqual(new[] {10, 11}, chunks[3]); } [Test] @@ -273,8 +273,8 @@ public void Chunk_SizeOf8() var chunks = enumerable.Chunk(8).ToList(); - Assert.AreEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, chunks[0]); - Assert.AreEqual(new[] { 9, 10, 11 }, chunks[1]); + Assert.AreEqual(new[] {1, 2, 3, 4, 5, 6, 7, 8}, chunks[0]); + Assert.AreEqual(new[] {9, 10, 11}, chunks[1]); } [Test] @@ -285,6 +285,72 @@ public void Chunk_SizeOfZero_ExpectedException() Assert.Throws(() => enumerable.Chunk(0).ToList()); } +#if NET7_0_OR_GREATER + [Test] + public void InfiniteSequence_StartsAtGivenValue() + { + var start = 10; + var step = 2; + var sequence = Enumerable.InfiniteSequence(start, step) + .Take(5) + .ToList(); + Assert.AreEqual(start, sequence[0]); + } + + [Test] + public void InfiniteSequence_IncrementsByStep() + { + var start = 1; + var step = 3; + var sequence = Enumerable.InfiniteSequence(start, step) + .Take(4) + .ToList(); + Assert.AreEqual(new[] {1, 4, 7, 10}, sequence); + } + + [Test] + public void InfiniteSequence_IsInfinite() + { + var start = 0; + var step = 1; + var sequence = Enumerable.InfiniteSequence(start, step); + // Only take first 100 elements to avoid infinite loop + Assert.AreEqual(100, sequence.Take(100).Count()); + } + + [Test] + public void Sequence_Increments_FromStartToEndInclusive() + { + var result = Enumerable.Sequence(1, 5, 1).ToList(); + Assert.AreEqual(new[] {1, 2, 3, 4, 5}, result); + } + + [Test] + public void Sequence_Decrements_FromStartToEndInclusive() + { + var result = Enumerable.Sequence(5, 1, -1).ToList(); + Assert.AreEqual(new[] {5, 4, 3, 2, 1}, result); + } + + [Test] + public void Sequence_SingleValue_WhenStartEqualsEnd() + { + var result = Enumerable.Sequence(3, 3, 1).ToList(); + Assert.AreEqual(new[] {3}, result); + } + + [Test] + public void Sequence_Throws_WhenStepPositiveAndEndLessThanStart() => + Assert.Throws(() => + Enumerable.Sequence(5, 1, 1).ToList()); + + [Test] + public void Sequence_Throws_WhenStepNegativeAndEndGreaterThanStart() => + Assert.Throws(() => + Enumerable.Sequence(1, 5, -1).ToList()); + +#endif + [Test] public void IEnumerableUnionBy() { diff --git a/src/Tests/PolyfillTests_OperatingSystem.cs b/src/Tests/PolyfillTests_OperatingSystem.cs index ee92697a..ae765c10 100644 --- a/src/Tests/PolyfillTests_OperatingSystem.cs +++ b/src/Tests/PolyfillTests_OperatingSystem.cs @@ -16,7 +16,7 @@ partial class PolyfillTests [Test] public void IsOperatingSystemWindows() { - bool actual = OperatingSystemPolyfill.IsWindows(); + bool actual = OperatingSystem.IsWindows(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); Assert.AreEqual(expected, actual); @@ -25,7 +25,7 @@ public void IsOperatingSystemWindows() [Test] public void IsOperatingSystemLinux() { - bool actual = OperatingSystemPolyfill.IsLinux(); + bool actual = OperatingSystem.IsLinux(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); Assert.AreEqual(expected, actual); @@ -34,7 +34,7 @@ public void IsOperatingSystemLinux() [Test] public void IsOperatingSystemMacOS() { - bool actual = OperatingSystemPolyfill.IsMacOS(); + bool actual = OperatingSystem.IsMacOS(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); Assert.AreEqual(expected, actual); @@ -44,7 +44,7 @@ public void IsOperatingSystemMacOS() [Test] public void IsOperatingSystemFreeBSD() { - bool actual = OperatingSystemPolyfill.IsFreeBSD(); + bool actual = OperatingSystem.IsFreeBSD(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD); Assert.AreEqual(expected, actual); @@ -55,7 +55,7 @@ public void IsOperatingSystemFreeBSD() [Test] public void IsOperatingSystemIOS() { - bool actual = OperatingSystemPolyfill.IsIOS(); + bool actual = OperatingSystem.IsIOS(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")); Assert.AreEqual(expected, actual); @@ -64,7 +64,7 @@ public void IsOperatingSystemIOS() [Test] public void IsOperatingSystemAndroid() { - bool actual = OperatingSystemPolyfill.IsAndroid(); + bool actual = OperatingSystem.IsAndroid(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("Android")); Assert.AreEqual(expected, actual); @@ -73,7 +73,7 @@ public void IsOperatingSystemAndroid() [Test] public void IsOperatingSystemTvOS() { - bool actual = OperatingSystemPolyfill.IsTvOS(); + bool actual = OperatingSystem.IsTvOS(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("tvOS")); Assert.AreEqual(expected, actual); @@ -82,7 +82,7 @@ public void IsOperatingSystemTvOS() [Test] public void IsOperatingSystemWatchOS() { - bool actual = OperatingSystemPolyfill.IsWatchOS(); + bool actual = OperatingSystem.IsWatchOS(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("watchOS")); Assert.AreEqual(expected, actual); @@ -91,7 +91,7 @@ public void IsOperatingSystemWatchOS() [Test] public void IsOperatingSystemBrowser() { - bool actual = OperatingSystemPolyfill.IsBrowser(); + bool actual = OperatingSystem.IsBrowser(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("Browser")); Assert.AreEqual(expected, actual); @@ -100,7 +100,7 @@ public void IsOperatingSystemBrowser() [Test] public void IsOperatingSystemWasi() { - bool actual = OperatingSystemPolyfill.IsWasi(); + bool actual = OperatingSystem.IsWasi(); bool expected = RuntimeInformation.IsOSPlatform(OSPlatform.Create("wasi")); Assert.AreEqual(expected, actual); diff --git a/src/Tests/PolyfillTests_Regex.cs b/src/Tests/PolyfillTests_Regex.cs index 0950a858..20d2e97f 100644 --- a/src/Tests/PolyfillTests_Regex.cs +++ b/src/Tests/PolyfillTests_Regex.cs @@ -29,7 +29,7 @@ public void EnumerateMatchesStatic() { var span = "a55a".AsSpan(); var found = false; - foreach (var match in RegexPolyfill.EnumerateMatches(span, @"\d+")) + foreach (var match in Regex.EnumerateMatches(span, @"\d+")) { found = true; Assert.AreEqual(1, match.Index); diff --git a/src/Tests/PolyfillTests_String.cs b/src/Tests/PolyfillTests_String.cs index 11f96348..58a8c6db 100644 --- a/src/Tests/PolyfillTests_String.cs +++ b/src/Tests/PolyfillTests_String.cs @@ -3,8 +3,14 @@ partial class PolyfillTests [Test] public void GetHashCodeStringComparison() { - var hash = "value".GetHashCode(StringComparison.Ordinal); - Assert.AreNotEqual(0, hash); + var hash1 = "value".GetHashCode(StringComparison.Ordinal); + Assert.AreNotEqual(0, hash1); + + var hash2 = string.GetHashCode("value".AsSpan()); + Assert.AreNotEqual(0, hash2); + + var hash3 = string.GetHashCode("value".AsSpan(), StringComparison.Ordinal); + Assert.AreNotEqual(0, hash3); } [Test] diff --git a/src/Tests/PolyfillTests_StringBuilder.cs b/src/Tests/PolyfillTests_StringBuilder.cs index 4a3d7fa8..d296394e 100644 --- a/src/Tests/PolyfillTests_StringBuilder.cs +++ b/src/Tests/PolyfillTests_StringBuilder.cs @@ -36,7 +36,7 @@ public void Replace() [Test] public void GetChunks() { - var builder = new StringBuilder("a",1); + var builder = new StringBuilder("a", 1); builder.Append("bb"); var list = new List(); foreach (var chunk in builder.GetChunks()) @@ -98,15 +98,15 @@ public void AppendJoin() string?[] span = ["value1", "value2"]; builder.AppendJoin(",", span); Assert(); - builder.AppendJoin(",", new object[]{"value1", "value2"}); + builder.AppendJoin(",", new object[] {"value1", "value2"}); Assert(); builder.AppendJoin(',', span); Assert(); - builder.AppendJoin(',', new object[]{"value1", "value2"}); + builder.AppendJoin(',', new object[] {"value1", "value2"}); Assert(); - builder.AppendJoin(",", new object[]{"value1", "value2"}.Select(_=>_)); + builder.AppendJoin(",", new object[] {"value1", "value2"}.Select(_ => _)); Assert(); - builder.AppendJoin(',', new object[]{"value1", "value2"}.Select(_=>_)); + builder.AppendJoin(',', new object[] {"value1", "value2"}.Select(_ => _)); Assert(); // ReSharper disable once RedundantExplicitParamsArrayCreation builder.AppendJoin(',', ["value1", "value2"]); diff --git a/src/Tests/PolyfillTests_TaskCompletionSource.cs b/src/Tests/PolyfillTests_TaskCompletionSource.cs index 3e6cccf5..294b26fc 100644 --- a/src/Tests/PolyfillTests_TaskCompletionSource.cs +++ b/src/Tests/PolyfillTests_TaskCompletionSource.cs @@ -22,13 +22,13 @@ public async Task TaskCompletionSource() public async Task TaskCompletionSource_SetCanceled_WithCancellationToken() { var completionSource = new TaskCompletionSource(); - var tokenSource = new CancelSource(); + var cancelSource = new CancelSource(); // Simulate some background work that will cancel the task Task.Run(async () => { await Task.Delay(20); // Simulate a delay - completionSource.SetCanceled(tokenSource.Token); + completionSource.SetCanceled(cancelSource.Token); }); try diff --git a/src/Tests/PolyfillTests_TryFormatToByteSpan.cs b/src/Tests/PolyfillTests_TryFormatToByteSpan.cs index a5c6b2f8..585c4065 100644 --- a/src/Tests/PolyfillTests_TryFormatToByteSpan.cs +++ b/src/Tests/PolyfillTests_TryFormatToByteSpan.cs @@ -466,7 +466,7 @@ public void TryFormatDateTimeLarger_ToByteSpan() [Test] public void TryFormatDate_ToByteSpan() { - var value = new DateOnly(2001, 10, 1); + var value = new Date(2001, 10, 1); Span buffer = stackalloc byte[16]; var result = value.TryFormat(buffer, out var written, format: "R", CultureInfo.InvariantCulture); Assert.True(result); @@ -477,7 +477,7 @@ public void TryFormatDate_ToByteSpan() [Test] public void TryFormatDateSmaller_ToByteSpan() { - var value = new DateOnly(2001, 10, 1); + var value = new Date(2001, 10, 1); Span buffer = stackalloc byte[20]; var result = value.TryFormat(buffer, out var written, format: "R", CultureInfo.InvariantCulture); Assert.True(result); @@ -488,7 +488,7 @@ public void TryFormatDateSmaller_ToByteSpan() [Test] public void TryFormatDateLarger_ToByteSpan() { - var value = new DateOnly(2001, 10, 1); + var value = new Date(2001, 10, 1); Span buffer = stackalloc byte[15]; var result = value.TryFormat(buffer, out var written, format: "R", CultureInfo.InvariantCulture); Assert.False(result); diff --git a/src/Tests/PolyfillTests_XDocument.cs b/src/Tests/PolyfillTests_XDocument.cs index 90f625b0..6929f377 100644 --- a/src/Tests/PolyfillTests_XDocument.cs +++ b/src/Tests/PolyfillTests_XDocument.cs @@ -1,6 +1,3 @@ -using System.Xml; -using System.Xml.Linq; - partial class PolyfillTests { [Test] diff --git a/src/Tests/PolyfillTests_XElement.cs b/src/Tests/PolyfillTests_XElement.cs index 9bd351d1..f5c2c0e0 100644 --- a/src/Tests/PolyfillTests_XElement.cs +++ b/src/Tests/PolyfillTests_XElement.cs @@ -1,6 +1,3 @@ -using System.Xml; -using System.Xml.Linq; - partial class PolyfillTests { [Test] diff --git a/src/Tests/RandomNumberGeneratorPolyfillTests.cs b/src/Tests/RandomNumberGeneratorPolyfillTests.cs index bb911dd9..6b4cd8b6 100644 --- a/src/Tests/RandomNumberGeneratorPolyfillTests.cs +++ b/src/Tests/RandomNumberGeneratorPolyfillTests.cs @@ -1,4 +1,6 @@ -[TestFixture] +using System.Security.Cryptography; + +[TestFixture] public class RandomNumberGeneratorPolyfillTests { [Test] @@ -8,7 +10,7 @@ public void GetInt32_Range_Valid() var max = 10; for (var i = 0; i < 100; i++) { - var value = RandomNumberGeneratorPolyfill.GetInt32(min, max); + var value = RandomNumberGenerator.GetInt32(min, max); Assert.That(value, Is.GreaterThanOrEqualTo(min).And.LessThan(max)); } } @@ -16,8 +18,8 @@ public void GetInt32_Range_Valid() [Test] public void GetInt32_Range_Invalid_Throws() { - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetInt32(10, 5)); - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetInt32(5, 5)); + Assert.Throws(() => RandomNumberGenerator.GetInt32(10, 5)); + Assert.Throws(() => RandomNumberGenerator.GetInt32(5, 5)); } [Test] @@ -26,7 +28,7 @@ public void GetInt32_Exclusive_Valid() var max = 10; for (var i = 0; i < 100; i++) { - var value = RandomNumberGeneratorPolyfill.GetInt32(max); + var value = RandomNumberGenerator.GetInt32(max); Assert.That(value, Is.GreaterThanOrEqualTo(0).And.LessThan(max)); } } @@ -34,28 +36,28 @@ public void GetInt32_Exclusive_Valid() [Test] public void GetInt32_Exclusive_Invalid_Throws() { - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetInt32(0)); - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetInt32(-1)); + Assert.Throws(() => RandomNumberGenerator.GetInt32(0)); + Assert.Throws(() => RandomNumberGenerator.GetInt32(-1)); } [Test] public void GetBytes_ReturnsArrayOfCorrectLength() { - var bytes = RandomNumberGeneratorPolyfill.GetBytes(16); + var bytes = RandomNumberGenerator.GetBytes(16); Assert.That(bytes.Length, Is.EqualTo(16)); Assert.That(bytes, Is.Not.All.EqualTo(0)); } [Test] public void GetBytes_Invalid_Throws() => - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetBytes(-1)); + Assert.Throws(() => RandomNumberGenerator.GetBytes(-1)); #if FeatureMemory [Test] public void Fill_FillsSpan() { Span data = new byte[8]; - RandomNumberGeneratorPolyfill.Fill(data); + RandomNumberGenerator.Fill(data); Assert.That(data.ToArray(), Has.Some.Not.EqualTo(0)); } @@ -63,7 +65,7 @@ public void Fill_FillsSpan() public void GetHexString_Span_FillsWithHex() { Span chars = new char[8]; - RandomNumberGeneratorPolyfill.GetHexString(chars, lowercase: true); + RandomNumberGenerator.GetHexString(chars, lowercase: true); Assert.That(chars.ToArray(), Is.All.Matches(c => "0123456789abcdef".Contains(c))); } #endif @@ -71,12 +73,12 @@ public void GetHexString_Span_FillsWithHex() [Test] public void GetHexString_StringLength_Valid() { - var hex = RandomNumberGeneratorPolyfill.GetHexString(12, lowercase: false); + var hex = RandomNumberGenerator.GetHexString(12, lowercase: false); Assert.That(hex.Length, Is.EqualTo(12)); Assert.That(hex, Is.All.Matches(c => "0123456789ABCDEF".Contains(c))); } [Test] public void GetHexString_StringLength_Invalid_Throws() => - Assert.Throws(() => RandomNumberGeneratorPolyfill.GetHexString(-1)); + Assert.Throws(() => RandomNumberGenerator.GetHexString(-1)); } \ No newline at end of file diff --git a/src/Tests/RandomPolyfillTests.cs b/src/Tests/RandomPolyfillTests.cs index 1960b1aa..20ec960a 100644 --- a/src/Tests/RandomPolyfillTests.cs +++ b/src/Tests/RandomPolyfillTests.cs @@ -4,7 +4,7 @@ public class RandomPolyfillTests [Test, Repeat(100)] public void NextInt() { - var number = RandomPolyfill.Shared.Next(10); + var number = Random.Shared.Next(10); Assert.That(number, Is.InRange(0, 10)); } diff --git a/src/Tests/Sha256PolyfillTests.cs b/src/Tests/Sha256PolyfillTests.cs index 3adffc28..9f2bcea6 100644 --- a/src/Tests/Sha256PolyfillTests.cs +++ b/src/Tests/Sha256PolyfillTests.cs @@ -1,4 +1,7 @@ // ReSharper disable ReplaceSliceWithRangeIndexer + +using System.Security.Cryptography; + #pragma warning disable IDE0057 [TestFixture] @@ -10,7 +13,7 @@ public class Sha256PolyfillTests [Test] public void HashData_ByteArray_ReturnsCorrectHash() { - var actualHash = SHA256Polyfill.HashData(data); + var actualHash = SHA256.HashData(data); Assert.AreEqual(expected, actualHash); } @@ -21,7 +24,7 @@ public void HashData_Stream_ReturnsCorrectHash() stream.Position = 0; - var actualHash = SHA256Polyfill.HashData(stream); + var actualHash = SHA256.HashData(stream); Assert.AreEqual(expected, actualHash); } @@ -33,7 +36,7 @@ public async Task HashDataAsync_Stream_ReturnsCorrectHash() stream.Position = 0; - var actualHash = await SHA256Polyfill.HashDataAsync(stream); + var actualHash = await SHA256.HashDataAsync(stream); Assert.AreEqual(expected, actualHash); } #endif @@ -44,7 +47,7 @@ public void HashData_ReadOnlySpan_ReturnsCorrectHash() { ReadOnlySpan span = data; - var actualHash = SHA256Polyfill.HashData(span); + var actualHash = SHA256.HashData(span); Assert.AreEqual(expected, actualHash); } @@ -57,7 +60,7 @@ public async Task HashDataAsync_Memory_ReturnsCorrectHash() stream.Position = 0; Memory destination = new byte[expected.Length]; - var length = await SHA256Polyfill.HashDataAsync(stream, destination); + var length = await SHA256.HashDataAsync(stream, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Span)); } @@ -71,7 +74,7 @@ public void HashData_StreamAndSpan_LongerDestination() stream.Position = 0; - var length = SHA256Polyfill.HashData(stream, destination); + var length = SHA256.HashData(stream, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Slice(0, expected.Length))); @@ -82,7 +85,7 @@ public void HashData_ReadOnlySpanAndSpan_LongerDestination() { Span destination = stackalloc byte[expected.Length + 1]; - var length = SHA256Polyfill.HashData(data, destination); + var length = SHA256.HashData(data, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Slice(0, expected.Length))); @@ -98,7 +101,7 @@ public void HashData_StreamAndSpan_ShorterDestination() var exception = Assert.Throws(() => { Span destination = stackalloc byte[expected.Length - 1]; - SHA256Polyfill.HashData(stream, destination); + SHA256.HashData(stream, destination); }); Assert.True(exception!.Message.StartsWith("Destination is too short.")); @@ -110,7 +113,7 @@ public void HashData_ReadOnlySpanAndSpan_ShorterDestination() var exception = Assert.Throws(() => { Span destination = stackalloc byte[expected.Length - 1]; - SHA256Polyfill.HashData(data, destination); + SHA256.HashData(data, destination); }); Assert.True(exception!.Message.StartsWith("Destination is too short.")); @@ -122,7 +125,7 @@ public void TryHashData_ValidInput_ReturnsTrueAndCorrectHash() { Span destination = stackalloc byte[expected.Length]; - var result = SHA256Polyfill.TryHashData(data, destination, out var written); + var result = SHA256.TryHashData(data, destination, out var written); Assert.IsTrue(result); Assert.AreEqual(expected.Length, written); @@ -134,7 +137,7 @@ public void TryHashData_InsufficientDestinationBuffer_ReturnsFalse() { Span destination = stackalloc byte[expected.Length - 1]; - var result = SHA256Polyfill.TryHashData(data, destination, out var written); + var result = SHA256.TryHashData(data, destination, out var written); Assert.IsFalse(result); Assert.AreEqual(0, written); diff --git a/src/Tests/Sha512PolyfillTests.cs b/src/Tests/Sha512PolyfillTests.cs index 6d47c13a..4b1167b7 100644 --- a/src/Tests/Sha512PolyfillTests.cs +++ b/src/Tests/Sha512PolyfillTests.cs @@ -1,4 +1,7 @@ // ReSharper disable ReplaceSliceWithRangeIndexer + +using System.Security.Cryptography; + #pragma warning disable IDE0057 [TestFixture] @@ -10,7 +13,7 @@ public class Sha512PolyfillTests [Test] public void HashData_ByteArray_ReturnsCorrectHash() { - var actualHash = SHA512Polyfill.HashData(data); + var actualHash = SHA512.HashData(data); Assert.AreEqual(expected, actualHash); } @@ -21,7 +24,7 @@ public void HashData_Stream_ReturnsCorrectHash() stream.Position = 0; - var actualHash = SHA512Polyfill.HashData(stream); + var actualHash = SHA512.HashData(stream); Assert.AreEqual(expected, actualHash); } @@ -33,7 +36,7 @@ public async Task HashDataAsync_Stream_ReturnsCorrectHash() stream.Position = 0; - var actualHash = await SHA512Polyfill.HashDataAsync(stream); + var actualHash = await SHA512.HashDataAsync(stream); Assert.AreEqual(expected, actualHash); } #endif @@ -44,7 +47,7 @@ public void HashData_ReadOnlySpan_ReturnsCorrectHash() { ReadOnlySpan span = data; - var actualHash = SHA512Polyfill.HashData(span); + var actualHash = SHA512.HashData(span); Assert.AreEqual(expected, actualHash); } @@ -57,7 +60,7 @@ public async Task HashDataAsync_Memory_ReturnsCorrectHash() stream.Position = 0; Memory destination = new byte[expected.Length]; - var length = await SHA512Polyfill.HashDataAsync(stream, destination); + var length = await SHA512.HashDataAsync(stream, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Span)); } @@ -71,7 +74,7 @@ public void HashData_StreamAndSpan_LongerDestination() stream.Position = 0; - var length = SHA512Polyfill.HashData(stream, destination); + var length = SHA512.HashData(stream, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Slice(0, expected.Length))); @@ -82,7 +85,7 @@ public void HashData_ReadOnlySpanAndSpan_LongerDestination() { Span destination = stackalloc byte[expected.Length + 1]; - var length = SHA512Polyfill.HashData(data, destination); + var length = SHA512.HashData(data, destination); Assert.AreEqual(expected.Length, length); Assert.IsTrue(expected.AsSpan().SequenceEqual(destination.Slice(0, expected.Length))); @@ -98,7 +101,7 @@ public void HashData_StreamAndSpan_ShorterDestination() var exception = Assert.Throws(() => { Span destination = stackalloc byte[expected.Length - 1]; - SHA512Polyfill.HashData(stream, destination); + SHA512.HashData(stream, destination); }); Assert.True(exception!.Message.StartsWith("Destination is too short.")); @@ -110,19 +113,18 @@ public void HashData_ReadOnlySpanAndSpan_ShorterDestination() var exception = Assert.Throws(() => { Span destination = stackalloc byte[expected.Length - 1]; - SHA512Polyfill.HashData(data, destination); + SHA512.HashData(data, destination); }); Assert.True(exception!.Message.StartsWith("Destination is too short.")); } - [Test] public void TryHashData_ValidInput_ReturnsTrueAndCorrectHash() { Span destination = stackalloc byte[expected.Length]; - var result = SHA512Polyfill.TryHashData(data, destination, out var bytesWritten); + var result = SHA512.TryHashData(data, destination, out var bytesWritten); Assert.IsTrue(result); Assert.AreEqual(expected.Length, bytesWritten); @@ -134,7 +136,7 @@ public void TryHashData_InsufficientDestinationBuffer_ReturnsFalse() { Span destination = stackalloc byte[expected.Length - 1]; - var result = SHA512Polyfill.TryHashData(data, destination, out var bytesWritten); + var result = SHA512.TryHashData(data, destination, out var bytesWritten); Assert.IsFalse(result); Assert.AreEqual(0, bytesWritten); diff --git a/src/Tests/SolutionDirectoryFinder.cs b/src/Tests/SolutionDirectoryFinder.cs index 528bd8af..42b22294 100644 --- a/src/Tests/SolutionDirectoryFinder.cs +++ b/src/Tests/SolutionDirectoryFinder.cs @@ -15,7 +15,7 @@ public static bool TryFind(string sourceFile, [NotNullWhen(true)] out string? pa var currentDirectory = Directory.GetParent(sourceFile)!.FullName; do { - if (Directory.GetFiles(currentDirectory, "*.sln").Length > 0) + if (Directory.GetFiles(currentDirectory, "*.slnx").Length > 0) { path = currentDirectory; return true; diff --git a/src/Tests/StringPolyfillTests.cs b/src/Tests/StringPolyfillTests.cs index 916cd2f2..9f3ca037 100644 --- a/src/Tests/StringPolyfillTests.cs +++ b/src/Tests/StringPolyfillTests.cs @@ -1,15 +1,16 @@ +// ReSharper disable RedundantExplicitParamsArrayCreation [TestFixture] public class StringPolyfillTest { [Test] public void Join() { - Assert.AreEqual("bac", StringPolyfill.Join('a', ["b", "c"])); - Assert.AreEqual("ba1c", StringPolyfill.Join("a1", ["b", "c"])); - Assert.AreEqual("ba1a1c", StringPolyfill.Join("a1", ["b", null, "c"])); - Assert.AreEqual("bac", StringPolyfill.Join('a', new object[] {"b", "c"})); - Assert.AreEqual("baac", StringPolyfill.Join('a', new object?[] {"b", null, "c"})); + Assert.AreEqual("bac", string.Join('a', ["b", "c"])); + Assert.AreEqual("ba1c", string.Join("a1", ["b", "c"])); + Assert.AreEqual("ba1a1c", string.Join("a1", ["b", null, "c"])); + Assert.AreEqual("bac", string.Join('a', new object[] {"b", "c"})); + Assert.AreEqual("baac", string.Join('a', new object?[] {"b", null, "c"})); // ReSharper disable once RedundantCast - Assert.AreEqual("bac", StringPolyfill.Join('a', (IEnumerable) new List{"b", "c"})); + Assert.AreEqual("bac", string.Join('a', (IEnumerable) new List{"b", "c"})); } } \ No newline at end of file diff --git a/src/Tests/XElementPolyfillTests.cs b/src/Tests/XElementPolyfillTests.cs new file mode 100644 index 00000000..b0a8f181 --- /dev/null +++ b/src/Tests/XElementPolyfillTests.cs @@ -0,0 +1,58 @@ +[TestFixture] +public class XElementPolyfillTests +{ + const string XmlContent = "value"; + + [Test] + public async Task LoadAsync_Stream_ReturnsXElement() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(XmlContent)); + var result = await XElement.LoadAsync(stream, LoadOptions.None, Cancel.None); + Assert.AreEqual("root", result.Name.LocalName); + Assert.AreEqual("value", result.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_TextReader_ReturnsXElement() + { + using var reader = new StringReader(XmlContent); + var result = await XElement.LoadAsync(reader, LoadOptions.None, Cancel.None); + Assert.AreEqual("root", result.Name.LocalName); + Assert.AreEqual("value", result.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_XmlReader_ReturnsXElement() + { + using var stringReader = new StringReader(XmlContent); + using var xmlReader = XmlReader.Create( + stringReader, + new() + { + Async = true + }); + var result = await XElement.LoadAsync(xmlReader, LoadOptions.None, Cancel.None); + Assert.AreEqual("root", result.Name.LocalName); + Assert.AreEqual("value", result.Element("child")?.Value); + } + + [Test] + public async Task LoadAsync_Stream_CancellationRequested_Throws() + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(XmlContent)); + var cancelSource = new CancelSource(); + await cancelSource.CancelAsync(); + Exception? exception = null; + try + { + await XElement.LoadAsync(stream, LoadOptions.None, cancelSource.Token); + } + catch (Exception e) + { + exception = e; + } + + Assert.IsNotNull(exception); + Assert.IsTrue(exception is OperationCanceledException or TaskCanceledException); + } +} \ No newline at end of file diff --git a/src/appveyor.yml b/src/appveyor.yml index a7015eea..3b5aaa7d 100644 --- a/src/appveyor.yml +++ b/src/appveyor.yml @@ -12,11 +12,11 @@ build_script: Invoke-WebRequest "https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.ps1" -OutFile "./dotnet-install.ps1" ./dotnet-install.ps1 -JSonFile src/global.json -Architecture x64 -InstallDir 'C:\Program Files\dotnet' ./dotnet-install.ps1 -Version 5.0.408 -Architecture x64 -InstallDir 'C:\Program Files\dotnet' - ./dotnet-install.ps1 -Version 9.0.301 -Architecture x64 -InstallDir 'C:\Program Files\dotnet' - dotnet build src/Polyfill.sln --configuration Release --verbosity quiet + ./dotnet-install.ps1 -Version 9.0.306 -Architecture x64 -InstallDir 'C:\Program Files\dotnet' + dotnet build src/Polyfill.slnx --configuration Release --verbosity quiet + dotnet test src/Polyfill.slnx --configuration Release --no-build --no-restore + # msbuild.exe src/PolyfillUwp.slnx /p:Configuration=Release -verbosity:quiet dotnet build src/PolyfillTrimmed.slnf --target PublishAll --configuration Release - dotnet test src/Polyfill.sln --configuration Release --no-build --no-restore - msbuild.exe src/PolyfillUwp.sln /p:Configuration=Release -verbosity:quiet } else { Invoke-WebRequest "https://dotnet.microsoft.com/download/dotnet/scripts/v1/dotnet-install.sh" -OutFile "./dotnet-install.sh" @@ -24,13 +24,13 @@ build_script: if ($isMacOS) { sudo ./dotnet-install.sh --jsonfile src/global.json --architecture x64 --install-dir '/usr/local/share/dotnet' sudo ./dotnet-install.sh --version 5.0.408 --architecture x64 --install-dir '/usr/local/share/dotnet' - sudo ./dotnet-install.sh --version 9.0.301 --architecture x64 --install-dir '/usr/local/share/dotnet' + sudo ./dotnet-install.sh --version 9.0.306 --architecture x64 --install-dir '/usr/local/share/dotnet' } else { sudo ./dotnet-install.sh --jsonfile src/global.json --architecture x64 --install-dir '/usr/share/dotnet' } - dotnet build src/Polyfill.sln --configuration Release --verbosity quiet + dotnet build src/Polyfill.slnx --configuration Release --verbosity quiet + dotnet test src/Polyfill.slnx --configuration Release --no-build --no-restore dotnet build src/PolyfillTrimmed.slnf --target PublishAll --configuration Release - dotnet test src/Polyfill.sln --configuration Release --no-build --no-restore } on_failure: diff --git a/src/global.json b/src/global.json index 346156e6..b124219c 100644 --- a/src/global.json +++ b/src/global.json @@ -7,4 +7,4 @@ "msbuild-sdks": { "MSBuild.Sdk.Extras": "3.0.44" } -} \ No newline at end of file +} diff --git a/target-frameworks.md b/target-frameworks.md index a6d6dbe2..35c71948 100644 --- a/target-frameworks.md +++ b/target-frameworks.md @@ -95,7 +95,7 @@ At build time, if a project is detected to not properly multi target, then a war >true ``` -snippet source | anchor +snippet source | anchor @@ -119,7 +119,7 @@ For example: Condition="$(MaxNetRequired)" /> ``` -snippet source | anchor +snippet source | anchor