From 97fc99aaf72598870a3a7cd23c3e5b0c64297f81 Mon Sep 17 00:00:00 2001 From: Youssef1313 Date: Sun, 29 Dec 2024 09:46:45 +0100 Subject: [PATCH] Add text-only package Polyfill 7.9.1 --- .../src/polyfill/7.9.1/.editorconfig | 2 + .../src/polyfill/7.9.1/Polyfill.7.9.1.csproj | 8 + .../src/polyfill/7.9.1/build/Polyfill.targets | 125 +++ .../CallerArgumentExpressionAttribute.cs | 40 + .../Polyfill/CollectionBuilderAttribute.cs | 42 + .../CompilerFeatureRequiredAttribute.cs | 56 ++ .../Polyfill/ConstantExpectedAttribute.cs | 35 + .../Polyfill/DateTimeOffsetPolyfill.cs | 88 ++ .../Polyfill/DateTimePolyfill.cs | 87 ++ ...DisableUserUnhandledExceptionsAttribute.cs | 23 + .../Polyfill/DelegatePolyfill.cs | 65 ++ .../DisableRuntimeMarshallingAttribute.cs | 38 + .../netstandard2.0/Polyfill/EnumPolyfill.cs | 137 +++ .../Polyfill/ExperimentalAttribute.cs | 69 ++ .../Polyfill/FeatureGuardAttribute.cs | 47 + .../FeatureSwitchDefinitionAttribute.cs | 41 + .../cs/netstandard2.0/Polyfill/Guard/Guard.cs | 39 + .../Polyfill/Guard/Guard_NotEmpty.cs | 144 ++++ .../Polyfill/Guard/Guard_NotNull.cs | 39 + .../Polyfill/Guard/Guard_NotNullOrEmpty.cs | 106 +++ .../Guard/Guard_NotNullOrWhiteSpace.cs | 97 +++ .../Polyfill/Guard/Guard_NotWhiteSpace.cs | 135 +++ .../netstandard2.0/Polyfill/GuidPolyfill.cs | 132 +++ .../Polyfill/IndexRange/Index.cs | 154 ++++ .../Polyfill/IndexRange/Range.cs | 81 ++ .../netstandard2.0/Polyfill/IsExternalInit.cs | 22 + .../netstandard2.0/Polyfill/KeyValuePair.cs | 34 + .../cs/netstandard2.0/Polyfill/Lock.cs | 182 ++++ .../Polyfill/ModuleInitializerAttribute.cs | 42 + .../Polyfill/Nullability/NullabilityInfo.cs | 81 ++ .../Nullability/NullabilityInfoContext.cs | 669 ++++++++++++++ .../Nullability/NullabilityInfoExtensions.cs | 154 ++++ .../Polyfill/Nullable/AllowNullAttribute.cs | 25 + .../Nullable/DisallowNullAttribute.cs | 25 + .../Nullable/DoesNotReturnAttribute.cs | 21 + .../Nullable/DoesNotReturnIfAttribute.cs | 41 + .../Polyfill/Nullable/MaybeNullAttribute.cs | 26 + .../Nullable/MaybeNullWhenAttribute.cs | 38 + .../Nullable/MemberNotNullAttribute.cs | 51 ++ .../Nullable/MemberNotNullWhenAttribute.cs | 71 ++ .../Polyfill/Nullable/NotNullAttribute.cs | 26 + .../Nullable/NotNullIfNotNullAttribute.cs | 41 + .../Polyfill/Nullable/NotNullWhenAttribute.cs | 38 + .../Polyfill/Numbers/BytePolyfill.cs | 98 +++ .../Polyfill/Numbers/DoublePolyfill.cs | 97 +++ .../Polyfill/Numbers/IntPolyfill.cs | 97 +++ .../Polyfill/Numbers/LongPolyfill.cs | 97 +++ .../Polyfill/Numbers/SBytePolyfill.cs | 97 +++ .../Polyfill/Numbers/ShortPolyfill.cs | 97 +++ .../Polyfill/Numbers/UIntPolyfill.cs | 97 +++ .../Polyfill/Numbers/ULongPolyfill.cs | 97 +++ .../Polyfill/Numbers/UShortPolyfill.cs | 97 +++ .../OverloadResolutionPriorityAttribute.cs | 42 + .../Polyfill/ParamCollectionAttribute.cs | 23 + .../OSPlatformAttribute.cs | 25 + .../ObsoletedOSPlatformAttribute.cs | 56 ++ .../SupportedOSPlatformAttribute.cs | 47 + .../SupportedOSPlatformGuardAttribute.cs | 39 + .../TargetPlatformAttribute.cs | 25 + .../UnsupportedOSPlatformAttribute.cs | 56 ++ .../UnsupportedOSPlatformGuardAttribute.cs | 41 + .../cs/netstandard2.0/Polyfill/Polyfill.cs | 16 + .../Polyfill/Polyfill_CancellationToken.cs | 136 +++ .../Polyfill_CancellationTokenSource.cs | 59 ++ .../Polyfill/Polyfill_ConcurrentBag.cs | 25 + .../Polyfill/Polyfill_ConcurrentDictionary.cs | 69 ++ .../Polyfill/Polyfill_ConcurrentQueue.cs | 22 + .../Polyfill/Polyfill_Delegate.cs | 26 + .../Polyfill/Polyfill_Dictionary.cs | 82 ++ .../Polyfill/Polyfill_Encoding.cs | 81 ++ .../Polyfill/Polyfill_HashSet.cs | 41 + .../Polyfill/Polyfill_HttpClient.cs | 183 ++++ .../Polyfill/Polyfill_HttpContent.cs | 78 ++ .../Polyfill_IEnumerable_AggregateBy.cs | 126 +++ .../Polyfill/Polyfill_IEnumerable_Append.cs | 34 + .../Polyfill/Polyfill_IEnumerable_Chunk.cs | 101 +++ .../Polyfill/Polyfill_IEnumerable_CountBy.cs | 68 ++ .../Polyfill_IEnumerable_DistinctBy.cs | 62 ++ .../Polyfill_IEnumerable_ElementAt.cs | 105 +++ .../Polyfill/Polyfill_IEnumerable_Except.cs | 121 +++ .../Polyfill_IEnumerable_FirstOrDefault.cs | 84 ++ .../Polyfill/Polyfill_IEnumerable_Index.cs | 28 + .../Polyfill_IEnumerable_LastOrDefault.cs | 120 +++ .../Polyfill/Polyfill_IEnumerable_Max.cs | 34 + .../Polyfill/Polyfill_IEnumerable_MaxBy.cs | 124 +++ .../Polyfill/Polyfill_IEnumerable_Min.cs | 36 + .../Polyfill/Polyfill_IEnumerable_MinBy.cs | 125 +++ .../Polyfill_IEnumerable_SingleOrDefault.cs | 106 +++ .../Polyfill/Polyfill_IEnumerable_SkipLast.cs | 29 + .../Polyfill/Polyfill_IEnumerable_Take.cs | 211 +++++ .../Polyfill/Polyfill_IEnumerable_TakeLast.cs | 39 + .../Polyfill_IEnumerable_ThrowHelper.cs | 10 + .../Polyfill_IEnumerable_ToHashSet.cs | 28 + ...ll_IEnumerable_TryGetNonEnumeratedCount.cs | 53 ++ .../Polyfill/Polyfill_IEnumerable_Zip.cs | 65 ++ .../Polyfill/Polyfill_IReadOnlyDictionary.cs | 65 ++ .../Polyfill/Polyfill_KeyValuePair.cs | 28 + .../netstandard2.0/Polyfill/Polyfill_List.cs | 68 ++ .../Polyfill/Polyfill_Memory.cs | 173 ++++ .../Polyfill/Polyfill_Memory_EndsWith.cs | 72 ++ .../Polyfill/Polyfill_Memory_SpanSplit.cs | 94 ++ .../Polyfill_Memory_SpanSplitEnumerator.cs | 220 +++++ ...Polyfill_Memory_SpanSplitEnumeratorMode.cs | 38 + .../Polyfill/Polyfill_Memory_StartsWith.cs | 64 ++ .../Polyfill/Polyfill_MicroNanosecond.cs | 121 +++ .../Polyfill/Polyfill_MicroNanosecondAdd.cs | 27 + .../Polyfill/Polyfill_Process.cs | 117 +++ .../Polyfill/Polyfill_Random.cs | 89 ++ .../Polyfill/Polyfill_SortedList.cs | 34 + .../Polyfill/Polyfill_Stream.cs | 89 ++ .../Polyfill/Polyfill_Stream_DisposeAsync.cs | 32 + .../Polyfill/Polyfill_String.cs | 139 +++ .../Polyfill/Polyfill_StringBuilder.cs | 75 ++ .../Polyfill/Polyfill_StringBuilder_Append.cs | 87 ++ .../Polyfill_StringBuilder_AppendJoin.cs | 81 ++ .../Polyfill_StringBuilder_AppendLine.cs | 59 ++ .../Polyfill/Polyfill_StringBuilder_CopyTo.cs | 46 + .../Polyfill_StringBuilder_GetChunks.cs | 209 +++++ .../netstandard2.0/Polyfill/Polyfill_Task.cs | 127 +++ .../Polyfill/Polyfill_TaskCompletionSource.cs | 38 + .../Polyfill/Polyfill_TextReader.cs | 91 ++ .../Polyfill/Polyfill_TextWriter.cs | 211 +++++ .../Polyfill/Polyfill_TryFormatToByteSpan.cs | 381 ++++++++ .../Polyfill/Polyfill_TryFormatToCharSpan.cs | 389 +++++++++ .../netstandard2.0/Polyfill/Polyfill_Type.cs | 88 ++ .../Polyfill/Polyfill_XDocument.cs | 82 ++ .../Polyfill/Regex/Polyfill_Regex.cs | 45 + .../Polyfill/Regex/RegexCache.cs | 290 +++++++ .../Polyfill/Regex/RegexPolyfill.cs | 111 +++ .../Polyfill/Regex/ValueMatch.cs | 50 ++ .../Polyfill/Regex/ValueMatchEnumerator.cs | 83 ++ .../Polyfill/RequiredMemberAttribute.cs | 29 + .../RequiresPreviewFeaturesAttribute .cs | 60 ++ .../Polyfill/ResolveHttpGlobalProblem.cs | 17 + .../Polyfill/SetsRequiredMembersAttribute.cs | 20 + .../Polyfill/SkipLocalsInitAttribute.cs | 44 + .../Polyfill/SpanLineEnumerator.cs | 95 ++ .../Polyfill/StackTraceHiddenAttribute.cs | 28 + .../AppendInterpolatedStringHandler.cs | 351 ++++++++ .../DefaultInterpolatedStringHandler.cs | 816 ++++++++++++++++++ .../StringInterpolation/ISpanFormattable.cs | 31 + ...erpolatedStringHandlerArgumentAttribute.cs | 45 + .../InterpolatedStringHandlerAttribute.cs | 27 + .../netstandard2.0/Polyfill/StringPolyfill.cs | 60 ++ .../Polyfill/StringSyntaxAttribute.cs | 89 ++ .../Polyfill/SuppressGCTransitionAttribute.cs | 75 ++ .../Polyfill/TaskCompletionSource.cs | 227 +++++ .../Trimming/DynamicDependencyAttribute.cs | 142 +++ .../DynamicallyAccessedMemberTypes.cs | 100 +++ .../DynamicallyAccessedMembersAttribute.cs | 62 ++ .../Trimming/RequiresDynamicCodeAttribute.cs | 53 ++ .../RequiresUnreferencedCodeAttribute.cs | 55 ++ .../UnconditionalSuppressMessageAttribute.cs | 98 +++ .../Polyfill/UnmanagedCallersOnlyAttribute.cs | 50 ++ .../Polyfill/UnreachableException.cs | 56 ++ .../Polyfill/UnscopedRefAttribute.cs | 48 ++ .../src/polyfill/7.9.1/icon.png | Bin 0 -> 3215 bytes .../src/polyfill/7.9.1/polyfill.nuspec | 16 + 158 files changed, 13879 insertions(+) create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/.editorconfig create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/Polyfill.7.9.1.csproj create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/build/Polyfill.targets create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CallerArgumentExpressionAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CollectionBuilderAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CompilerFeatureRequiredAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ConstantExpectedAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimeOffsetPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimePolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DelegatePolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DisableRuntimeMarshallingAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/EnumPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ExperimentalAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureGuardAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureSwitchDefinitionAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotEmpty.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNull.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrEmpty.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotWhiteSpace.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/GuidPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Index.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Range.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IsExternalInit.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/KeyValuePair.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Lock.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ModuleInitializerAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfo.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoContext.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoExtensions.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/AllowNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DisallowNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnIfAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullWhenAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullWhenAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullIfNotNullAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullWhenAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/BytePolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/DoublePolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/IntPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/LongPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/SBytePolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ShortPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UIntPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ULongPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UShortPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/OverloadResolutionPriorityAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ParamCollectionAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationToken.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationTokenSource.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentBag.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentDictionary.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentQueue.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Delegate.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Dictionary.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Encoding.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HashSet.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpClient.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpContent.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_AggregateBy.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Append.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Chunk.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_CountBy.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_DistinctBy.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ElementAt.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Except.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_FirstOrDefault.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Index.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_LastOrDefault.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Max.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MaxBy.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Min.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MinBy.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SingleOrDefault.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SkipLast.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Take.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TakeLast.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ThrowHelper.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ToHashSet.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TryGetNonEnumeratedCount.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Zip.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IReadOnlyDictionary.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_KeyValuePair.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_List.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_EndsWith.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplit.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumerator.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumeratorMode.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_StartsWith.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecond.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecondAdd.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Process.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Random.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_SortedList.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream_DisposeAsync.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_String.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_Append.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendJoin.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendLine.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_CopyTo.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_GetChunks.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Task.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TaskCompletionSource.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextReader.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextWriter.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToByteSpan.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToCharSpan.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Type.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_XDocument.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/Polyfill_Regex.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexCache.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatch.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatchEnumerator.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiredMemberAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiresPreviewFeaturesAttribute .cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ResolveHttpGlobalProblem.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SetsRequiredMembersAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SkipLocalsInitAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SpanLineEnumerator.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StackTraceHiddenAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/ISpanFormattable.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringPolyfill.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringSyntaxAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SuppressGCTransitionAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/TaskCompletionSource.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicDependencyAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnmanagedCallersOnlyAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnreachableException.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnscopedRefAttribute.cs create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/icon.png create mode 100644 src/textOnlyPackages/src/polyfill/7.9.1/polyfill.nuspec diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/.editorconfig b/src/textOnlyPackages/src/polyfill/7.9.1/.editorconfig new file mode 100644 index 000000000..8c1f7ee22 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/.editorconfig @@ -0,0 +1,2 @@ +# exclude code from dotnet format https://github.com/dotnet/sdk/issues/38906 +root = true \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/Polyfill.7.9.1.csproj b/src/textOnlyPackages/src/polyfill/7.9.1/Polyfill.7.9.1.csproj new file mode 100644 index 000000000..8e38473ad --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/Polyfill.7.9.1.csproj @@ -0,0 +1,8 @@ + + + + netstandard2.0 + Polyfill + + + diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/build/Polyfill.targets b/src/textOnlyPackages/src/polyfill/7.9.1/build/Polyfill.targets new file mode 100644 index 000000000..e95bce2f7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/build/Polyfill.targets @@ -0,0 +1,125 @@ + + + $(PrepareForBuildDependsOn);PreparePolyfill + $(TargetFramework.ToLower()) + $(TargetFrameworks.ToLower()) + + + $(DefineConstants);LangVersion13 + $(DefineConstants);LangVersion13 + $(DefineConstants);LangVersion13 + $(DefineConstants);LangVersion13 + $(DefineConstants);LangVersion13 + + + $(DefineConstants);AllowUnsafeBlocks + + + $(DefineConstants);PolyPublic + + + $(DefineConstants);NETCOREAPP2X + + + $(DefineConstants);NETCOREAPP3X + + + $(DefineConstants);NET46X + + + $(DefineConstants);NET47X + + + $(DefineConstants);NET48X + + + $(DefineConstants);NETCOREAPPX + + + false + true + + false + true + + + + + + + + $(DefineConstants);FeatureValueTuple + + @(ResolvedCompileFileDefinitions->WithMetadataValue('NuGetPackageId', 'System.Memory')->Metadata('NuGetPackageVersion')) + + $(DefineConstants);FeatureMemory + + $(DefineConstants);FeatureValueTask + + $(DefineConstants);FeatureHttp + + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureMemory;FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureValueTuple + $(DefineConstants);FeatureValueTuple + $(DefineConstants);FeatureValueTuple + $(DefineConstants);FeatureValueTuple;FeatureValueTask + $(DefineConstants);FeatureValueTuple + + + + + + + + + + false + + + diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CallerArgumentExpressionAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CallerArgumentExpressionAttribute.cs new file mode 100644 index 000000000..8c09018be --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,40 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Indicates that a parameter captures the expression passed for another parameter as a string. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute +#if PolyPublic +public +#endif +sealed class CallerArgumentExpressionAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class. + /// + /// + /// The name of the parameter whose expression should be captured as a string. + /// + public CallerArgumentExpressionAttribute(string parameterName) => + ParameterName = parameterName; + + /// + /// Gets the name of the parameter whose expression should be captured as a string. + /// + public string ParameterName { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CollectionBuilderAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CollectionBuilderAttribute.cs new file mode 100644 index 000000000..eb5b439c6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CollectionBuilderAttribute.cs @@ -0,0 +1,42 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER && FeatureMemory + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.collectionbuilderattribute +#if PolyPublic +public +#endif +sealed class CollectionBuilderAttribute : Attribute +{ + /// Initialize the attribute to refer to the method on the type. + /// The type of the builder to use to construct the collection. + /// The name of the method on the builder to use to construct the collection. + /// + /// must refer to a static method that accepts a single parameter of + /// type and returns an instance of the collection being built containing + /// a copy of the data from that span. In future releases of .NET, additional patterns may be supported. + /// + public CollectionBuilderAttribute(Type builderType, string methodName) + { + BuilderType = builderType; + MethodName = methodName; + } + + /// Gets the type of the builder to use to construct the collection. + public Type BuilderType { get; } + + /// Gets the name of the method on the builder to use to construct the collection. + /// This should match the metadata name of the target method. For example, this might be ".ctor" if targeting the type's constructor. + public string MethodName { get; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CompilerFeatureRequiredAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CompilerFeatureRequiredAttribute.cs new file mode 100644 index 000000000..7050a89e1 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/CompilerFeatureRequiredAttribute.cs @@ -0,0 +1,56 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Indicates that compiler support for a particular feature is required for the location where this attribute is applied. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: AttributeTargets.All, + AllowMultiple = true, + Inherited = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.compilerfeaturerequiredattribute +#if PolyPublic +public +#endif +sealed class CompilerFeatureRequiredAttribute : + Attribute +{ + /// + /// Initialize a new instance of + /// + /// The name of the required compiler feature. + public CompilerFeatureRequiredAttribute(string featureName) => + FeatureName = featureName; + + /// + /// The name of the compiler feature. + /// + public string FeatureName { get; } + + /// + /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand . + /// + public bool IsOptional { get; init; } + + /// + /// The used for the ref structs C# feature. + /// + public const string RefStructs = nameof(RefStructs); + + /// + /// The used for the required members C# feature. + /// + public const string RequiredMembers = nameof(RequiredMembers); +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ConstantExpectedAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ConstantExpectedAttribute.cs new file mode 100644 index 000000000..bd84870bb --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ConstantExpectedAttribute.cs @@ -0,0 +1,35 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +#nullable enable +namespace System.Diagnostics.CodeAnalysis; + +using Diagnostics; + +/// +/// Indicates that the specified method parameter expects a constant. +/// +/// +/// This can be used to inform tooling that a constant should be used as an argument for the annotated parameter. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.constantexpectedattribute +#if PolyPublic +public +#endif +sealed class ConstantExpectedAttribute : Attribute +{ + /// + /// Indicates the minimum bound of the expected constant, inclusive. + /// + public object? Min { get; set; } + /// + /// Indicates the maximum bound of the expected constant, inclusive. + /// + public object? Max { get; set; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimeOffsetPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimeOffsetPolyfill.cs new file mode 100644 index 000000000..cd6245aa2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimeOffsetPolyfill.cs @@ -0,0 +1,88 @@ +// +#pragma warning disable + +#nullable enable + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static class DateTimeOffsetPolyfill +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse#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); +#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#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); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse#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 + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparse#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.tryparseexact#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); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryparseexact#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 NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0 + DateTimeOffset.TryParseExact(target.ToString(), format.ToString(), provider, styles, out result); +#else + DateTimeOffset.TryParseExact(target, format, provider, styles, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimePolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimePolyfill.cs new file mode 100644 index 000000000..11a6c6105 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DateTimePolyfill.cs @@ -0,0 +1,87 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static class DateTimePolyfill +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse#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); +#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#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); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse#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 + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse#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.tryparseexact#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); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact#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 NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0 + DateTime.TryParseExact(target.ToString(), format.ToString(), provider, styles, out result); +#else + DateTime.TryParseExact(target, format, provider, styles, out result); +#endif + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs new file mode 100644 index 000000000..ce6502d95 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DebuggerDisableUserUnhandledExceptionsAttribute.cs @@ -0,0 +1,23 @@ +// +#pragma warning disable + +#if !NET9_0_OR_GREATER + +namespace System.Diagnostics; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// If a .NET Debugger is attached that supports the API, the debugger won't break on user-unhandled exceptions when the exception is caught by a method with this attribute, unless is called. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(System.AttributeTargets.Method)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerdisableuserunhandledexceptionsattribute +#if PolyPublic +public +#endif +sealed class DebuggerDisableUserUnhandledExceptionsAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DelegatePolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DelegatePolyfill.cs new file mode 100644 index 000000000..5a75f81f5 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DelegatePolyfill.cs @@ -0,0 +1,65 @@ +// + + +#pragma warning disable + +namespace Polyfills; + +using System; +using System.ComponentModel; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static partial class DelegatePolyfill +{ + /// + /// Gets an enumerator for the invocation targets of this delegate. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.enumerateinvocationlist +#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 InvocationListEnumerator(target); + + /// + /// Provides an enumerator for the invocation list of a delegate. + /// + /// Delegate type being enumerated. + public struct InvocationListEnumerator + where TDelegate : Delegate + { + Delegate[] delegates; + int index = -1; + + internal InvocationListEnumerator(Delegate target) => + delegates = target.GetInvocationList(); + + public TDelegate Current { get; private set; } + + public bool MoveNext() + { + int index = this.index + 1; + if (index == delegates.Length) + { + return false; + } + + Current = (TDelegate) delegates[index]; + this.index = index; + return true; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public InvocationListEnumerator GetEnumerator() => this; + } +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DisableRuntimeMarshallingAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DisableRuntimeMarshallingAttribute.cs new file mode 100644 index 000000000..2d86ec2fe --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/DisableRuntimeMarshallingAttribute.cs @@ -0,0 +1,38 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Disables the built-in runtime managed/unmanaged marshalling subsystem for +/// P/Invokes, Delegate types, and unmanaged function pointer invocations. +/// +/// +/// The built-in marshalling subsystem has some behaviors that cannot be changed due to +/// backward-compatibility requirements. This attribute allows disabling the built-in +/// subsystem and instead uses the following rules for P/Invokes, Delegates, +/// and unmanaged function pointer invocations: +/// +/// - All value types that do not contain reference type fields recursively (unmanaged in C#) are blittable +/// - Value types that recursively have any fields that have [StructLayout(LayoutKind.Auto)] are disallowed from interop. +/// - All reference types are disallowed from usage in interop scenarios. +/// - SetLastError support in P/Invokes is disabled. +/// - varargs support is disabled. +/// - LCIDConversionAttribute support is disabled. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Assembly)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.disableruntimemarshallingattribute +#if PolyPublic +public +#endif +sealed class DisableRuntimeMarshallingAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/EnumPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/EnumPolyfill.cs new file mode 100644 index 000000000..4eb293eeb --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/EnumPolyfill.cs @@ -0,0 +1,137 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static class EnumPolyfill +{ + /// + /// Retrieves an array of the values of the constants in a specified enumeration type. + /// + /// An array that contains the values of the constants in TEnum. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues + public static TEnum[] GetValues() + where TEnum : struct, Enum + { +#if NETCOREAPPX || NETFRAMEWORK || NETSTANDARD + var values = Enum.GetValues(typeof(TEnum)); + var result = new TEnum[values.Length]; + Array.Copy(values, result, values.Length); + return result; +#else + return Enum.GetValues(); +#endif + } + + /// Returns a telling whether a given integral value exists in a specified enumeration. + /// The type of the enumeration. + /// The value in . + /// if a given integral value exists in a specified enumeration; , otherwise. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined#system-enum-isdefined-1(-0) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsDefined (TEnum value) + where TEnum : struct, Enum => +#if NET5_0_OR_GREATER + Enum.IsDefined(value); +#else + Enum.IsDefined(typeof(TEnum), value); +#endif + + /// + /// Retrieves an array of the names of the constants in a specified enumeration type. + /// + /// A string array of the names of the constants in TEnum. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames + public static string[] GetNames() + where TEnum : struct, Enum => +#if NETCOREAPPX || NETFRAMEWORK || NETSTANDARD + Enum.GetNames(typeof(TEnum)); +#else + Enum.GetNames(); +#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#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#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 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#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#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 + + /// + /// 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#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 + + /// + /// 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#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 +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ExperimentalAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ExperimentalAttribute.cs new file mode 100644 index 000000000..2156b7147 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ExperimentalAttribute.cs @@ -0,0 +1,69 @@ +// +#pragma warning disable + +#nullable enable + +#if !NET8_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +using Diagnostics; + +/// +/// Indicates that a parameter captures the expression passed for another parameter as a string. +/// +/// +/// Indicates that an API is experimental and it may change in the future. +/// +/// +/// This attribute allows call sites to be flagged with a diagnostic that indicates that an experimental +/// feature is used. Authors can use this attribute to ship preview features in their assemblies. +/// +[AttributeUsage(AttributeTargets.Assembly | + AttributeTargets.Module | + AttributeTargets.Class | + AttributeTargets.Struct | + AttributeTargets.Enum | + AttributeTargets.Constructor | + AttributeTargets.Method | + AttributeTargets.Property | + AttributeTargets.Field | + AttributeTargets.Event | + AttributeTargets.Interface | + AttributeTargets.Delegate, Inherited = false)] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.experimentalattribute +#if PolyPublic +public +#endif +sealed class ExperimentalAttribute : Attribute +{ + /// + /// Initializes a new instance of the class, specifying the ID that the compiler will use + /// when reporting a use of the API the attribute applies to. + /// + /// The ID that the compiler will use when reporting a use of the API the attribute applies to. + public ExperimentalAttribute(string diagnosticId) => + DiagnosticId = diagnosticId; + + /// + /// Gets the ID that the compiler will use when reporting a use of the API the attribute applies to. + /// + /// The unique diagnostic ID. + /// + /// The diagnostic ID is shown in build output for warnings and errors. + /// This property represents the unique ID that can be used to suppress the warnings or errors, if needed. + /// + public string DiagnosticId { get; } + + /// + /// Gets or sets the URL for corresponding documentation. + /// The API accepts a format string instead of an actual URL, creating a generic URL that includes the diagnostic ID. + /// + /// The format string that represents a URL to corresponding documentation. + /// An example format string is https://contoso.com/obsoletion-warnings/{0}. + public string? UrlFormat { get; set; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureGuardAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureGuardAttribute.cs new file mode 100644 index 000000000..e8195084b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureGuardAttribute.cs @@ -0,0 +1,47 @@ +// +#pragma warning disable + +#if !NET9_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + + +/// +/// Indicates that the specified public static boolean get-only property +/// guards access to the specified feature. +/// +/// +/// Analyzers can use this to prevent warnings on calls to code that is +/// annotated as requiring that feature, when the callsite is guarded by a +/// call to the property. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.featureguardattribute +#if PolyPublic +public +#endif +sealed class FeatureGuardAttribute : Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified feature type. + /// + /// + /// The type that represents the feature guarded by the property. + /// + public FeatureGuardAttribute(Type featureType) => + FeatureType = featureType; + + /// + /// The type that represents the feature guarded by the property. + /// + public Type FeatureType { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureSwitchDefinitionAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureSwitchDefinitionAttribute.cs new file mode 100644 index 000000000..d58bae61e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/FeatureSwitchDefinitionAttribute.cs @@ -0,0 +1,41 @@ +// +#pragma warning disable + +#if !NET9_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// [AttributeUsage(AttributeTargets.Property, Inherited = false)] +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Property, Inherited = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.featureswitchdefinitionattribute +#if PolyPublic +public +#endif +sealed class FeatureSwitchDefinitionAttribute : Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified feature switch name. + /// + /// + /// The name of the feature switch that provides the value for the specified property. + /// + public FeatureSwitchDefinitionAttribute(string switchName) + { + SwitchName = switchName; + } + + /// + /// The name of the feature switch that provides the value for the specified property. + /// + public string SwitchName { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard.cs new file mode 100644 index 000000000..c2e15bd6b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard.cs @@ -0,0 +1,39 @@ +// + +namespace Polyfills; + +using System.Runtime.CompilerServices; + +#pragma warning disable + +using System; +using System.IO; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[StackTraceHidden] +#if PolyPublic +public +#endif +static partial class Guard +{ + public static void FileExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + { + NotNullOrEmpty(path, argumentName); + if (!File.Exists(path)) + { + throw new ArgumentException($"File not found. Path: {path}", argumentName); + } + } + + public static void DirectoryExists(string path, [CallerArgumentExpression("path")] string argumentName = "") + { + NotNullOrEmpty(path, argumentName); + if (!Directory.Exists(path)) + { + throw new ArgumentException($"Directory not found. Path: {path}", argumentName); + } + } +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotEmpty.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotEmpty.cs new file mode 100644 index 000000000..167b6e514 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotEmpty.cs @@ -0,0 +1,144 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Runtime.CompilerServices; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Guard +{ + public static void NotEmpty(string? value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value is null) + { + return; + } + +#if NET7_0_OR_GREATER + ArgumentException.ThrowIfNullOrEmpty(value, argumentName); +#else + + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } +#endif + } + +#if FeatureMemory + + public static void NotEmpty(ReadOnlySpan value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + + public static void NotEmpty(Span value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + + public static void NotEmpty(Memory? value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value is null) + { + return; + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + + public static void NotEmpty(Memory value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + + public static void NotEmpty(ReadOnlyMemory? value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value is null) + { + return; + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + + public static void NotEmpty(ReadOnlyMemory value, [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + +#endif + + public static void NotEmpty( + [NotNull] T? value, + [CallerArgumentExpression("value")] string argumentName = "") + where T : IEnumerable + { + if (value is null) + { + return; + } + + if (value is ICollection {Count: 0}) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + if (value is ICollection {Count: 0}) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + if (value is IReadOnlyCollection {Count: 0}) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + if (value is T[] {Length: 0}) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + var enumerator = value.GetEnumerator(); + try + { + if (!enumerator.MoveNext()) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + } + finally + { + if (enumerator is IDisposable disposable) + { + disposable.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNull.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNull.cs new file mode 100644 index 000000000..2f380c3a6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNull.cs @@ -0,0 +1,39 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif +static partial class Guard +{ + public static T NotNull( + [NotNull] T? argument, + [CallerArgumentExpression("argument")] string? name = null) + where T : class + { + if (argument is null) + { + throw new ArgumentNullException(name); + } + + return argument; + } + + public static string NotNull( + [NotNull] string? argument, + [CallerArgumentExpression("argument")] string? name = null) + { + if (argument is null) + { + throw new ArgumentNullException(name); + } + + return argument; + } +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrEmpty.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrEmpty.cs new file mode 100644 index 000000000..c50f2b1f3 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrEmpty.cs @@ -0,0 +1,106 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Runtime.CompilerServices; +using System; +using System.Collections; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Guard +{ + public static string NotNullOrEmpty( + [NotNull] string? value, + [CallerArgumentExpression("value")] string argumentName = "") + { +#if NET7_0_OR_GREATER + ArgumentException.ThrowIfNullOrEmpty(value, argumentName); + return value; +#else + if (value is null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + return value; +#endif + } + + public static T NotNullOrEmpty( + [NotNull] T? value, + [CallerArgumentExpression("value")] string argumentName = "") + where T : IEnumerable + { + if (value is null) + { + throw new ArgumentNullException(argumentName); + } + + NotEmpty(value); + + return value; + } + + +#if FeatureMemory + public static Memory NotNullOrEmpty( + [NotNull] Memory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return value.Value; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } + + public static ReadOnlyMemory NotNullOrEmpty( + [NotNull] ReadOnlyMemory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return value.Value; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs new file mode 100644 index 000000000..fc934f6bd --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotNullOrWhiteSpace.cs @@ -0,0 +1,97 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Runtime.CompilerServices; +using System; +using System.Diagnostics.CodeAnalysis; + +#if PolyPublic +public +#endif + +static partial class Guard +{ + public static string NotNullOrWhiteSpace( + [NotNull] string? value, + [CallerArgumentExpression("value")] string argumentName = "") + { +#if NET8_0_OR_GREATER + ArgumentException.ThrowIfNullOrWhiteSpace(value, argumentName); + return value; +#else + if (value == null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value) + { + if (!char.IsWhiteSpace(ch)) + { + return value; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); +#endif + } + +#if FeatureMemory + public static Memory NotNullOrWhiteSpace( + [NotNull] Memory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return value.Value; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } + + public static ReadOnlyMemory NotNullOrWhiteSpace( + [NotNull] ReadOnlyMemory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + throw new ArgumentNullException(argumentName); + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return value.Value; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotWhiteSpace.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotWhiteSpace.cs new file mode 100644 index 000000000..40068526c --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Guard/Guard_NotWhiteSpace.cs @@ -0,0 +1,135 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Runtime.CompilerServices; +using System; + +#if PolyPublic +public +#endif + +static partial class Guard +{ + public static void NotWhiteSpace( + string? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + return; + } +#if NET8_0_OR_GREATER + ArgumentException.ThrowIfNullOrWhiteSpace(value, argumentName); +#else + + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value) + { + if (!char.IsWhiteSpace(ch)) + { + return; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); +#endif + } +#if FeatureMemory + + public static void NotWhiteSpace( + ReadOnlySpan value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value) + { + if (!char.IsWhiteSpace(ch)) + { + return; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } + + public static void NotWhiteSpace( + Memory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + return; + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } + + public static void NotWhiteSpace( + ReadOnlyMemory? value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value == null) + { + return; + } + + if (value.Value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value.Value.Span) + { + if (!char.IsWhiteSpace(ch)) + { + return; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } + + public static void NotWhiteSpace( + Span value, + [CallerArgumentExpression("value")] string argumentName = "") + { + if (value.Length == 0) + { + throw new ArgumentException("Argument cannot be empty.", argumentName); + } + + foreach (var ch in value) + { + if (!char.IsWhiteSpace(ch)) + { + return; + } + } + + throw new ArgumentException("Argument cannot be whitespace.", argumentName); + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/GuidPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/GuidPolyfill.cs new file mode 100644 index 000000000..37aa5d4c9 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/GuidPolyfill.cs @@ -0,0 +1,132 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static class GuidPolyfill +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse#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 + + /// Creates a new according to RFC 9562, following the Version 7 format. + /// A new according to RFC 9562, following the Version 7 format. + /// + /// This uses to determine the Unix Epoch timestamp source. + /// This seeds the rand_a and rand_b sub-fields with random data. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7#system-guid-createversion7 + public static Guid CreateVersion7() => CreateVersion7(DateTimeOffset.UtcNow); + + /// Creates a new according to RFC 9562, following the Version 7 format. + /// The date time offset used to determine the Unix Epoch timestamp. + /// A new according to RFC 9562, following the Version 7 format. + /// represents an offset prior to . + /// + /// This seeds the rand_a and rand_b sub-fields with random data. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7#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(); + + 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 randomBytes = uuidBytes.AsSpan().Slice(6); + + RandomNumberGenerator.Fill(randomBytes); + + uuidBytes[6] &= 0x0F; + uuidBytes[6] += 0x70; + + return new(uuidBytes, true); + +#else + + var randomBytes = new byte[10]; + + 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); + + uuidBytes[6] = (byte)((uuidBytes[6] & 0x0F) | 0x70); + + uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80); + + 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#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 NETFRAMEWORK || NETCOREAPP2_0 || NETSTANDARD2_0 + Guid.TryParseExact(target.ToString(), format.ToString(), out result); +#else + Guid.TryParseExact(target, format, 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#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); +#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#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); +#endif + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Index.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Index.cs new file mode 100644 index 000000000..184759668 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Index.cs @@ -0,0 +1,154 @@ +// +#pragma warning disable + +#if (NET46X && FeatureValueTuple) || NET47X || NET48X || NETSTANDARD2_0 || NETCOREAPP2X + +namespace System; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Runtime.CompilerServices; + +/// Represent a type can be used to index a collection either from the start or the end. +/// +/// Index is used by the C# compiler to support the new index syntax +/// +/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; +/// int lastElement = someArray[^1]; // lastElement = 5 +/// +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +readonly struct Index : IEquatable +{ + readonly int _value; + + /// Construct an Index using a value and indicating if the index is from the start or from the end. + /// The index value. it has to be zero or positive number. + /// Indicating if the index is from the start or from the end. + /// + /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) + { + if (value < 0) + { + throw new ArgumentOutOfRangeException(nameof(value)); + } + + if (fromEnd) + { + _value = ~value; + } + else + { + _value = value; + } + } + + // The following private constructors mainly created for perf reason to avoid the checks + Index(int value) => + _value = value; + + /// Create an Index pointing at first element. + public static Index Start => new(0); + + /// Create an Index pointing at beyond last element. + public static Index End => new(~0); + + /// Create an Index from the start at the position indicated by the value. + /// The index value from the start. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + { + throw new IndexOutOfRangeException(nameof(value)); + } + + return new(value); + } + + /// Create an Index from the end at the position indicated by the value. + /// The index value from the end. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + { + throw new IndexOutOfRangeException(nameof(value)); + } + + return new(~value); + } + + /// Returns the index value. + public int Value + { + get + { + if (_value < 0) + { + return ~_value; + } + + return _value; + } + } + + /// Indicates whether the index is from the start or the end. + public bool IsFromEnd => _value < 0; + + /// Calculate the offset from the start using the giving collection length. + /// The length of the collection that the Index will be used with. length has to be a positive value + /// + /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. + /// we don't validate either the returned offset is greater than the input length. + /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and + /// then used to index a collection will get out of range exception which will be same affect as the validation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + var offset = _value; + if (IsFromEnd) + { + offset += length + 1; + } + + return offset; + } + + /// Indicates whether the current Index object is equal to another object of the same type. + /// An object to compare with this object + public override bool Equals(object value) => value is Index index && _value == index._value; + + /// Indicates whether the current Index object is equal to another Index object. + /// An object to compare with this object + public bool Equals(Index other) => _value == other._value; + + /// Returns the hash code for this instance. + public override int GetHashCode() => _value; + + /// Converts integer number to an Index. + public static implicit operator Index(int value) => FromStart(value); + + /// Converts the value of the current Index object to its equivalent string representation. + public override string ToString() + { + if (IsFromEnd) + { + return ToStringFromEnd(); + } + + return ((uint)Value).ToString(); + } + + string ToStringFromEnd() => + '^' + Value.ToString(); +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Range.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Range.cs new file mode 100644 index 000000000..4c853ca0f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IndexRange/Range.cs @@ -0,0 +1,81 @@ +// +#pragma warning disable + +#if (NET46X && FeatureValueTuple) || NET47X || NET48X || NETSTANDARD2_0 || NETCOREAPP2X + +namespace System; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Runtime.CompilerServices; + +/// Represent a range has start and end indexes. +/// +/// Range is used by the C# compiler to support the range syntax. +/// +/// int[] someArray = new int[5] { 1, 2, 3, 4, 5 }; +/// int[] subArray1 = someArray[0..2]; // { 1, 2 } +/// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 } +/// +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +record Range(Index Start, Index End) +{ + /// Converts the value of the current Range object to its equivalent string representation. + public override string ToString() => + $"{Start}..{End}"; + + /// Create a Range object starting from start index to the end of the collection. + public static Range StartAt(Index start) => new(start, Index.End); + + /// Create a Range object starting from first element in the collection to the end Index. + public static Range EndAt(Index end) => new(Index.Start, end); + + /// Create a Range object starting from first element to the end. + public static Range All => new(Index.Start, Index.End); + + /// Calculate the start offset and length of range object using a collection length. + /// The length of the collection that the range will be used with. length has to be a positive value. + /// + /// For performance reason, we don't validate the input length parameter against negative values. + /// It is expected Range will be used with collections which always have non negative length/count. + /// We validate the range is inside the length scope though. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public (int Offset, int Length) GetOffsetAndLength(int length) + { + int start; + var startIndex = Start; + if (startIndex.IsFromEnd) + { + start = length - startIndex.Value; + } + else + { + start = startIndex.Value; + } + + int end; + var endIndex = End; + if (endIndex.IsFromEnd) + { + end = length - endIndex.Value; + } + else + { + end = endIndex.Value; + } + + if ((uint)end > (uint)length || (uint)start > (uint)end) + { + throw new ArgumentOutOfRangeException(nameof(length)); + } + + return (start, end - start); + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IsExternalInit.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IsExternalInit.cs new file mode 100644 index 000000000..10bc30604 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/IsExternalInit.cs @@ -0,0 +1,22 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// Reserved to be used by the compiler for tracking metadata. This class should not be used by developers in source code. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.isexternalinit +#if PolyPublic +public +#endif +static class IsExternalInit; + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/KeyValuePair.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/KeyValuePair.cs new file mode 100644 index 000000000..6d704f6a4 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/KeyValuePair.cs @@ -0,0 +1,34 @@ +// +#pragma warning disable + +#if (NETFRAMEWORK || NETSTANDARD2_0) + +#nullable enable + +namespace System.Collections.Generic; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +// Provides the Create factory method for KeyValuePair. +// https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair +#if PolyPublic +public +#endif +static class KeyValuePair +{ + /// + /// Creates a new key/value pair instance using provided values. + /// + /// The key of the new to be created. + /// The value of the new to be created. + /// The type of the key. + /// The type of the value. + /// A key/value pair containing the provided arguments as values. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair.create + public static KeyValuePair Create(TKey key, TValue value) => + new KeyValuePair(key, value); +} +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Lock.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Lock.cs new file mode 100644 index 000000000..64bfcd991 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Lock.cs @@ -0,0 +1,182 @@ +// +#pragma warning disable + +#nullable enable + +#if !NET9_0_OR_GREATER + +namespace System.Threading; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Provides a way to get mutual exclusion in regions of code between different threads. A lock may be held by one thread at +/// a time. +/// +/// +/// Threads that cannot immediately enter the lock may wait for the lock to be exited or until a specified timeout. A thread +/// that holds a lock may enter the lock repeatedly without exiting it, such as recursively, in which case the thread should +/// eventually exit the lock the same number of times to fully exit the lock and allow other threads to enter the lock. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.lock +#if PolyPublic +public +#endif +class Lock +{ +#if NETCOREAPP || NETFRAMEWORK || NETSTANDARD + public bool IsHeldByCurrentThread => Monitor.IsEntered(this); +#endif + + /// + /// Enters the lock. Once the method returns, the calling thread would be the only thread that holds the lock. + /// + /// + /// If the lock cannot be entered immediately, the calling thread waits for the lock to be exited. If the lock is + /// already held by the calling thread, the lock is entered again. The calling thread should exit the lock as many times + /// as it had entered the lock to fully exit the lock and allow other threads to enter the lock. + /// + /// + /// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high + /// enough that it would typically not be reached when the lock is used properly. + /// + public void Enter() => Monitor.Enter(this); + + /// + /// Tries to enter the lock without waiting. If the lock is entered, the calling thread would be the only thread that + /// holds the lock. + /// + /// + /// true if the lock was entered, false otherwise. + /// + /// + /// If the lock cannot be entered immediately, the method returns false. If the lock is already held by the + /// calling thread, the lock is entered again. The calling thread should exit the lock as many times as it had entered + /// the lock to fully exit the lock and allow other threads to enter the lock. + /// + /// + /// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high + /// enough that it would typically not be reached when the lock is used properly. + /// + public bool TryEnter() => Monitor.TryEnter(this); + + /// + /// Tries to enter the lock, waiting for roughly the specified duration. If the lock is entered, the calling thread + /// would be the only thread that holds the lock. + /// + /// + /// The rough duration for which the method will wait if the lock is not available. The timeout is converted to a number + /// of milliseconds by casting of the timeout to an integer value. A value + /// representing 0 milliseconds specifies that the method should not wait, and a value representing + /// or -1 milliseconds specifies that the method should wait indefinitely + /// until the lock is entered. + /// + /// + /// true if the lock was entered, false otherwise. + /// + /// + /// If the lock cannot be entered immediately, the calling thread waits for roughly the specified duration for the lock + /// to be exited. If the lock is already held by the calling thread, the lock is entered again. The calling thread + /// should exit the lock as many times as it had entered the lock to fully exit the lock and allow other threads to + /// enter the lock. + /// + /// + /// , after its conversion to an integer millisecond value, represents a value that is less + /// than -1 milliseconds or greater than milliseconds. + /// + /// + /// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high + /// enough that it would typically not be reached when the lock is used properly. + /// + public bool TryEnter(TimeSpan timeout) => + Monitor.TryEnter(this, timeout); + + /// + /// Tries to enter the lock, waiting for roughly the specified duration. If the lock is entered, the calling thread + /// would be the only thread that holds the lock. + /// + /// + /// The rough duration in milliseconds for which the method will wait if the lock is not available. A value of + /// 0 specifies that the method should not wait, and a value of or + /// -1 specifies that the method should wait indefinitely until the lock is entered. + /// + /// + /// true if the lock was entered, false otherwise. + /// + /// + /// If the lock cannot be entered immediately, the calling thread waits for roughly the specified duration for the lock + /// to be exited. If the lock is already held by the calling thread, the lock is entered again. The calling thread + /// should exit the lock as many times as it had entered the lock to fully exit the lock and allow other threads to + /// enter the lock. + /// + /// + /// is less than -1. + /// + /// + /// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high + /// enough that it would typically not be reached when the lock is used properly. + /// + public bool TryEnter(int millisecondsTimeout) => + TryEnter(TimeSpan.FromMilliseconds(millisecondsTimeout)); + + /// + /// Exits the lock. + /// + /// + /// If the calling thread holds the lock multiple times, such as recursively, the lock is exited only once. The + /// calling thread should ensure that each enter is matched with an exit. + /// + /// + /// The calling thread does not hold the lock. + /// + public void Exit() => Monitor.Exit(this); + + /// + /// Enters the lock and returns a that may be disposed to exit the lock. Once the method returns, + /// the calling thread would be the only thread that holds the lock. This method is intended to be used along with a + /// language construct that would automatically dispose the , such as with the C# using + /// statement. + /// + /// + /// A that may be disposed to exit the lock. + /// + /// + /// If the lock cannot be entered immediately, the calling thread waits for the lock to be exited. If the lock is + /// already held by the calling thread, the lock is entered again. The calling thread should exit the lock, such as by + /// disposing the returned , as many times as it had entered the lock to fully exit the lock and + /// allow other threads to enter the lock. + /// + /// + /// The lock has reached the limit of recursive enters. The limit is implementation-defined, but is expected to be high + /// enough that it would typically not be reached when the lock is used properly. + /// + public Scope EnterScope() + { + Enter(); + return new Scope(this); + } + + /// + /// A disposable structure that is returned by , which when disposed, exits the lock. + /// + public readonly ref struct Scope(Lock owner) + { + /// + /// Exits the lock. + /// + /// + /// If the calling thread holds the lock multiple times, such as recursively, the lock is exited only once. The + /// calling thread should ensure that each enter is matched with an exit. + /// + /// + /// The calling thread does not hold the lock. + /// + public void Dispose() => owner.Exit(); + } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ModuleInitializerAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ModuleInitializerAttribute.cs new file mode 100644 index 000000000..eb6d30a64 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ModuleInitializerAttribute.cs @@ -0,0 +1,42 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +/// +/// Used to indicate to the compiler that a method should be called +/// in its containing module's initializer. +/// +/// +/// When one or more valid methods +/// with this attribute are found in a compilation, the compiler will +/// emit a module initializer which calls each of the attributed methods. +/// +/// Certain requirements are imposed on any method targeted with this attribute: +/// - The method must be `static`. +/// - The method must be an ordinary member method, as opposed to a property accessor, constructor, local function, etc. +/// - The method must be parameterless. +/// - The method must return `void`. +/// - The method must not be generic or be contained in a generic type. +/// - The method's effective accessibility must be `internal` or `public`. +/// +/// The specification for module initializers in the .NET runtime can be found here: +/// https://github.com/dotnet/runtime/blob/master/docs/design/specs/Ecma-335-Augments.md#module-initializer +/// +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: AttributeTargets.Method, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class ModuleInitializerAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfo.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfo.cs new file mode 100644 index 000000000..997770a41 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfo.cs @@ -0,0 +1,81 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +#nullable enable + +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Reflection; + +using Diagnostics.CodeAnalysis; +using Diagnostics; + +/// +/// A class that represents nullability info +/// +[DebuggerNonUserCode] +[ExcludeFromCodeCoverage] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.nullabilityinfo +#if PolyPublic +public +#endif +sealed class NullabilityInfo +{ + internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState writeState, NullabilityInfo? elementType, NullabilityInfo[] typeArguments) + { + Type = type; + ReadState = readState; + WriteState = writeState; + ElementType = elementType; + GenericTypeArguments = typeArguments; + } + + /// + /// The of the member or generic parameter + /// to which this NullabilityInfo belongs + /// + public Type Type { get; } + /// + /// The nullability read state of the member + /// + public NullabilityState ReadState { get; internal set; } + /// + /// The nullability write state of the member + /// + public NullabilityState WriteState { get; internal set; } + /// + /// If the member type is an array, gives the of the elements of the array, null otherwise + /// + public NullabilityInfo? ElementType { get; } + /// + /// If the member type is a generic type, gives the array of for each type parameter + /// + public NullabilityInfo[] GenericTypeArguments { get; } +} + +/// +/// An enum that represents nullability state +/// +#if PolyPublic +public +#endif +enum NullabilityState +{ + /// + /// Nullability context not enabled (oblivious) + /// + Unknown, + /// + /// Non nullable value or reference type + /// + NotNull, + /// + /// Nullable value or reference type + /// + Nullable +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoContext.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoContext.cs new file mode 100644 index 000000000..6c4829fb2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoContext.cs @@ -0,0 +1,669 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +#nullable enable + +namespace System.Reflection; + +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Collections.Generic; +using Collections.ObjectModel; +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// Provides APIs for populating nullability information/context from reflection members: +/// , , and . +/// +[DebuggerNonUserCode] +[ExcludeFromCodeCoverage] +#if PolyPublic +public +#endif +sealed class NullabilityInfoContext +{ + const string CompilerServicesNameSpace = "System.Runtime.CompilerServices"; + Dictionary _publicOnlyModules = new(); + Dictionary _context = new(); + + internal static bool IsSupported { get; } = + AppContext.TryGetSwitch("System.Reflection.NullabilityInfoContext.IsSupported", out bool isSupported) ? isSupported : true; + + [Flags] + enum NotAnnotatedStatus + { + // no restriction, all members annotated + None = 0x0, + + // private members not annotated + Private = 0x1, + + // internal members not annotated + Internal = 0x2 + } + + NullabilityState? GetNullableContext(MemberInfo? memberInfo) + { + while (memberInfo != null) + { + if (_context.TryGetValue(memberInfo, out NullabilityState state)) + { + return state; + } + + foreach (CustomAttributeData attribute in memberInfo.GetCustomAttributesData()) + { + if (attribute.AttributeType.Name == "NullableContextAttribute" && + attribute.AttributeType.Namespace == CompilerServicesNameSpace && + attribute.ConstructorArguments.Count == 1) + { + state = TranslateByte(attribute.ConstructorArguments[0].Value); + _context.Add(memberInfo, state); + return state; + } + } + + memberInfo = memberInfo.DeclaringType; + } + + return null; + } + + /// + /// Populates for the given . + /// If the nullablePublicOnly feature is set for an assembly, like it does in .NET SDK, the private and/or internal member's + /// nullability attributes are omitted, in this case the API will return NullabilityState.Unknown state. + /// + /// The parameter which nullability info gets populated + /// If the parameterInfo parameter is null + /// + public NullabilityInfo Create(ParameterInfo parameterInfo) + { + EnsureIsSupported(); + + IList attributes = parameterInfo.GetCustomAttributesData(); + NullableAttributeStateParser parser = parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method) + ? NullableAttributeStateParser.Unknown + : CreateParser(attributes); + NullabilityInfo nullability = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, parser); + + if (nullability.ReadState != NullabilityState.Unknown) + { + CheckParameterMetadataType(parameterInfo, nullability); + } + + CheckNullabilityAttributes(nullability, attributes); + return nullability; + } + + void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability) + { + ParameterInfo? metaParameter; + MemberInfo metaMember; + + switch (parameter.Member) + { + case ConstructorInfo ctor: + var metaCtor = (ConstructorInfo)GetMemberMetadataDefinition(ctor); + metaMember = metaCtor; + metaParameter = GetMetaParameter(metaCtor, parameter); + break; + + case MethodInfo method: + MethodInfo metaMethod = GetMethodMetadataDefinition(method); + metaMember = metaMethod; + metaParameter = string.IsNullOrEmpty(parameter.Name) ? metaMethod.ReturnParameter : GetMetaParameter(metaMethod, parameter); + break; + + default: + return; + } + + if (metaParameter != null) + { + CheckGenericParameters(nullability, metaMember, metaParameter.ParameterType, parameter.Member.ReflectedType); + } + } + + static ParameterInfo? GetMetaParameter(MethodBase metaMethod, ParameterInfo parameter) + { + var parameters = metaMethod.GetParameters(); + for (int i = 0; i < parameters.Length; i++) + { + if (parameter.Position == i && + parameter.Name == parameters[i].Name) + { + return parameters[i]; + } + } + + return null; + } + + static MethodInfo GetMethodMetadataDefinition(MethodInfo method) + { + if (method.IsGenericMethod && !method.IsGenericMethodDefinition) + { + method = method.GetGenericMethodDefinition(); + } + + return (MethodInfo)GetMemberMetadataDefinition(method); + } + + static void CheckNullabilityAttributes(NullabilityInfo nullability, IList attributes) + { + var codeAnalysisReadState = NullabilityState.Unknown; + var codeAnalysisWriteState = NullabilityState.Unknown; + + foreach (CustomAttributeData attribute in attributes) + { + if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis") + { + if (attribute.AttributeType.Name == "NotNullAttribute") + { + codeAnalysisReadState = NullabilityState.NotNull; + } + else if ((attribute.AttributeType.Name == "MaybeNullAttribute" || + attribute.AttributeType.Name == "MaybeNullWhenAttribute") && + codeAnalysisReadState == NullabilityState.Unknown && + !IsValueTypeOrValueTypeByRef(nullability.Type)) + { + codeAnalysisReadState = NullabilityState.Nullable; + } + else if (attribute.AttributeType.Name == "DisallowNullAttribute") + { + codeAnalysisWriteState = NullabilityState.NotNull; + } + else if (attribute.AttributeType.Name == "AllowNullAttribute" && + codeAnalysisWriteState == NullabilityState.Unknown && + !IsValueTypeOrValueTypeByRef(nullability.Type)) + { + codeAnalysisWriteState = NullabilityState.Nullable; + } + } + } + + if (codeAnalysisReadState != NullabilityState.Unknown) + { + nullability.ReadState = codeAnalysisReadState; + } + if (codeAnalysisWriteState != NullabilityState.Unknown) + { + nullability.WriteState = codeAnalysisWriteState; + } + } + + /// + /// Populates for the given . + /// If the nullablePublicOnly feature is set for an assembly, like it does in .NET SDK, the private and/or internal member's + /// nullability attributes are omitted, in this case the API will return NullabilityState.Unknown state. + /// + /// The parameter which nullability info gets populated + /// If the propertyInfo parameter is null + /// + public NullabilityInfo Create(PropertyInfo propertyInfo) + { + EnsureIsSupported(); + + MethodInfo? getter = propertyInfo.GetGetMethod(true); + MethodInfo? setter = propertyInfo.GetSetMethod(true); + bool annotationsDisabled = (getter == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getter)) + && (setter == null || IsPrivateOrInternalMethodAndAnnotationDisabled(setter)); + NullableAttributeStateParser parser = annotationsDisabled ? NullableAttributeStateParser.Unknown : CreateParser(propertyInfo.GetCustomAttributesData()); + NullabilityInfo nullability = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, parser); + + if (getter != null) + { + CheckNullabilityAttributes(nullability, getter.ReturnParameter.GetCustomAttributesData()); + } + else + { + nullability.ReadState = NullabilityState.Unknown; + } + + if (setter != null) + { + var parameters = setter.GetParameters(); + + CheckNullabilityAttributes(nullability, parameters[parameters.Length-1].GetCustomAttributesData()); + } + else + { + nullability.WriteState = NullabilityState.Unknown; + } + + return nullability; + } + + bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method) => + (method.IsPrivate || method.IsFamilyAndAssembly || method.IsAssembly) && + IsPublicOnly(method.IsPrivate, method.IsFamilyAndAssembly, method.IsAssembly, method.Module); + + /// + /// Populates for the given . + /// If the nullablePublicOnly feature is set for an assembly, like it does in .NET SDK, the private and/or internal member's + /// nullability attributes are omitted, in this case the API will return NullabilityState.Unknown state. + /// + /// The parameter which nullability info gets populated + /// If the eventInfo parameter is null + /// + public NullabilityInfo Create(EventInfo eventInfo) + { + EnsureIsSupported(); + + return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType!, CreateParser(eventInfo.GetCustomAttributesData())); + } + + /// + /// Populates for the given + /// If the nullablePublicOnly feature is set for an assembly, like it does in .NET SDK, the private and/or internal member's + /// nullability attributes are omitted, in this case the API will return NullabilityState.Unknown state. + /// + /// The parameter which nullability info gets populated + /// If the fieldInfo parameter is null + /// + public NullabilityInfo Create(FieldInfo fieldInfo) + { + EnsureIsSupported(); + + IList attributes = fieldInfo.GetCustomAttributesData(); + NullableAttributeStateParser parser = IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(attributes); + NullabilityInfo nullability = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser); + CheckNullabilityAttributes(nullability, attributes); + return nullability; + } + + static void EnsureIsSupported() + { + if (!IsSupported) + { + throw new InvalidOperationException("NullabilityInfoContext is not supported"); + } + } + + bool IsPrivateOrInternalFieldAndAnnotationDisabled(FieldInfo fieldInfo) => + (fieldInfo.IsPrivate || fieldInfo.IsFamilyAndAssembly || fieldInfo.IsAssembly) && + IsPublicOnly(fieldInfo.IsPrivate, fieldInfo.IsFamilyAndAssembly, fieldInfo.IsAssembly, fieldInfo.Module); + + bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssembly, Module module) + { + if (!_publicOnlyModules.TryGetValue(module, out NotAnnotatedStatus value)) + { + value = PopulateAnnotationInfo(module.GetCustomAttributesData()); + _publicOnlyModules.Add(module, value); + } + + if (value == NotAnnotatedStatus.None) + { + return false; + } + + if ((isPrivate || isFamilyAndAssembly) && value.HasFlag(NotAnnotatedStatus.Private) || + isAssembly && value.HasFlag(NotAnnotatedStatus.Internal)) + { + return true; + } + + return false; + } + + static NotAnnotatedStatus PopulateAnnotationInfo(IList customAttributes) + { + foreach (CustomAttributeData attribute in customAttributes) + { + if (attribute.AttributeType.Name == "NullablePublicOnlyAttribute" && + attribute.AttributeType.Namespace == CompilerServicesNameSpace && + attribute.ConstructorArguments.Count == 1) + { + if (attribute.ConstructorArguments[0].Value is bool boolValue && boolValue) + { + return NotAnnotatedStatus.Internal | NotAnnotatedStatus.Private; + } + else + { + return NotAnnotatedStatus.Private; + } + } + } + + return NotAnnotatedStatus.None; + } + + NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser) + { + int index = 0; + NullabilityInfo nullability = GetNullabilityInfo(memberInfo, type, parser, ref index); + + if (nullability.ReadState != NullabilityState.Unknown) + { + TryLoadGenericMetaTypeNullability(memberInfo, nullability); + } + + return nullability; + } + + NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser, ref int index) + { + NullabilityState state = NullabilityState.Unknown; + NullabilityInfo? elementState = null; + NullabilityInfo[] genericArgumentsState = Array.Empty(); + Type underlyingType = type; + + if (underlyingType.IsByRef || underlyingType.IsPointer) + { + underlyingType = underlyingType.GetElementType()!; + } + + if (underlyingType.IsValueType) + { + if (Nullable.GetUnderlyingType(underlyingType) is { } nullableUnderlyingType) + { + underlyingType = nullableUnderlyingType; + state = NullabilityState.Nullable; + } + else + { + state = NullabilityState.NotNull; + } + + if (underlyingType.IsGenericType) + { + ++index; + } + } + else + { + if (!parser.ParseNullableState(index++, ref state) + && GetNullableContext(memberInfo) is { } contextState) + { + state = contextState; + } + + if (underlyingType.IsArray) + { + elementState = GetNullabilityInfo(memberInfo, underlyingType.GetElementType()!, parser, ref index); + } + } + + if (underlyingType.IsGenericType) + { + Type[] genericArguments = underlyingType.GetGenericArguments(); + genericArgumentsState = new NullabilityInfo[genericArguments.Length]; + + for (int i = 0; i < genericArguments.Length; i++) + { + genericArgumentsState[i] = GetNullabilityInfo(memberInfo, genericArguments[i], parser, ref index); + } + } + + return new NullabilityInfo(type, state, state, elementState, genericArgumentsState); + } + + static NullableAttributeStateParser CreateParser(IList customAttributes) + { + foreach (CustomAttributeData attribute in customAttributes) + { + if (attribute.AttributeType.Name == "NullableAttribute" && + attribute.AttributeType.Namespace == CompilerServicesNameSpace && + attribute.ConstructorArguments.Count == 1) + { + return new NullableAttributeStateParser(attribute.ConstructorArguments[0].Value); + } + } + + return new NullableAttributeStateParser(null); + } + + void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability) + { + MemberInfo? metaMember = GetMemberMetadataDefinition(memberInfo); + Type? metaType = null; + if (metaMember is FieldInfo field) + { + metaType = field.FieldType; + } + else if (metaMember is PropertyInfo property) + { + metaType = GetPropertyMetaType(property); + } + + if (metaType != null) + { + CheckGenericParameters(nullability, metaMember!, metaType, memberInfo.ReflectedType); + } + } + + static MemberInfo GetMemberMetadataDefinition(MemberInfo member) + { + Type? type = member.DeclaringType; + if ((type != null) && + type.IsGenericType && + !type.IsGenericTypeDefinition) + { + return type.GetGenericTypeDefinition().GetMemberWithSameMetadataDefinitionAs(member); + } + + return member; + } + + static Type GetPropertyMetaType(PropertyInfo property) + { + if (property.GetGetMethod(true) is MethodInfo method) + { + return method.ReturnType; + } + + return property.GetSetMethod(true)!.GetParameters()[0].ParameterType; + } + + void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType, Type? reflectedType) + { + if (metaType.IsGenericParameter) + { + if (nullability.ReadState == NullabilityState.NotNull) + { + TryUpdateGenericParameterNullability(nullability, metaType, reflectedType); + } + } + else if (metaType.ContainsGenericParameters) + { + if (nullability.GenericTypeArguments.Length > 0) + { + Type[] genericArguments = metaType.GetGenericArguments(); + + for (int i = 0; i < genericArguments.Length; i++) + { + CheckGenericParameters(nullability.GenericTypeArguments[i], metaMember, genericArguments[i], reflectedType); + } + } + else if (nullability.ElementType is { } elementNullability && metaType.IsArray) + { + CheckGenericParameters(elementNullability, metaMember, metaType.GetElementType()!, reflectedType); + } + // We could also follow this branch for metaType.IsPointer, but since pointers must be unmanaged this + // will be a no-op regardless + else if (metaType.IsByRef) + { + CheckGenericParameters(nullability, metaMember, metaType.GetElementType()!, reflectedType); + } + } + } + + bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, Type genericParameter, Type? reflectedType) + { + Debug.Assert(genericParameter.IsGenericParameter); + + if (reflectedType is not null + && !genericParameter.IsGenericMethodParameter() + && TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, reflectedType, reflectedType)) + { + return true; + } + + if (IsValueTypeOrValueTypeByRef(nullability.Type)) + { + return true; + } + + var state = NullabilityState.Unknown; + if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state)) + { + nullability.ReadState = state; + nullability.WriteState = state; + return true; + } + + if (GetNullableContext(genericParameter) is { } contextState) + { + nullability.ReadState = contextState; + nullability.WriteState = contextState; + return true; + } + + return false; + } + + bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType) + { + Debug.Assert(genericParameter.IsGenericParameter && !genericParameter.IsGenericMethodParameter()); + + Type contextTypeDefinition = context.IsGenericType && !context.IsGenericTypeDefinition ? context.GetGenericTypeDefinition() : context; + if (genericParameter.DeclaringType == contextTypeDefinition) + { + return false; + } + + Type? baseType = contextTypeDefinition.BaseType; + if (baseType is null) + { + return false; + } + + if (!baseType.IsGenericType + || (baseType.IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition()) != genericParameter.DeclaringType) + { + return TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, baseType, reflectedType); + } + + Type[] genericArguments = baseType.GetGenericArguments(); + Type genericArgument = genericArguments[genericParameter.GenericParameterPosition]; + if (genericArgument.IsGenericParameter) + { + return TryUpdateGenericParameterNullability(nullability, genericArgument, reflectedType); + } + + NullableAttributeStateParser parser = CreateParser(contextTypeDefinition.GetCustomAttributesData()); + int nullabilityStateIndex = 1; // start at 1 since index 0 is the type itself + for (int i = 0; i < genericParameter.GenericParameterPosition; i++) + { + nullabilityStateIndex += CountNullabilityStates(genericArguments[i]); + } + return TryPopulateNullabilityInfo(nullability, parser, ref nullabilityStateIndex); + + static int CountNullabilityStates(Type type) + { + Type underlyingType = Nullable.GetUnderlyingType(type) ?? type; + if (underlyingType.IsGenericType) + { + int count = 1; + foreach (Type genericArgument in underlyingType.GetGenericArguments()) + { + count += CountNullabilityStates(genericArgument); + } + return count; + } + + if (underlyingType.HasElementType) + { + return (underlyingType.IsArray ? 1 : 0) + CountNullabilityStates(underlyingType.GetElementType()!); + } + + return type.IsValueType ? 0 : 1; + } + } + + static bool TryPopulateNullabilityInfo(NullabilityInfo nullability, NullableAttributeStateParser parser, ref int index) + { + bool isValueType = IsValueTypeOrValueTypeByRef(nullability.Type); + if (!isValueType) + { + var state = NullabilityState.Unknown; + if (!parser.ParseNullableState(index, ref state)) + { + return false; + } + + nullability.ReadState = state; + nullability.WriteState = state; + } + + if (!isValueType || (Nullable.GetUnderlyingType(nullability.Type) ?? nullability.Type).IsGenericType) + { + index++; + } + + if (nullability.GenericTypeArguments.Length > 0) + { + foreach (NullabilityInfo genericTypeArgumentNullability in nullability.GenericTypeArguments) + { + TryPopulateNullabilityInfo(genericTypeArgumentNullability, parser, ref index); + } + } + else if (nullability.ElementType is { } elementTypeNullability) + { + TryPopulateNullabilityInfo(elementTypeNullability, parser, ref index); + } + + return true; + } + + static NullabilityState TranslateByte(object? value) => + value is byte b ? TranslateByte(b) : NullabilityState.Unknown; + + static NullabilityState TranslateByte(byte b) => + b switch + { + 1 => NullabilityState.NotNull, + 2 => NullabilityState.Nullable, + _ => NullabilityState.Unknown + }; + + static bool IsValueTypeOrValueTypeByRef(Type type) => + type.IsValueType || ((type.IsByRef || type.IsPointer) && type.GetElementType()!.IsValueType); + + readonly struct NullableAttributeStateParser + { + static readonly object UnknownByte = (byte)0; + + readonly object? _nullableAttributeArgument; + + public NullableAttributeStateParser(object? nullableAttributeArgument) + { + this._nullableAttributeArgument = nullableAttributeArgument; + } + + public static NullableAttributeStateParser Unknown => new(UnknownByte); + + public bool ParseNullableState(int index, ref NullabilityState state) + { + switch (this._nullableAttributeArgument) + { + case byte b: + state = TranslateByte(b); + return true; + case ReadOnlyCollection args + when index < args.Count && args[index].Value is byte elementB: + state = TranslateByte(elementB); + return true; + default: + return false; + } + } + } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoExtensions.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoExtensions.cs new file mode 100644 index 000000000..ec0cc0c70 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullability/NullabilityInfoExtensions.cs @@ -0,0 +1,154 @@ +// +#pragma warning disable + +#nullable enable + +namespace Polyfills; +using System; +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 = []; + static ConcurrentDictionary properties = []; + static ConcurrentDictionary events = []; + static ConcurrentDictionary fields = []; + + public static NullabilityInfo GetNullabilityInfo(this MemberInfo info) + { + if (info is PropertyInfo propertyInfo) + { + return propertyInfo.GetNullabilityInfo(); + } + + if (info is EventInfo eventInfo) + { + return eventInfo.GetNullabilityInfo(); + } + + if (info is FieldInfo fieldInfo) + { + return fieldInfo.GetNullabilityInfo(); + } + + throw new ArgumentException($"Unsupported type:{info.GetType().FullName}"); + } + + public static NullabilityState GetNullability(this MemberInfo info) => + GetReadOrWriteState(info.GetNullabilityInfo()); + + public static bool IsNullable(this MemberInfo info) + { + var nullability = info.GetNullabilityInfo(); + return IsNullable(info.Name, nullability); + } + + public static NullabilityInfo GetNullabilityInfo(this FieldInfo info) => + fields.GetOrAdd( + info, + static inner => + { + var context = new NullabilityInfoContext(); + return context.Create(inner); + }); + + public static NullabilityState GetNullability(this FieldInfo info) => + GetReadOrWriteState(info.GetNullabilityInfo()); + + public static bool IsNullable(this FieldInfo info) + { + var nullability = info.GetNullabilityInfo(); + return IsNullable(info.Name, nullability); + } + + public static NullabilityInfo GetNullabilityInfo(this EventInfo info) => + events.GetOrAdd( + info, + static inner => + { + var context = new NullabilityInfoContext(); + return context.Create(inner); + }); + + public static NullabilityState GetNullability(this EventInfo info) => + GetReadOrWriteState(info.GetNullabilityInfo()); + + public static bool IsNullable(this EventInfo info) + { + var nullability = info.GetNullabilityInfo(); + return IsNullable(info.Name, nullability); + } + + public static NullabilityInfo GetNullabilityInfo(this PropertyInfo info) => + properties.GetOrAdd( + info, + static inner => + { + var context = new NullabilityInfoContext(); + return context.Create(inner); + }); + + public static NullabilityState GetNullability(this PropertyInfo info) => + GetReadOrWriteState(info.GetNullabilityInfo()); + + public static bool IsNullable(this PropertyInfo info) + { + var nullability = info.GetNullabilityInfo(); + return IsNullable(info.Name, nullability); + } + + public static NullabilityInfo GetNullabilityInfo(this ParameterInfo info) => + parameters.GetOrAdd( + info, + static inner => + { + var context = new NullabilityInfoContext(); + return context.Create(inner); + }); + + public static NullabilityState GetNullability(this ParameterInfo info) => + GetReadOrWriteState(info.GetNullabilityInfo()); + + public static bool IsNullable(this ParameterInfo info) + { + var nullability = info.GetNullabilityInfo(); + return IsNullable(info.Name!, nullability); + } + + static NullabilityState GetReadOrWriteState(NullabilityInfo info) + { + if (info.ReadState == NullabilityState.Unknown) + { + return info.WriteState; + } + + return info.ReadState; + } + + static NullabilityState GetKnownState(string name, NullabilityInfo info) + { + var read = info.ReadState; + if (read != NullabilityState.Unknown) + { + return read; + } + + var write = info.WriteState; + if (write != NullabilityState.Unknown) + { + return write; + } + + throw new($"The nullability of '{info.Type.FullName}.{name}' is unknown. Assembly: {info.Type.Assembly.FullName}."); + } + + static bool IsNullable(string name, NullabilityInfo info) => + GetKnownState(name, info) == NullabilityState.Nullable; +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/AllowNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/AllowNullAttribute.cs new file mode 100644 index 000000000..1a63d72c7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/AllowNullAttribute.cs @@ -0,0 +1,25 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that is allowed as an input even if the +/// corresponding type disallows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Parameter | + Targets.Property)] +#if PolyPublic +public +#endif +sealed class AllowNullAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DisallowNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DisallowNullAttribute.cs new file mode 100644 index 000000000..83f8817e7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DisallowNullAttribute.cs @@ -0,0 +1,25 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that is disallowed as an input even if the +/// corresponding type allows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Parameter | + Targets.Property)] +#if PolyPublic +public +#endif +sealed class DisallowNullAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnAttribute.cs new file mode 100644 index 000000000..ba8c66d0f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnAttribute.cs @@ -0,0 +1,21 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that a method that will never return under any circumstance. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: AttributeTargets.Method, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class DoesNotReturnAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnIfAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnIfAttribute.cs new file mode 100644 index 000000000..b00a1ff0d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/DoesNotReturnIfAttribute.cs @@ -0,0 +1,41 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that the method will not return if the associated +/// parameter is passed the specified value. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +#if PolyPublic +public +#endif +sealed class DoesNotReturnIfAttribute : + Attribute +{ + /// + /// Gets the condition parameter value. + /// Code after the method is considered unreachable by diagnostics if the argument + /// to the associated parameter matches this value. + /// + public bool ParameterValue { get; } + + /// + /// Initializes a new instance of the + /// class with the specified parameter value. + /// + /// + /// The condition parameter value. + /// Code after the method is considered unreachable by diagnostics if the argument + /// to the associated parameter matches this value. + /// + public DoesNotReturnIfAttribute(bool parameterValue) => + ParameterValue = parameterValue; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullAttribute.cs new file mode 100644 index 000000000..a8032c075 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullAttribute.cs @@ -0,0 +1,26 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that an output may be even if the +/// corresponding type disallows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Parameter | + Targets.Property | + Targets.ReturnValue)] +#if PolyPublic +public +#endif +sealed class MaybeNullAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullWhenAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullWhenAttribute.cs new file mode 100644 index 000000000..39fb70562 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MaybeNullWhenAttribute.cs @@ -0,0 +1,38 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that when a method returns , +/// the parameter may be even if the corresponding type disallows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +#if PolyPublic +public +#endif +sealed class MaybeNullWhenAttribute : + Attribute +{ + /// + /// Gets the return value condition. + /// If the method returns this value, the associated parameter may be . + /// + public bool ReturnValue { get; } + + /// + /// Initializes the attribute with the specified return value condition. + /// + /// + /// The return value condition. + /// If the method returns this value, the associated parameter may be . + /// + public MaybeNullWhenAttribute(bool returnValue) => + ReturnValue = returnValue; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullAttribute.cs new file mode 100644 index 000000000..efd492606 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullAttribute.cs @@ -0,0 +1,51 @@ +// +#pragma warning disable + +#if NETSTANDARD || NETFRAMEWORK || NETCOREAPPX + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that the method or property will ensure that the listed field and property members have +/// not- values. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Method | + Targets.Property, + Inherited = false, + AllowMultiple = true)] +#if PolyPublic +public +#endif +sealed class MemberNotNullAttribute : + Attribute +{ + /// + /// Gets field or property member names. + /// + public string[] Members { get; } + + /// + /// Initializes the attribute with a field or property member. + /// + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullAttribute(string member) => + Members = [member]; + + /// + /// Initializes the attribute with the list of field and property members. + /// + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullAttribute(params string[] members) => + Members = members; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullWhenAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullWhenAttribute.cs new file mode 100644 index 000000000..bf9ad2704 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/MemberNotNullWhenAttribute.cs @@ -0,0 +1,71 @@ +// +#pragma warning disable + +#if NETSTANDARD || NETFRAMEWORK || NETCOREAPPX + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that the method or property will ensure that the listed field and property members have +/// non- values when returning with the specified return value condition. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Method | + Targets.Property, + Inherited = false, + AllowMultiple = true)] +#if PolyPublic +public +#endif +sealed class MemberNotNullWhenAttribute : + Attribute +{ + /// + /// Gets the return value condition. + /// + public bool ReturnValue { get; } + + /// + /// Gets field or property member names. + /// + public string[] Members { get; } + + /// + /// Initializes the attribute with the specified return value condition and a field or property member. + /// + /// + /// The return value condition. If the method returns this value, + /// the associated parameter will not be . + /// + /// + /// The field or property member that is promised to be not-. + /// + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = [member]; + } + + /// + /// Initializes the attribute with the specified return value condition and list + /// of field and property members. + /// + /// + /// The return value condition. If the method returns this value, + /// the associated parameter will not be . + /// + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullAttribute.cs new file mode 100644 index 000000000..8b20fae69 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullAttribute.cs @@ -0,0 +1,26 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that an output is not even if the +/// corresponding type allows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Parameter | + Targets.Property | + Targets.ReturnValue)] +#if PolyPublic +public +#endif +sealed class NotNullAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullIfNotNullAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullIfNotNullAttribute.cs new file mode 100644 index 000000000..50afab438 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullIfNotNullAttribute.cs @@ -0,0 +1,41 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Parameter | + Targets.Property | + Targets.ReturnValue, + AllowMultiple = true)] +#if PolyPublic +public +#endif +sealed class NotNullIfNotNullAttribute : + Attribute +{ + /// + /// Gets the associated parameter name. + /// The output will be non- if the argument to the + /// parameter specified is non-. + /// + public string ParameterName { get; } + + /// + /// Initializes the attribute with the associated parameter name. + /// + /// + /// The associated parameter name. + /// The output will be non- if the argument to the + /// parameter specified is non-. + /// + public NotNullIfNotNullAttribute(string parameterName) => + ParameterName = parameterName; +} +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullWhenAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullWhenAttribute.cs new file mode 100644 index 000000000..be043ad96 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Nullable/NotNullWhenAttribute.cs @@ -0,0 +1,38 @@ +// +#pragma warning disable + +#if NETSTANDARD2_0 || NETFRAMEWORK || NETCOREAPP2X + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that when a method returns , +/// the parameter will not be even if the corresponding type allows it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +#if PolyPublic +public +#endif +sealed class NotNullWhenAttribute : + Attribute +{ + /// + /// Gets the return value condition. + /// If the method returns this value, the associated parameter will not be . + /// + public bool ReturnValue { get; } + + /// + /// Initializes the attribute with the specified return value condition. + /// + /// + /// The return value condition. + /// If the method returns this value, the associated parameter will not be . + /// + public NotNullWhenAttribute(bool returnValue) => + ReturnValue = returnValue; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/BytePolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/BytePolyfill.cs new file mode 100644 index 000000000..59231d53c --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/BytePolyfill.cs @@ -0,0 +1,98 @@ +// +#pragma warning disable + +#nullable enable + +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 +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse#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); +#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#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#system-byte-tryparse(system-readonlyspan((system-char))-system-byte@) + public static bool TryParse(ReadOnlySpan target, out byte result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + byte.TryParse(target.ToString(), out result); +#else + byte.TryParse(target, 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#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 UTF-8 characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryparse#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#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); +#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + byte.TryParse(target.ToString(), style, provider, out result); +#else + byte.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/DoublePolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/DoublePolyfill.cs new file mode 100644 index 000000000..2c594df31 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/DoublePolyfill.cs @@ -0,0 +1,97 @@ +// +#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 DoublePolyfill +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse#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); +#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#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 + + /// + /// 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#system-double-tryparse(system-readonlyspan((system-char))-system-double@) + public static bool TryParse(ReadOnlySpan target, out double result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + double.TryParse(target.ToString(), out result); +#else + double.TryParse(target, out result); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse#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#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#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); +#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + double.TryParse(target.ToString(), style, provider, out result); +#else + double.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/IntPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/IntPolyfill.cs new file mode 100644 index 000000000..60dd304e6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/IntPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-int32-tryparse(system-readonlyspan((system-char))-system-int32@) + public static bool TryParse(ReadOnlySpan target, out int result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + int.TryParse(target.ToString(), out result); +#else + int.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + int.TryParse(target.ToString(), style, provider, out result); +#else + int.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/LongPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/LongPolyfill.cs new file mode 100644 index 000000000..848c4baee --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/LongPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-int64-tryparse(system-readonlyspan((system-char))-system-int64@) + public static bool TryParse(ReadOnlySpan target, out long result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + long.TryParse(target.ToString(), out result); +#else + long.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + long.TryParse(target.ToString(), style, provider, out result); +#else + long.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/SBytePolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/SBytePolyfill.cs new file mode 100644 index 000000000..a1d0f334e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/SBytePolyfill.cs @@ -0,0 +1,97 @@ +// +#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 SBytePolyfill +{ + /// + /// Tries to parse a string into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse#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); +#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#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#system-sbyte-tryparse(system-readonlyspan((system-char))-system-sbyte@) + public static bool TryParse(ReadOnlySpan target, out sbyte result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + sbyte.TryParse(target.ToString(), out result); +#else + sbyte.TryParse(target, out result); +#endif + + /// + /// Tries to parse a span of characters into a value. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryparse#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#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#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); +#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + sbyte.TryParse(target.ToString(), style, provider, out result); +#else + sbyte.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ShortPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ShortPolyfill.cs new file mode 100644 index 000000000..c085479cf --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ShortPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-int16-tryparse(system-readonlyspan((system-char))-system-int16@) + public static bool TryParse(ReadOnlySpan target, out short result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + short.TryParse(target.ToString(), out result); +#else + short.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + short.TryParse(target.ToString(), style, provider, out result); +#else + short.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UIntPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UIntPolyfill.cs new file mode 100644 index 000000000..93e80a984 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UIntPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-uint32-tryparse(system-readonlyspan((system-char))-system-uint32@) + public static bool TryParse(ReadOnlySpan target, out uint result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + uint.TryParse(target.ToString(), out result); +#else + uint.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + uint.TryParse(target.ToString(), style, provider, out result); +#else + uint.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ULongPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ULongPolyfill.cs new file mode 100644 index 000000000..2b8ebe9d5 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/ULongPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-uint64-tryparse(system-readonlyspan((system-char))-system-uint64@) + public static bool TryParse(ReadOnlySpan target, out ulong result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + ulong.TryParse(target.ToString(), out result); +#else + ulong.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + ulong.TryParse(target.ToString(), style, provider, out result); +#else + ulong.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UShortPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UShortPolyfill.cs new file mode 100644 index 000000000..313f1758a --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Numbers/UShortPolyfill.cs @@ -0,0 +1,97 @@ +// +#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#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#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#system-uint16-tryparse(system-readonlyspan((system-char))-system-uint16@) + public static bool TryParse(ReadOnlySpan target, out ushort result) => +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + ushort.TryParse(target.ToString(), out result); +#else + ushort.TryParse(target, 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#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#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#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#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_0 || NETSTANDARD2_0 || NETFRAMEWORK + ushort.TryParse(target.ToString(), style, provider, out result); +#else + ushort.TryParse(target, style, provider, out result); +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/OverloadResolutionPriorityAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/OverloadResolutionPriorityAttribute.cs new file mode 100644 index 000000000..dbc2dfa4a --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/OverloadResolutionPriorityAttribute.cs @@ -0,0 +1,42 @@ +// +#pragma warning disable + +#if !NET9_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Specifies the priority of a member in overload resolution. When unspecified, the default priority is 0. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + AttributeTargets.Method | + AttributeTargets.Constructor | + AttributeTargets.Property, + Inherited = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.overloadresolutionpriorityattribute +#if PolyPublic +public +#endif +sealed class OverloadResolutionPriorityAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class. + /// + /// The priority of the attributed member. Higher numbers are prioritized, + /// lower numbers are deprioritized. 0 is the default if no attribute is present. + public OverloadResolutionPriorityAttribute(int priority) => + Priority = priority; + + /// + /// The priority of the member. + /// + public int Priority { get; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ParamCollectionAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ParamCollectionAttribute.cs new file mode 100644 index 000000000..e4563f446 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ParamCollectionAttribute.cs @@ -0,0 +1,23 @@ +// +#pragma warning disable + +#if !NET9_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// Indicates that a method allows a variable number of arguments in its invocation. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.paramcollectionattribute +#if PolyPublic +public +#endif +sealed class ParamCollectionAttribute : Attribute; + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs new file mode 100644 index 000000000..9c4017b28 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/OSPlatformAttribute.cs @@ -0,0 +1,25 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// Base type for all platform-specific API attributes. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +abstract class OSPlatformAttribute(string platformName) : + Attribute +{ + public string PlatformName { get; } = platformName; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs new file mode 100644 index 000000000..50d229ba7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/ObsoletedOSPlatformAttribute.cs @@ -0,0 +1,56 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +#nullable enable + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Marks APIs that were obsoleted in a given operating system version. +/// +/// +/// Primarily used by OS bindings to indicate APIs that should not be used anymore. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Assembly | + Targets.Class | + Targets.Constructor | + Targets.Enum | + Targets.Event | + Targets.Field | + Targets.Interface | + Targets.Method | + Targets.Module | + Targets.Property | + Targets.Struct, + AllowMultiple = true, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class ObsoletedOSPlatformAttribute : + OSPlatformAttribute +{ + public ObsoletedOSPlatformAttribute(string platformName) : + base(platformName) + { + } + + public ObsoletedOSPlatformAttribute(string platformName, string? message) : + base(platformName) => + Message = message; + + public string? Message { get; } + public string? Url { get; set; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs new file mode 100644 index 000000000..ae43f4971 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformAttribute.cs @@ -0,0 +1,47 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Records the operating system (and minimum version) that supports an API. Multiple attributes can be +/// applied to indicate support on multiple operating systems. +/// +/// +/// Callers can apply a +/// or use guards to prevent calls to APIs on unsupported operating systems. +/// +/// A given platform should only be specified once. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Assembly | + Targets.Class | + Targets.Constructor | + Targets.Enum | + Targets.Event | + Targets.Field | + Targets.Interface | + Targets.Method | + Targets.Module | + Targets.Property | + Targets.Struct, + AllowMultiple = true, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class SupportedOSPlatformAttribute(string platformName) : + OSPlatformAttribute(platformName) +{ +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs new file mode 100644 index 000000000..a0d55a7aa --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/SupportedOSPlatformGuardAttribute.cs @@ -0,0 +1,39 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Annotates a custom guard field, property or method with a supported platform name and optional version. +/// Multiple attributes can be applied to indicate guard for multiple supported platforms. +/// +/// +/// Callers can apply a to a field, property or method +/// and use that field, property or method in a conditional or assert statements in order to safely call platform specific APIs. +/// +/// The type of the field or property should be boolean, the method return type should be boolean in order to be used as platform guard. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Method | + Targets.Property, + AllowMultiple = true, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class SupportedOSPlatformGuardAttribute(string platformName) : + OSPlatformAttribute(platformName) +{ +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs new file mode 100644 index 000000000..e34820c89 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/TargetPlatformAttribute.cs @@ -0,0 +1,25 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +/// +/// Records the platform that the project targeted. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Assembly)] +#if PolyPublic +public +#endif +sealed class TargetPlatformAttribute(string platformName) : + OSPlatformAttribute(platformName) +{ +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs new file mode 100644 index 000000000..38e3febb3 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformAttribute.cs @@ -0,0 +1,56 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Marks APIs that were removed in a given operating system version. +/// +/// +/// Primarily used by OS bindings to indicate APIs that are only available in +/// earlier versions. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Assembly | + Targets.Class | + Targets.Constructor | + Targets.Enum | + Targets.Event | + Targets.Field | + Targets.Interface | + Targets.Method | + Targets.Module | + Targets.Property | + Targets.Struct, + AllowMultiple = true, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class UnsupportedOSPlatformAttribute : + OSPlatformAttribute +{ + public UnsupportedOSPlatformAttribute(string platformName) : + base(platformName) + { + } + + public UnsupportedOSPlatformAttribute(string platformName, string? message) : + base(platformName) => + Message = message; + + public string? Message { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs new file mode 100644 index 000000000..43f9071e6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/PlatformCompatibility/UnsupportedOSPlatformGuardAttribute.cs @@ -0,0 +1,41 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +#pragma warning disable + +namespace System.Runtime.Versioning; + +using Diagnostics; +using Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Annotates the custom guard field, property or method with an unsupported platform name and optional version. +/// Multiple attributes can be applied to indicate guard for multiple unsupported platforms. +/// +/// +/// Callers can apply a to a field, property or method +/// and use that field, property or method in a conditional or assert statements as a guard to safely call APIs unsupported on those platforms. +/// +/// The type of the field or property should be boolean, the method return type should be boolean in order to be used as platform guard. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Field | + Targets.Method | + Targets.Property, + AllowMultiple = true, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class UnsupportedOSPlatformGuardAttribute(string platformName) : + OSPlatformAttribute(platformName) +{ +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill.cs new file mode 100644 index 000000000..c790ed9b2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill.cs @@ -0,0 +1,16 @@ +// +#pragma warning disable +global using global::Polyfills; + +namespace Polyfills; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[EditorBrowsable(EditorBrowsableState.Never)] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static partial class Polyfill; \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationToken.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationToken.cs new file mode 100644 index 000000000..121aebce4 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationToken.cs @@ -0,0 +1,136 @@ +// +#pragma warning disable + +#nullable enable + +namespace Polyfills; + +using System; +using System.Threading; + +static partial class Polyfill +{ +#if !NETCOREAPP3_0_OR_GREATER + + /// + /// Registers a delegate that will be called when this + /// CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the delegate will be run immediately and synchronously. + /// Any exception the delegate generates will be propagated out of this method call. + /// + /// + /// ExecutionContext is not captured nor flowed + /// to the callback's invocation. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// The instance that can + /// be used to unregister the callback. + /// is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.unsaferegister#system-threading-cancellationtoken-unsaferegister(system-action((system-object))-system-object) + public static CancellationTokenRegistration UnsafeRegister(this CancellationToken target, Action callback, object? state) + { + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + // The main difference between UnsafeRegister and Register appears to be that UnsafeRegister callbacks don't capture and use the execution context. + // So to emulate that here, let's suppress the execution context if needed before calling Register. + // This idea was taken from UniTask and how they implemented their RegisterWithoutCaptureExecutionContext extension methods: + // https://github.com/Cysharp/UniTask/blob/master/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs + + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + return target.Register(callback, state, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + +#endif + +#if !NET6_0_OR_GREATER + + /// Registers a delegate that will be called when this CancellationToken is canceled. + /// + /// If this token is already in the canceled state, the delegate will be run immediately and synchronously. Any exception the delegate + /// generates will be propagated out of this method call. The current ExecutionContext, if one exists, + /// will be captured along with the delegate and will be used when executing it. The current is not captured. + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// The instance that can be used to unregister the callback. + /// is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.register#system-threading-cancellationtoken-register(system-action((system-object-system-threading-cancellationtoken))-system-object) + public static CancellationTokenRegistration Register(this CancellationToken target, Action callback, object? state) + { + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + return target.Register(data => callback(data, target), state, useSynchronizationContext: false); + } + + /// Registers a delegate that will be called when this CancellationToken is canceled. + /// + /// If this token is already in the canceled state, the delegate will be run immediately and synchronously. Any exception the delegate + /// generates will be propagated out of this method call. is not captured nor flowed to the callback's invocation. + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// The instance that can be used to unregister the callback. + /// is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.unsaferegister#system-threading-cancellationtoken-unsaferegister(system-action((system-object-system-threading-cancellationtoken))-system-object) + public static CancellationTokenRegistration UnsafeRegister(this CancellationToken target, Action callback, object? state) + { + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + // The main difference between UnsafeRegister and Register appears to be that UnsafeRegister callbacks don't capture and use the execution context. + // So to emulate that here, let's suppress the execution context if needed before calling Register. + // This idea was taken from UniTask and how they implemented their RegisterWithoutCaptureExecutionContext extension methods: + // https://github.com/Cysharp/UniTask/blob/master/src/UniTask/Assets/Plugins/UniTask/Runtime/CancellationTokenExtensions.cs + + var restoreFlow = false; + if (!ExecutionContext.IsFlowSuppressed()) + { + ExecutionContext.SuppressFlow(); + restoreFlow = true; + } + + try + { + Action internalCallback = data => callback(data, target); + return target.Register(internalCallback, state, false); + } + finally + { + if (restoreFlow) + { + ExecutionContext.RestoreFlow(); + } + } + } + +#endif +} diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationTokenSource.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationTokenSource.cs new file mode 100644 index 000000000..9c001a135 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_CancellationTokenSource.cs @@ -0,0 +1,59 @@ +// +#pragma warning disable + +#if !NET8_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + + /// Communicates a request for cancellation asynchronously. + /// + /// + /// The associated will be notified of the cancellation + /// and will synchronously transition to a state where returns true. + /// Any callbacks or cancelable operations registered with the will be executed asynchronously, + /// with the returned representing their eventual completion. + /// + /// + /// Callbacks registered with the token should not throw exceptions. + /// However, any such exceptions that are thrown will be aggregated into an , + /// such that one callback throwing an exception will not prevent other registered callbacks from being executed. + /// + /// + /// The that was captured when each callback was registered + /// will be reestablished when the callback is invoked. + /// + /// + /// This has been disposed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtokensource.cancelasync + public static Task CancelAsync(this CancellationTokenSource target) + { + if (target.IsCancellationRequested) + { + // If cancellation has already been requested then we can just return immediately + return Task.CompletedTask; + } + else + { + // Run sync Cancel call in Task to avoid possible deadlock. + // As an example, the CancellationTokenSource_CancelAsync_CallbacksInvokedAsynchronously test + // will hit a deadlock if we try to just call Cancel directly without it being run in a task + Task task = Task.Run(() => target.Cancel()); + + while (!target.IsCancellationRequested) + { + // Don't return until we know that the cancellation request has started, to match the + // state that the real implemenation for CancelAsync would be in after being called + } + + return task; + } + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentBag.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentBag.cs new file mode 100644 index 000000000..72ee8bbf6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentBag.cs @@ -0,0 +1,25 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System; +using System.Collections.Concurrent; + +static partial class Polyfill +{ + /// + /// Removes all values from the . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentbag-1.clear + public static void Clear(this ConcurrentBag target) + { + while (!target.IsEmpty) + { + target.TryTake(out _); + } + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentDictionary.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentDictionary.cs new file mode 100644 index 000000000..1c7b6473a --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentDictionary.cs @@ -0,0 +1,69 @@ +// +#pragma warning disable + +#if NET46X || NETSTANDARD2_0 || NET47 || NET471 + +namespace Polyfills; + +using System; +using System.Collections.Concurrent; + +static partial class Polyfill +{ + + /// + /// Adds a key/value pair to the + /// if the key does not already exist. + /// + /// The key of the element to add. + /// The function used to generate a value for the key + /// An argument value to pass into . + /// is a null reference + /// (Nothing in Visual Basic). + /// is a null reference + /// (Nothing in Visual Basic). + /// The dictionary contains too many + /// elements. + /// The value for the key. This will be either the existing value for the key if the + /// key is already in the dictionary, or the new value for the key as returned by valueFactory + /// if the key was not in the dictionary. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.getoradd#system-collections-concurrent-concurrentdictionary-2-getoradd-1(-0-system-func((-0-0-1))-0) + public static TValue GetOrAdd(this ConcurrentDictionary target, TKey key, Func valueFactory, TArg factoryArgument) + where TKey : notnull + { + // Implementation based on https://github.com/dotnet/runtime/issues/13978#issuecomment-69494764. + // Because this API is intended to be used in high performance scenarios where avoiding allocations + // is important, we can't delegate to the existing `GetOrAdd`2`, as that would allocate a closure + // over `factoryArgument`. + + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + + if (key is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (valueFactory is null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } + + while (true) + { + TValue value; + if (target.TryGetValue(key, out value)) + { + return value; + } + + value = valueFactory(key, factoryArgument); + if (target.TryAdd(key, value)) + { + return value; + } + } + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentQueue.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentQueue.cs new file mode 100644 index 000000000..cea93664f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_ConcurrentQueue.cs @@ -0,0 +1,22 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System; +using System.Collections.Concurrent; + +static partial class Polyfill +{ + /// + /// Removes all values from the . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1.clear + public static void Clear(this ConcurrentQueue target) + { + while (target.TryDequeue(out _)); + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Delegate.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Delegate.cs new file mode 100644 index 000000000..048c2a062 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Delegate.cs @@ -0,0 +1,26 @@ +// + +using System.Runtime.CompilerServices; + +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Concurrent; + +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 + public static bool HasSingleTarget(this Delegate target) + { +#if NET9_0_OR_GREATER + return target.HasSingleTarget; +#else + return target.GetInvocationList().Length == 1; +#endif + } +} diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Dictionary.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Dictionary.cs new file mode 100644 index 000000000..6b28ed44b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Dictionary.cs @@ -0,0 +1,82 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; + +static partial class Polyfill +{ +#if !NET7_0_OR_GREATER + /// + /// Returns a read-only wrapper for the current dictionary. + /// + /// The type of keys in the dictionary. + /// The type of values in the dictionary. + /// The dictionary to wrap. + /// An object that acts as a read-only wrapper around the current . + /// is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.asreadonly#system-collections-generic-collectionextensions-asreadonly-2(system-collections-generic-idictionary((-0-1))) + public static ReadOnlyDictionary AsReadOnly(this IDictionary target) + where TKey : notnull => + new(target); +#endif + +#if NETFRAMEWORK || NETSTANDARD2_0 + + /// + /// Attempts to add the specified key and value to the dictionary. + /// + /// The key of the element to add. + /// The value of the element to add. It can be . + /// true if the key/value pair was added to the dictionary successfully; otherwise, false. + /// is . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd + public static bool TryAdd(this Dictionary target, TKey key, TValue value) + where TKey : notnull + { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + if (!target.ContainsKey(key)) + { + target.Add(key, value); + return true; + } + + return false; + } + +#endif + +#if NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2X + + /// + /// Removes the value with the specified key from the , and copies the element + /// to the value parameter. + /// + /// A dictionary with keys of type TKey and values of type TValue. + /// The key of the element to remove. + /// The removed element. + /// The type of the keys in the dictionary. + /// The type of the values in the dictionary. + /// true if the element is successfully found and removed; otherwise, false. + /// is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove + public static bool Remove( + this Dictionary target, + TKey key, + [MaybeNullWhen(false)] out TValue value) + where TKey : notnull + { + target.TryGetValue(key, out value); + return target.Remove(key); + } + +#endif +} diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Encoding.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Encoding.cs new file mode 100644 index 000000000..a44f78ed0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Encoding.cs @@ -0,0 +1,81 @@ +// + +using System.Runtime.InteropServices; +using System.Text; + +#pragma warning disable + +#if FeatureMemory + +namespace Polyfills; + +using System; + +static partial class Polyfill +{ +#if NETCOREAPP2_0 || NETFRAMEWORK || NETSTANDARD2_0 + /// + /// When overridden in a derived class, calculates the number of bytes produced by encoding the characters in the specified character span. + /// + /// + /// The span of characters to encode. + /// The number of bytes produced by encoding the specified character span. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getbytecount#system-text-encoding-getbytecount(system-readonlyspan((system-char))) + public static int GetByteCount(this Encoding target, ReadOnlySpan chars) => + target.GetByteCount(chars.ToArray()); +#endif + +#if AllowUnsafeBlocks && !NETCOREAPP2_1_OR_GREATER + /// When overridden in a derived class, encodes into a span of bytes a set of characters from the specified read-only span. + /// The span containing the set of characters to encode. + /// The byte span to hold the encoded bytes. + /// The number of encoded bytes. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getbytes#system-text-encoding-getbytes(system-readonlyspan((system-char))-system-span((system-byte))) + public static unsafe int GetBytes(this Encoding target, ReadOnlySpan chars, Span bytes) + { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + + fixed (char* charsPtr = chars) + fixed (byte* bytesPtr = bytes) + { + return target.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); + } + } + +#endif +#if !NETCOREAPP2_1_OR_GREATER + /// When overridden in a derived class, decodes all the bytes in the specified byte span into a string. + /// A read-only byte span to decode to a Unicode string. + /// A string that contains the decoded bytes from the provided read-only span. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getstring#system-text-encoding-getstring(system-readonlyspan((system-byte))) +#if AllowUnsafeBlocks + public static unsafe string GetString(this Encoding target, ReadOnlySpan bytes) + { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + + fixed (byte* bytesPtr = bytes) + { + return target.GetString(bytesPtr, bytes.Length); + } + } +#else + public static string GetString(this Encoding target, ReadOnlySpan bytes) + { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + + return target.GetString(bytes.ToArray()); + } +#endif +#endif +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HashSet.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HashSet.cs new file mode 100644 index 000000000..a7b13090b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HashSet.cs @@ -0,0 +1,41 @@ +// +#pragma warning disable + +#if NET46X || NET47 || NET471 || NETSTANDARD2_0 + +namespace Polyfills; + +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +static partial class Polyfill +{ + /// + /// Searches the set for a given value and returns the equal value it finds, if any. + /// + /// The value to search for. + /// The value from the set that the search found, or the default value of T when the search yielded no match. + /// A value indicating whether the search was successful. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.trygetvalue + public static bool TryGetValue( + this HashSet target, + T equalValue, + [MaybeNullWhen(false)] out T actualValue) + { + var comparer = target.Comparer; + var hashCode = comparer.GetHashCode(equalValue); + foreach (var item in target) + { + if (comparer.GetHashCode(item) == hashCode && + comparer.Equals(item, equalValue)) + { + actualValue = item; + return true; + } + } + + actualValue = default; + return false; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpClient.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpClient.cs new file mode 100644 index 000000000..607ddb4ad --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpClient.cs @@ -0,0 +1,183 @@ +// +#pragma warning disable + +#if ((NETFRAMEWORK && FeatureHttp) || NETSTANDARD || NETCOREAPP2X || NETCOREAPP3X) + +namespace Polyfills; + +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + /// + /// Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. + /// + /// + /// This operation will not block. The returned object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getstreamasync#system-net-http-httpclient-getstreamasync(system-string-system-threading-cancellationtoken) + public static async Task GetStreamAsync( + this HttpClient target, + string requestUri, + CancellationToken cancellationToken = default) + { + try + { + // Must not be disposed for the stream to be usable + var response = await target.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken + ).ConfigureAwait(false); + + response.EnsureSuccessStatusCode(); + + return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + } + // Older versions of HttpClient methods don't propagate the cancellation token inside the exception + catch (OperationCanceledException ex) when ( + ex.CancellationToken != cancellationToken && + cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(ex.Message, ex.InnerException, cancellationToken); + } + } + + /// + /// Send a GET request to the specified Uri and return the response body as a stream in an asynchronous operation. + /// + /// + /// This operation will not block. The returned object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getstreamasync#system-net-http-httpclient-getstreamasync(system-uri-system-threading-cancellationtoken) + public static Task GetStreamAsync( + this HttpClient target, + Uri requestUri, + CancellationToken cancellationToken = default) => + target.GetStreamAsync(requestUri.ToString(), cancellationToken); + + /// + /// Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. + /// + /// + /// This operation will not block. The returned Task{Byte[]} object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getbytearrayasync#system-net-http-httpclient-getbytearrayasync(system-string-system-threading-cancellationtoken) + public static async Task GetByteArrayAsync( + this HttpClient target, + string requestUri, + CancellationToken cancellationToken = default) + { + try + { + using var response = await target.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken) + .ConfigureAwait(false); + + response.EnsureSuccessStatusCode(); + + return await response.Content + .ReadAsByteArrayAsync(cancellationToken) + .ConfigureAwait(false); + } + // Older versions of HttpClient methods don't propagate the cancellation token inside the exception + catch (OperationCanceledException exception) when ( + exception.CancellationToken != cancellationToken && + cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(exception.Message, exception.InnerException, cancellationToken); + } + } + + /// + /// Send a GET request to the specified Uri and return the response body as a byte array in an asynchronous operation. + /// + /// + /// This operation will not block. The returned Task{byte[]} object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getbytearrayasync#system-net-http-httpclient-getbytearrayasync(system-uri-system-threading-cancellationtoken) + public static Task GetByteArrayAsync( + this HttpClient target, + Uri requestUri, + CancellationToken cancellationToken = default) => + target.GetByteArrayAsync(requestUri.ToString(), cancellationToken); + + /// + /// Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. + /// + /// + /// This operation will not block. The returned object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getstringasync#system-net-http-httpclient-getstringasync(system-string-system-threading-cancellationtoken) + public static async Task GetStringAsync( + this HttpClient target, + string requestUri, + CancellationToken cancellationToken = default) + { + try + { + using var response = await target.GetAsync( + requestUri, + HttpCompletionOption.ResponseHeadersRead, + cancellationToken) + .ConfigureAwait(false); + + response.EnsureSuccessStatusCode(); + + return await response.Content + .ReadAsStringAsync(cancellationToken) + .ConfigureAwait(false); + } + // Older versions of HttpClient methods don't propagate the cancellation token inside the exception + catch (OperationCanceledException exception) when ( + exception.CancellationToken != cancellationToken && + cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(exception.Message, exception.InnerException, cancellationToken); + } + } + + /// + /// Send a GET request to the specified Uri and return the response body as a string in an asynchronous operation. + /// + /// + /// This operation will not block. The returned object will complete after the response headers are read. + /// This method does not read nor buffer the response body. + /// + /// The Uri the request is sent to. + /// The cancellation token to cancel the operation. + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getstringasync#system-net-http-httpclient-getstringasync(system-uri-system-threading-cancellationtoken) + public static Task GetStringAsync( + this HttpClient target, + Uri requestUri, + CancellationToken cancellationToken = default) => + target.GetStringAsync(requestUri.ToString(), cancellationToken); +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpContent.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpContent.cs new file mode 100644 index 000000000..188eb255d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_HttpContent.cs @@ -0,0 +1,78 @@ +// +#pragma warning disable + +#if ((NETFRAMEWORK && FeatureHttp) || NETSTANDARD || NETCOREAPP2X || NETCOREAPP3X) + +namespace Polyfills; + +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + /// + /// Serializes the HTTP content and returns a stream that represents the content. + /// + /// + /// Note that this method will internally buffer the content unless CreateContentReadStreamAsync() has been + /// implemented to do otherwise. + /// + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.readasstreamasync#system-net-http-httpcontent-readasstreamasync(system-threading-cancellationtoken) + public static Task ReadAsStreamAsync( + this HttpContent target, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return target.ReadAsStreamAsync() + .WaitAsync(cancellationToken); + } + + /// + /// Serializes the HTTP content to a byte array as an asynchronous operation. + /// + /// + /// Note that this method will internally buffer the content unless CreateContentReadStreamAsync() has been + /// implemented to do otherwise. + /// + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.readasbytearrayasync#system-net-http-httpcontent-readasbytearrayasync(system-threading-cancellationtoken) + public static Task ReadAsByteArrayAsync( + this HttpContent target, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return target.ReadAsByteArrayAsync() + .WaitAsync(cancellationToken); + } + + /// + /// Serializes the HTTP content to a string as an asynchronous operation. + /// + /// + /// Note that this method will internally buffer the content unless CreateContentReadStreamAsync() has been + /// implemented to do otherwise. + /// + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// The task object representing the asynchronous operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.readasstringasync#system-net-http-httpcontent-readasstringasync(system-threading-cancellationtoken) + public static Task ReadAsStringAsync( + this HttpContent target, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return target.ReadAsStringAsync() + .WaitAsync(cancellationToken); + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_AggregateBy.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_AggregateBy.cs new file mode 100644 index 000000000..bec99de29 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_AggregateBy.cs @@ -0,0 +1,126 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET9_0_OR_GREATER + + /// + /// https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/overview#linq + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregateby#system-linq-enumerable-aggregateby-3(system-collections-generic-ienumerable((-0))-system-func((-0-1))-system-func((-1-2))-system-func((-2-0-2))-system-collections-generic-iequalitycomparer((-1))) + public static IEnumerable> AggregateBy( + this IEnumerable source, + Func keySelector, + TAccumulate seed, + Func func, + IEqualityComparer? keyComparer = null) + where TKey : notnull + { + if (source is TSource[] {Length: 0}) + { + return []; + } + + return AggregateByIterator(source, keySelector, seed, func, keyComparer); + } + + /// + /// https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/overview#linq + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregateby#system-linq-enumerable-aggregateby-3(system-collections-generic-ienumerable((-0))-system-func((-0-1))-2-system-func((-2-0-2))-system-collections-generic-iequalitycomparer((-1))) + public static IEnumerable> AggregateBy( + this IEnumerable source, + Func keySelector, + Func seedSelector, + Func func, + IEqualityComparer? keyComparer = null) + where TKey : notnull + { + if (source is TSource[] {Length: 0}) + { + return []; + } + + return AggregateByIterator(source, keySelector, seedSelector, func, keyComparer); + } + + static IEnumerable> AggregateByIterator(IEnumerable source, Func keySelector, TAccumulate seed, Func func, IEqualityComparer? keyComparer) + where TKey : notnull + { + using var enumerator = source.GetEnumerator(); + + if (!enumerator.MoveNext()) + { + yield break; + } + + foreach (var item in PopulateDictionary(enumerator, keySelector, seed, func, keyComparer)) + { + yield return item; + } + + static Dictionary PopulateDictionary(IEnumerator enumerator, Func keySelector, TAccumulate seed, Func func, IEqualityComparer? keyComparer) + { + Dictionary dict = new(keyComparer); + + do + { + var value = enumerator.Current; + var key = keySelector(value); + + if (!dict.TryGetValue(key, out var accumulate)) + { + accumulate = seed; + } + + dict[key] = func(accumulate, value); + } while (enumerator.MoveNext()); + + return dict; + } + } + + static IEnumerable> AggregateByIterator(IEnumerable source, Func keySelector, Func seedSelector, Func func, IEqualityComparer? keyComparer) + where TKey : notnull + { + using var enumerator = source.GetEnumerator(); + + if (!enumerator.MoveNext()) + { + yield break; + } + + foreach (var item in PopulateDictionary(enumerator, keySelector, seedSelector, func, keyComparer)) + { + yield return item; + } + + static Dictionary PopulateDictionary(IEnumerator enumerator, Func keySelector, Func seedSelector, Func func, IEqualityComparer? keyComparer) + { + var dict = new Dictionary(keyComparer); + + do + { + var value = enumerator.Current; + var key = keySelector(value); + + if (!dict.TryGetValue(key, out var accumulate)) + { + accumulate = seedSelector(key); + } + + dict[key] = func(accumulate, value); + } while (enumerator.MoveNext()); + + return dict; + } + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Append.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Append.cs new file mode 100644 index 000000000..e493838f2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Append.cs @@ -0,0 +1,34 @@ +// +#pragma warning disable + +#if NET46X || NET47 + +namespace Polyfills; + +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + /// + /// Appends a value to the end of the sequence. + /// + /// A sequence of values. + /// The value to append to . + /// The type of the elements of source. + /// A new sequence that ends with element. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append + public static IEnumerable Append( + this IEnumerable target, + TSource element) + { + foreach (var item in target) + { + yield return item; + } + + yield return element; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Chunk.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Chunk.cs new file mode 100644 index 000000000..5172fb915 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Chunk.cs @@ -0,0 +1,101 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// + /// Split the elements of a sequence into chunks of size at most . + /// + /// + /// Every chunk except the last will be of size . + /// The last chunk will contain the remaining elements and may be of a smaller size. + /// + /// An whose elements to chunk. + /// Maximum size of each chunk. + /// The type of the elements of source. + /// + /// An that contains the elements the input sequence split into chunks of size . + /// + /// is null. + /// is below 1. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.chunk + public static IEnumerable Chunk(this IEnumerable source, int size) + { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (size < 1) + { + throw new ArgumentOutOfRangeException(nameof(size), size, "Size must be greater than 0."); + } + + return ChunkIterator(source, size); + + static IEnumerable ChunkIterator(IEnumerable source, int size) + { + using var enumerator = source.GetEnumerator(); + + // Before allocating anything, make sure there's at least one element. + if (enumerator.MoveNext()) + { + // Now that we know we have at least one item, allocate an initial storage array. This is not + // the array we'll yield. It starts out small in order to avoid significantly overallocating + // when the source has many fewer elements than the chunk size. + var arraySize = Math.Min(size, 4); + int i; + do + { + var array = new TSource[arraySize]; + + // Store the first item. + array[0] = enumerator.Current; + i = 1; + + if (size != array.Length) + { + // This is the first chunk. As we fill the array, grow it as needed. + for (; i < size && enumerator.MoveNext(); i++) + { + if (i >= array.Length) + { + arraySize = (int) Math.Min((uint) size, 2 * (uint) array.Length); + Array.Resize(ref array, arraySize); + } + + array[i] = enumerator.Current; + } + } + else + { + // For all but the first chunk, the array will already be correctly sized. + // We can just store into it until either it's full or MoveNext returns false. + // avoid bounds checks by using cached local (`array` is lifted to iterator object as a field) + var local = array; + for (; (uint) i < (uint) local.Length && enumerator.MoveNext(); i++) + { + local[i] = enumerator.Current; + } + } + + if (i != array.Length) + { + Array.Resize(ref array, i); + } + + yield return array; + } while (i >= size && enumerator.MoveNext()); + } + } + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_CountBy.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_CountBy.cs new file mode 100644 index 000000000..e996a0519 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_CountBy.cs @@ -0,0 +1,68 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET9_0_OR_GREATER + + /// + /// https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/overview#linq + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.countby + public static IEnumerable> CountBy(this IEnumerable source, Func keySelector, IEqualityComparer? keyComparer = null) + where TKey : notnull + { + if (source is TSource[] { Length: 0 }) + { + return []; + } + + return CountByIterator(source, keySelector, keyComparer); + } + + static IEnumerable> CountByIterator(IEnumerable source, Func selector, IEqualityComparer? comparer) + where TKey : notnull + { + using var enumerator = source.GetEnumerator(); + + if (!enumerator.MoveNext()) + { + yield break; + } + + foreach (var item in BuildCountDictionary(enumerator, selector, comparer)) + { + yield return item; + } + } + + static Dictionary BuildCountDictionary(IEnumerator enumerator, Func selector, IEqualityComparer? comparer) + where TKey : notnull + { + Dictionary countsBy = new(comparer); + + do + { + var value = enumerator.Current; + var key = selector(value); + + if (!countsBy.TryGetValue(key, out var count)) + { + count = 0; + } + + count++; + countsBy[key] = count; + } + while (enumerator.MoveNext()); + + return countsBy; + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_DistinctBy.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_DistinctBy.cs new file mode 100644 index 000000000..7b643ccd9 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_DistinctBy.cs @@ -0,0 +1,62 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ + +#if !NET6_0_OR_GREATER + + /// Returns distinct elements from a sequence according to a specified key selector function. + /// The type of the elements of . + /// The type of key to distinguish elements by. + /// The sequence to remove duplicate elements from. + /// A function to extract the key for each element. + /// An that contains distinct elements from the source sequence. + /// is . + /// + /// This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic. + /// The method returns an unordered sequence that contains no duplicate values. The default equality comparer, , is used to compare values. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinctby#system-linq-enumerable-distinctby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))) + public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector) => + DistinctBy(source, keySelector, null); + + /// Returns distinct elements from a sequence according to a specified key selector function. + /// The type of the elements of . + /// The type of key to distinguish elements by. + /// The sequence to remove duplicate elements from. + /// A function to extract the key for each element. + /// An to compare keys. + /// An that contains distinct elements from the source sequence. + /// is . + /// + /// This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic. + /// The method returns an unordered sequence that contains no duplicate values. If is , the default equality comparer, , is used to compare values. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinctby#system-linq-enumerable-distinctby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))-system-collections-generic-iequalitycomparer((-1))) + public static IEnumerable DistinctBy(this IEnumerable source, Func keySelector, IEqualityComparer comparer) + { + using IEnumerator enumerator = source.GetEnumerator(); + + if (enumerator.MoveNext()) + { + var set = new HashSet(comparer); + do + { + TSource element = enumerator.Current; + if (set.Add(keySelector(element))) + { + yield return element; + } + } + while (enumerator.MoveNext()); + } + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ElementAt.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ElementAt.cs new file mode 100644 index 000000000..d276dfce5 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ElementAt.cs @@ -0,0 +1,105 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER && (NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1) + + /// Returns the element at a specified index in a sequence. + /// The type of the elements of . + /// An to return an element from. + /// The index of the element to retrieve, which is either from the start or the end. + /// is . + /// is outside the bounds of the sequence. + /// The element at the specified position in the sequence. + /// + /// If the type of implements , that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element. + /// This method throws an exception if is out of range. To instead return a default value when the specified index is out of range, use the method. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.elementat#system-linq-enumerable-elementat-1(system-collections-generic-ienumerable((-0))-system-index) + public static TSource ElementAt(this IEnumerable source, Index index) + { + if (!index.IsFromEnd) + { + return Enumerable.ElementAt(source, index.Value); + } + + if (source.TryGetNonEnumeratedCount(out int count)) + { + return Enumerable.ElementAt(source, count - index.Value); + } + + if (!TryGetElementFromEnd(source, index.Value, out TSource? element)) + { + throw new ArgumentOutOfRangeException("index"); + } + + return element; + } + + static bool TryGetElementFromEnd(IEnumerable source, int indexFromEnd, [MaybeNullWhen(false)] out TSource element) + { + if (indexFromEnd > 0) + { + using IEnumerator e = source.GetEnumerator(); + if (e.MoveNext()) + { + Queue queue = new(); + queue.Enqueue(e.Current); + while (e.MoveNext()) + { + if (queue.Count == indexFromEnd) + { + queue.Dequeue(); + } + + queue.Enqueue(e.Current); + } + + if (queue.Count == indexFromEnd) + { + element = queue.Dequeue(); + return true; + } + } + } + + element = default; + return false; + } + + /// Returns the element at a specified index in a sequence or a default value if the index is out of range. + /// The type of the elements of . + /// An to return an element from. + /// The index of the element to retrieve, which is either from the start or the end. + /// is . + /// if is outside the bounds of the sequence; otherwise, the element at the specified position in the sequence. + /// + /// If the type of implements , that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element. + /// The default value for reference and nullable types is . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.elementatordefault#system-linq-enumerable-elementatordefault-1(system-collections-generic-ienumerable((-0))-system-index) + public static TSource? ElementAtOrDefault(this IEnumerable source, Index index) + { + if (!index.IsFromEnd) + { + return Enumerable.ElementAtOrDefault(source, index.Value); + } + + if (source.TryGetNonEnumeratedCount(out int count)) + { + return Enumerable.ElementAtOrDefault(source, count - index.Value); + } + + TryGetElementFromEnd(source, index.Value, out TSource? element); + return element; + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Except.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Except.cs new file mode 100644 index 000000000..e6d8f5446 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Except.cs @@ -0,0 +1,121 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + /// + /// Produces a set items excluding by using the default equality comparer to compare values. + /// + /// An whose elements that are not equal to will be returned. + /// An that is elements equal it will cause those elements to be removed from the returned sequence. + /// The type of the elements of . + /// A sequence that contains the items of but excluding . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))) + public static IEnumerable Except( + this IEnumerable target, + TSource item) => + Except(target, item, null); + + //TODO: removed due to R# and Rider issue https://youtrack.jetbrains.com/issue/RSRP-496127/Intelisense-incorrectly-ignores-strong-name-mismatch + // /// + // /// Produces the set difference of two sequences by using the default equality comparer to compare values. + // /// + // /// An whose elements that are not equal to will be returned. + // /// An that is elements equal it will cause those elements to be removed from the returned sequence. + // /// The type of the elements of . + // /// A sequence that contains the items of but excluding . + // //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))) + // public static IEnumerable Except( + // this IEnumerable target, + // params TSource[] items) => + // target.Except((IEnumerable)items); + + /// + /// Produces a set items excluding by using to compare values. + /// + /// An whose elements that are not equal to will be returned. + /// An that is elements equal it will cause those elements to be removed from the returned sequence. + /// An to compare values. + /// The type of the elements of . + /// A sequence that contains the items of but excluding . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0))) + public static IEnumerable Except( + this IEnumerable target, + TSource item, + IEqualityComparer? comparer) + { + var set = new HashSet(comparer); + set.Add(item); + foreach (TSource element in target) + { + if (set.Add(element)) + { + yield return element; + } + } + } + + /// + /// Produces the set difference of two sequences by to compare values. + /// + /// An whose elements that are not equal to will be returned. + /// An that is elements equal it will cause those elements to be removed from the returned sequence. + /// The type of the elements of . + /// A sequence that contains the items of but excluding . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0))) + public static IEnumerable Except( + this IEnumerable target, + IEqualityComparer comparer, + params TSource[] items) => + target.Except((IEnumerable)items, comparer); + +#if !NET6_0_OR_GREATER + + /// + /// Produces the set difference of two sequences according to a specified key selector function. + /// + /// The type of the elements of the input sequence. + /// The type of key to identify elements by. + /// An whose keys that are not also in will be returned. + /// An whose keys that also occur in the first sequence will cause those elements to be removed from the returned sequence. + /// A function to extract the key for each element. + /// A sequence that contains the set difference of the elements of two sequences. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.exceptby#system-linq-enumerable-exceptby-2(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-1))-system-func((-0-1))) + public static IEnumerable ExceptBy(this IEnumerable first, IEnumerable second, Func keySelector) => + ExceptBy(first, second, keySelector, null); + + /// + /// Produces the set difference of two sequences according to a specified key selector function. + /// + /// The type of the elements of the input sequence. + /// The type of key to identify elements by. + /// An whose keys that are not also in will be returned. + /// An whose keys that also occur in the first sequence will cause those elements to be removed from the returned sequence. + /// A function to extract the key for each element. + /// The to compare values. + /// A sequence that contains the set difference of the elements of two sequences. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.exceptby#system-linq-enumerable-exceptby-2(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-1))-system-func((-0-1))-system-collections-generic-iequalitycomparer((-1))) + public static IEnumerable ExceptBy(this IEnumerable first, IEnumerable second, Func keySelector, IEqualityComparer? comparer) => + ExceptByIterator(first, second, keySelector, comparer); + + static IEnumerable ExceptByIterator(IEnumerable first, IEnumerable second, Func keySelector, IEqualityComparer? comparer) + { + var set = new HashSet(second, comparer); + + foreach (var element in first) + { + if (set.Add(keySelector(element))) + { + yield return element; + } + } + } +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_FirstOrDefault.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_FirstOrDefault.cs new file mode 100644 index 000000000..f6c2913fd --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_FirstOrDefault.cs @@ -0,0 +1,84 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found. + /// The type of the elements of . + /// An to return an element from. + /// A function to test each element for a condition. + /// The default value to return if the sequence is empty. + /// if is empty or if no element passes the test specified by ; otherwise, the first element in that passes the test specified by . + /// or is . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault#system-linq-enumerable-firstordefault-1(system-collections-generic-ienumerable((-0))-system-func((-0-system-boolean))-0) + public static TSource FirstOrDefault(this IEnumerable source, Func predicate, TSource defaultValue) + { + TSource? first = source.TryGetFirst(predicate, out bool found); + return found ? first! : defaultValue; + } + + /// Returns the first element of a sequence, or a default value if the sequence contains no elements. + /// The type of the elements of . + /// The to return the first element of. + /// The default value to return if the sequence is empty. + /// if is empty; otherwise, the first element in . + /// is . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault#system-linq-enumerable-firstordefault-1(system-collections-generic-ienumerable((-0))-0) + public static TSource FirstOrDefault(this IEnumerable source, TSource defaultValue) + { + TSource? first = source.TryGetFirst(out bool found); + return found ? first! : defaultValue; + } + + static TSource? TryGetFirst(this IEnumerable source, out bool found) => + TryGetFirstNonIterator(source, out found); + + static TSource? TryGetFirstNonIterator(IEnumerable source, out bool found) + { + if (source is IList list) + { + if (list.Count > 0) + { + found = true; + return list[0]; + } + } + else + { + using (IEnumerator e = source.GetEnumerator()) + { + if (e.MoveNext()) + { + found = true; + return e.Current; + } + } + } + + found = false; + return default; + } + + static TSource? TryGetFirst(this IEnumerable source, Func predicate, out bool found) + { + foreach (TSource element in source) + { + if (predicate(element)) + { + found = true; + return element; + } + } + + found = false; + return default; + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Index.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Index.cs new file mode 100644 index 000000000..62e6f9cf3 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Index.cs @@ -0,0 +1,28 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Collections; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET9_0_OR_GREATER && FeatureValueTuple + + /// + /// https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/overview#linq + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.index#system-linq-enumerable-index-1(system-collections-generic-ienumerable((-0))) + public static IEnumerable<(int Index, TSource Item)> Index(this IEnumerable source) + { + int index = 0; + foreach (var item in source) + { + yield return (index, item); + index++; + } + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_LastOrDefault.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_LastOrDefault.cs new file mode 100644 index 000000000..fc2adfdf2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_LastOrDefault.cs @@ -0,0 +1,120 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// Returns the last element of a sequence, or a default value if the sequence contains no elements. + /// The type of the elements of . + /// An to return the last element of. + /// The default value to return if the sequence is empty. + /// if the source sequence is empty; otherwise, the last element in the . + /// is . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.lastordefault#system-linq-enumerable-lastordefault-1(system-collections-generic-ienumerable((-0))-0) + public static TSource LastOrDefault(this IEnumerable source, TSource defaultValue) + { + TSource? last = source.TryGetLast(out bool found); + return found ? last! : defaultValue; + } + + /// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found. + /// The type of the elements of . + /// An to return an element from. + /// A function to test each element for a condition. + /// The default value to return if the sequence is empty. + /// if the sequence is empty or if no elements pass the test in the predicate function; otherwise, the last element that passes the test in the predicate function. + /// or is . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.lastordefault#system-linq-enumerable-lastordefault-1(system-collections-generic-ienumerable((-0))-system-func((-0-system-boolean))-0) + public static TSource LastOrDefault(this IEnumerable source, Func predicate, TSource defaultValue) + { + TSource? last = source.TryGetLast(predicate, out bool found); + return found ? last! : defaultValue; + } + + static TSource? TryGetLast(this IEnumerable source, out bool found) => + TryGetLastNonIterator(source, out found); + + static TSource? TryGetLastNonIterator(IEnumerable source, out bool found) + { + if (source is IList list) + { + int count = list.Count; + if (count > 0) + { + found = true; + return list[count - 1]; + } + } + else + { + using (IEnumerator e = source.GetEnumerator()) + { + if (e.MoveNext()) + { + TSource result; + do + { + result = e.Current; + } + while (e.MoveNext()); + + found = true; + return result; + } + } + } + + found = false; + return default; + } + + static TSource? TryGetLast(this IEnumerable source, Func predicate, out bool found) + { + if (source is IList list) + { + for (int i = list.Count - 1; i >= 0; --i) + { + TSource result = list[i]; + if (predicate(result)) + { + found = true; + return result; + } + } + } + else + { + using (IEnumerator e = source.GetEnumerator()) + { + while (e.MoveNext()) + { + TSource result = e.Current; + if (predicate(result)) + { + while (e.MoveNext()) + { + TSource element = e.Current; + if (predicate(element)) + { + result = element; + } + } + + found = true; + return result; + } + } + } + } + + found = false; + return default; + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Max.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Max.cs new file mode 100644 index 000000000..58180cb2f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Max.cs @@ -0,0 +1,34 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// Returns the maximum value in a generic sequence. + /// The type of the elements of . + /// A sequence of values to determine the maximum value of. + /// The to compare values. + /// The maximum value in the sequence. + /// is . + /// No object in implements the or interface. + /// + /// If type implements , the method uses that implementation to compare values. Otherwise, if type implements , that implementation is used to compare values. + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// In Visual Basic query expression syntax, an `Aggregate Into Max()` clause translates to an invocation of . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.max#system-linq-enumerable-max-1(system-collections-generic-ienumerable((-0))-system-collections-generic-icomparer((-0))) + public static TSource? Max( + this IEnumerable source, + IComparer? comparer) => + source + .MaxBy(_ => _, comparer); + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MaxBy.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MaxBy.cs new file mode 100644 index 000000000..ccdaf1a47 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MaxBy.cs @@ -0,0 +1,124 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// + /// Returns the maximum value in a generic sequence according to a specified key selector function. + /// + /// The type of the elements of . + /// The type of key to compare elements by. + /// A sequence of values to determine the maximum value of. + /// A function to extract the key for each element. + /// The value with the maximum key in the sequence. + /// is . + /// No key extracted from implements the or interface. + /// + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.maxby#system-linq-enumerable-maxby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))) + public static TSource? MaxBy( + this IEnumerable source, + Func keySelector) => + MaxBy(source, keySelector, null); + + /// Returns the maximum value in a generic sequence according to a specified key selector function. + /// The type of the elements of . + /// The type of key to compare elements by. + /// A sequence of values to determine the maximum value of. + /// A function to extract the key for each element. + /// The to compare keys. + /// The value with the maximum key in the sequence. + /// is . + /// No key extracted from implements the or interface. + /// + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.maxby#system-linq-enumerable-maxby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))-system-collections-generic-icomparer((-1))) + public static TSource? MaxBy( + this IEnumerable source, + Func keySelector, + IComparer? comparer) + { + // Simplified from https://github.com/dotnet/runtime/blob/5d09a8f94c72ca4ef0a9c79eb9c58d06198e3ba9/src/libraries/System.Linq/src/System/Linq/Max.cs#L445-L526 + if (source is null) throw new ArgumentNullException(nameof(source)); + if (keySelector is null) throw new ArgumentNullException(nameof(keySelector)); + + comparer ??= Comparer.Default; + + using IEnumerator e = source.GetEnumerator(); + + if (!e.MoveNext()) + { + if (default(TSource) is null) + { + return default; + } + else + { + ThrowNoElementsException(); + } + } + + TSource value = e.Current; + TKey key = keySelector(value); + + if (default(TKey) is null) + { + if (key is null) + { + TSource firstValue = value; + + do + { + if (!e.MoveNext()) + { + // All keys are null, surface the first element. + return firstValue; + } + + value = e.Current; + key = keySelector(value); + } + while (key is null); + } + + while (e.MoveNext()) + { + TSource nextValue = e.Current; + TKey nextKey = keySelector(nextValue); + if (nextKey is not null && comparer.Compare(nextKey, key) > 0) + { + key = nextKey; + value = nextValue; + } + } + } + else + { + while (e.MoveNext()) + { + TSource nextValue = e.Current; + TKey nextKey = keySelector(nextValue); + if (comparer.Compare(nextKey, key) > 0) + { + key = nextKey; + value = nextValue; + } + } + } + + return value; + + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Min.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Min.cs new file mode 100644 index 000000000..23a96e4c6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Min.cs @@ -0,0 +1,36 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + +#if !NET6_0_OR_GREATER + + /// Returns the minimum value in a generic sequence. + /// The type of the elements of . + /// A sequence of values to determine the minimum value of. + /// The to compare values. + /// The minimum value in the sequence. + /// is . + /// No object in implements the or interface. + /// + /// If type implements , the method uses that implementation to compare values. Otherwise, if type implements , that implementation is used to compare values. + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// In Visual Basic query expression syntax, an `Aggregate Into Min()` clause translates to an invocation of . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.min#system-linq-enumerable-min-1(system-collections-generic-ienumerable((-0))-system-collections-generic-icomparer((-0))) + public static TSource? Min( + this IEnumerable source, + IComparer? comparer) => + source + .MinBy(_ => _, comparer); + +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MinBy.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MinBy.cs new file mode 100644 index 000000000..7a7101e48 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_MinBy.cs @@ -0,0 +1,125 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + +#if !NET6_0_OR_GREATER + + /// + /// Returns the minimum value in a generic sequence according to a specified key selector function. + /// + /// The type of the elements of . + /// The type of key to compare elements by. + /// A sequence of values to determine the minby value of. + /// A function to extract the key for each element. + /// The value with the minimum key in the sequence. + /// is . + /// No key extracted from implements the or interface. + /// + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.minby#system-linq-enumerable-minby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))) + public static TSource? MinBy( + this IEnumerable source, + Func keySelector) => + MinBy(source, keySelector, null); + + /// Returns the minimum value in a generic sequence according to a specified key selector function. + /// The type of the elements of . + /// The type of key to compare elements by. + /// A sequence of values to determine the minimum value of. + /// A function to extract the key for each element. + /// The to compare keys. + /// The value with the minimum key in the sequence. + /// is . + /// No key extracted from implements the or interface. + /// + /// If is a reference type and the source sequence is empty or contains only values that are , this method returns . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.minby#system-linq-enumerable-minby-2(system-collections-generic-ienumerable((-0))-system-func((-0-1))-system-collections-generic-icomparer((-1))) + public static TSource? MinBy( + this IEnumerable source, + Func keySelector, + IComparer? comparer) + { + // Simplified from https://github.com/dotnet/runtime/blob/5d09a8f94c72ca4ef0a9c79eb9c58d06198e3ba9/src/libraries/System.Linq/src/System/Linq/Min.cs#L413-L503 + if (source is null) throw new ArgumentNullException(nameof(source)); + if (keySelector is null) throw new ArgumentNullException(nameof(keySelector)); + + comparer ??= Comparer.Default; + + using IEnumerator e = source.GetEnumerator(); + + if (!e.MoveNext()) + { + if (default(TSource) is null) + { + return default; + } + else + { + ThrowNoElementsException(); + } + } + + TSource value = e.Current; + TKey key = keySelector(value); + + if (default(TKey) is null) + { + if (key is null) + { + TSource firstValue = value; + + do + { + if (!e.MoveNext()) + { + // All keys are null, surface the first element. + return firstValue; + } + + value = e.Current; + key = keySelector(value); + } + while (key is null); + } + + while (e.MoveNext()) + { + TSource nextValue = e.Current; + TKey nextKey = keySelector(nextValue); + if (nextKey is not null && comparer.Compare(nextKey, key) < 0) + { + key = nextKey; + value = nextValue; + } + } + } + else + { + while (e.MoveNext()) + { + TSource nextValue = e.Current; + TKey nextKey = keySelector(nextValue); + if (comparer.Compare(nextKey, key) < 0) + { + key = nextKey; + value = nextValue; + } + } + } + + return value; + } + +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SingleOrDefault.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SingleOrDefault.cs new file mode 100644 index 000000000..299276ea9 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SingleOrDefault.cs @@ -0,0 +1,106 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition. + /// The type of the elements of . + /// An to return a single element from. + /// A function to test an element for a condition. + /// The default value to return if the sequence is empty. + /// The single element of the input sequence that satisfies the condition, or if no such element is found. + /// or is . + /// More than one element satisfies the condition in . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault#system-linq-enumerable-singleordefault-1(system-collections-generic-ienumerable((-0))-system-func((-0-system-boolean))-0) + public static TSource SingleOrDefault(this IEnumerable source, Func predicate, TSource defaultValue) + { + var single = source.TryGetSingle(predicate, out bool found); + return found ? single! : defaultValue; + } + + static TSource? TryGetSingle(this IEnumerable source, Func predicate, out bool found) + { + using (IEnumerator e = source.GetEnumerator()) + { + while (e.MoveNext()) + { + TSource result = e.Current; + if (predicate(result)) + { + while (e.MoveNext()) + { + if (predicate(e.Current)) + { + throw new InvalidOperationException("Sequence contains more than one matching element"); + } + } + found = true; + return result; + } + } + } + + found = false; + return default; + } + + /// Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. + /// The type of the elements of . + /// An to return the single element of. + /// The default value to return if the sequence is empty. + /// The single element of the input sequence, or if the sequence contains no elements. + /// is . + /// The input sequence contains more than one element. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault#system-linq-enumerable-singleordefault-1(system-collections-generic-ienumerable((-0))-0) + public static TSource SingleOrDefault(this IEnumerable source, TSource defaultValue) + { + var single = source.TryGetSingle(out bool found); + return found ? single! : defaultValue; + } + + static TSource? TryGetSingle(this IEnumerable source, out bool found) + { + if (source is IList list) + { + switch (list.Count) + { + case 0: + found = false; + return default; + case 1: + found = true; + return list[0]; + } + } + else + { + using (IEnumerator e = source.GetEnumerator()) + { + if (!e.MoveNext()) + { + found = false; + return default; + } + + TSource result = e.Current; + if (!e.MoveNext()) + { + found = true; + return result; + } + } + } + + found = false; + throw new InvalidOperationException("Sequence contains more than one matching element"); + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SkipLast.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SkipLast.cs new file mode 100644 index 000000000..c92e93cb3 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_SkipLast.cs @@ -0,0 +1,29 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + /// + /// Returns a new enumerable collection that contains the elements from source with the last count elements of the + /// source collection omitted. + /// + /// An enumerable collection instance. + /// The number of elements to omit from the end of the collection. + /// The type of the elements in the enumerable collection. + /// A new enumerable collection that contains the elements from source minus count elements from the end + /// of the collection. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skiplast + public static IEnumerable SkipLast( + this IEnumerable target, + int count) => + target.Reverse().Skip(count).Reverse(); +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Take.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Take.cs new file mode 100644 index 000000000..b1e817b9d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Take.cs @@ -0,0 +1,211 @@ +// +#pragma warning disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Collections.Generic; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool IsEmptyArray(IEnumerable source) => + source is TSource[] { Length: 0 }; + + static IEnumerable TakeRangeFromEndIterator(IEnumerable source, bool isStartIndexFromEnd, int startIndex, bool isEndIndexFromEnd, int endIndex) + { + // Attempt to extract the count of the source enumerator, + // in order to convert fromEnd indices to regular indices. + // Enumerable counts can change over time, so it is very + // important that this check happens at enumeration time; + // do not move it outside of the iterator method. + if (source.TryGetNonEnumeratedCount(out int count)) + { + startIndex = CalculateStartIndex(isStartIndexFromEnd, startIndex, count); + endIndex = CalculateEndIndex(isEndIndexFromEnd, endIndex, count); + + if (startIndex < endIndex) + { + foreach (TSource element in TakeRangeIterator(source, startIndex, endIndex)) + { + yield return element; + } + } + + yield break; + } + + Queue queue; + + if (isStartIndexFromEnd) + { + // TakeLast compat: enumerator should be disposed before yielding the first element. + using (IEnumerator e = source.GetEnumerator()) + { + if (!e.MoveNext()) + { + yield break; + } + + queue = new Queue(); + queue.Enqueue(e.Current); + count = 1; + + while (e.MoveNext()) + { + if (count < startIndex) + { + queue.Enqueue(e.Current); + ++count; + } + else + { + do + { + queue.Dequeue(); + queue.Enqueue(e.Current); + checked + { + ++count; + } + } while (e.MoveNext()); + + break; + } + } + } + + startIndex = CalculateStartIndex(isStartIndexFromEnd: true, startIndex, count); + endIndex = CalculateEndIndex(isEndIndexFromEnd, endIndex, count); + + for (int rangeIndex = startIndex; rangeIndex < endIndex; rangeIndex++) + { + yield return queue.Dequeue(); + } + } + else + { + // SkipLast compat: the enumerator should be disposed at the end of the enumeration. + using IEnumerator e = source.GetEnumerator(); + + count = 0; + while (count < startIndex && e.MoveNext()) + { + ++count; + } + + if (count == startIndex) + { + queue = new Queue(); + while (e.MoveNext()) + { + if (queue.Count == endIndex) + { + do + { + queue.Enqueue(e.Current); + yield return queue.Dequeue(); + } while (e.MoveNext()); + + break; + } + else + { + queue.Enqueue(e.Current); + } + } + } + } + + static int CalculateStartIndex(bool isStartIndexFromEnd, int startIndex, int count) => + Math.Max(0, isStartIndexFromEnd ? count - startIndex : startIndex); + + static int CalculateEndIndex(bool isEndIndexFromEnd, int endIndex, int count) => + Math.Min(count, isEndIndexFromEnd ? count - endIndex : endIndex); + } + + static IEnumerable TakeRangeIterator(IEnumerable source, int startIndex, int endIndex) + { + using IEnumerator e = source.GetEnumerator(); + + int index = 0; + while (index < startIndex && e.MoveNext()) + { + ++index; + } + + if (index < startIndex) + { + yield break; + } + + while (index < endIndex && e.MoveNext()) + { + yield return e.Current; + ++index; + } + } + +#if FeatureValueTuple + + //https://github.com/dotnet/runtime/blob/main/src/libraries/System.Linq/src/System/Linq/Take.cs + /// Returns a specified range of contiguous elements from a sequence. + /// The type of the elements of . + /// The sequence to return elements from. + /// The range of elements to return, which has start and end indexes either from the start or the end. + /// is . + /// An that contains the specified of elements from the sequence. + /// + /// This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its `GetEnumerator` method directly or by using `foreach` in Visual C# or `For Each` in Visual Basic. + /// enumerates and yields elements whose indices belong to the specified . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take#system-linq-enumerable-take-1(system-collections-generic-ienumerable((-0))-system-range) + public static IEnumerable Take( + this IEnumerable target, + Range range) + { + if (IsEmptyArray(target)) + { + return []; + } + + Index start = range.Start; + Index end = range.End; + bool isStartIndexFromEnd = start.IsFromEnd; + bool isEndIndexFromEnd = end.IsFromEnd; + int startIndex = start.Value; + int endIndex = end.Value; + + if (isStartIndexFromEnd) + { + if (startIndex == 0 || (isEndIndexFromEnd && endIndex >= startIndex)) + { + return []; + } + } + else if (!isEndIndexFromEnd) + { + return startIndex >= endIndex ? [] : TakeRangeIterator(target, startIndex, endIndex); + } + + return TakeRangeFromEndIterator(target, isStartIndexFromEnd, startIndex, isEndIndexFromEnd, endIndex); + } + + static IEnumerable TakeIterator(IEnumerable source, int count) + { + foreach (TSource element in source) + { + yield return element; + if (--count == 0) break; + } + } + +#endif +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TakeLast.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TakeLast.cs new file mode 100644 index 000000000..7c58ad465 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TakeLast.cs @@ -0,0 +1,39 @@ +// +#pragma warning disable + +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Collections.Generic; + +static partial class Polyfill +{ + +#if NETSTANDARD2_0 || NETFRAMEWORK + + /// + /// Returns a new enumerable collection that contains the last count elements from source. + /// + /// An enumerable collection instance. + /// The number of elements to take from the end of the collection. + /// The type of the elements in the enumerable collection. + /// A new enumerable collection that contains the last count elements from source. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.takelast + public static IEnumerable TakeLast(this IEnumerable source, int count) + { + if (count <= 0 || IsEmptyArray(source)) + { + return []; + } + + return TakeRangeFromEndIterator( + source, + isStartIndexFromEnd: true, startIndex: count, + isEndIndexFromEnd: true, endIndex: 0); + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ThrowHelper.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ThrowHelper.cs new file mode 100644 index 000000000..80845cff8 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ThrowHelper.cs @@ -0,0 +1,10 @@ +// +#pragma warning disable + +namespace Polyfills; + +static partial class Polyfill +{ + static void ThrowNoElementsException() => + throw new System.InvalidOperationException("Sequence contains no elements"); +} diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ToHashSet.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ToHashSet.cs new file mode 100644 index 000000000..811a9ce13 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_ToHashSet.cs @@ -0,0 +1,28 @@ +// +#pragma warning disable + +#if NET471 || NET46X || NETSTANDARD2_0 + +namespace Polyfills; + +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + /// + /// Creates a HashSet from an IEnumerable using the comparer to compare keys. + /// + /// An IEnumerable to create a HashSet from. + /// An IEqualityComparer to compare keys. + /// The type of the elements of source. + /// A HashSet that contains values of type TSource selected from the input sequence. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tohashset#system-linq-enumerable-tohashset-1(system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0))) + public static HashSet ToHashSet( + this IEnumerable target, + IEqualityComparer? comparer = null) => + new HashSet(target, comparer); + +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TryGetNonEnumeratedCount.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TryGetNonEnumeratedCount.cs new file mode 100644 index 000000000..61f452583 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_TryGetNonEnumeratedCount.cs @@ -0,0 +1,53 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +namespace Polyfills; + +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +static partial class Polyfill +{ + /// + /// Attempts to determine the number of elements in a sequence without forcing an enumeration. + /// + /// The type of the elements of . + /// A sequence that contains elements to be counted. + /// + /// When this method returns, contains the count of if successful, + /// or zero if the method failed to determine the count. + /// + /// if the count of can be determined without enumeration; + /// otherwise, . + /// + /// + /// The method performs a series of type tests, identifying common subtypes whose + /// count can be determined without enumerating; this includes , + /// as well as internal types used in the LINQ implementation. + /// + /// The method is typically a constant-time operation, but ultimately this depends on the complexity + /// characteristics of the underlying collection implementation. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.trygetnonenumeratedcount + public static bool TryGetNonEnumeratedCount(this IEnumerable target, out int count) + { + if (target is ICollection genericCollection) + { + count = genericCollection.Count; + return true; + } + + if (target is ICollection collection) + { + count = collection.Count; + return true; + } + + count = 0; + return false; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Zip.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Zip.cs new file mode 100644 index 000000000..c48516c46 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IEnumerable_Zip.cs @@ -0,0 +1,65 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Collections.Generic; + +static partial class Polyfill +{ +#if FeatureValueTuple + +#if !NET6_0_OR_GREATER + + /// + /// Produces a sequence of tuples with elements from the three specified sequences. + /// + /// The type of the elements of the first input sequence. + /// The type of the elements of the second input sequence. + /// The type of the elements of the third input sequence. + /// The first sequence to merge. + /// The second sequence to merge. + /// The third sequence to merge. + /// A sequence of tuples with elements taken from the first, second, and third sequences, in that order. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip#system-linq-enumerable-zip-3(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-1))-system-collections-generic-ienumerable((-2))) + public static IEnumerable<(TFirst First, TSecond Second, TThird Third)> Zip(this IEnumerable first, IEnumerable second, IEnumerable third) + { + using (IEnumerator e1 = first.GetEnumerator()) + using (IEnumerator e2 = second.GetEnumerator()) + using (IEnumerator e3 = third.GetEnumerator()) + { + while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext()) + { + yield return (e1.Current, e2.Current, e3.Current); + } + } + } +#endif + +#if NETCOREAPP2X || NETSTANDARD || NETFRAMEWORK + + /// + /// Produces a sequence of tuples with elements from the two specified sequences. + /// + /// The type of the elements of the first input sequence. + /// The type of the elements of the second input sequence. + /// The first sequence to merge. + /// The second sequence to merge. + /// A sequence of tuples with elements taken from the first, and second sequences, in that order. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip#system-linq-enumerable-zip-2(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-1))) + public static IEnumerable<(TFirst First, TSecond Second)> Zip(this IEnumerable first, IEnumerable second) + { + using (IEnumerator e1 = first.GetEnumerator()) + using (IEnumerator e2 = second.GetEnumerator()) + { + while (e1.MoveNext() && e2.MoveNext()) + { + yield return (e1.Current, e2.Current); + } + } + } + +#endif + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IReadOnlyDictionary.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IReadOnlyDictionary.cs new file mode 100644 index 000000000..762d27627 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_IReadOnlyDictionary.cs @@ -0,0 +1,65 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ + /// + /// Tries to get the value associated with the specified key in the dictionary. + /// + /// A dictionary with keys of type TKey and values of type TValue. + /// The key of the value to get. + /// The type of the keys in the dictionary. + /// The type of the values in the dictionary. + /// + /// A TValue instance. When the method is successful, the returned object is the value associated with + /// the specified key. When the method fails, it returns the default value for TValue. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.getvalueordefault + public static TValue? GetValueOrDefault( + this IReadOnlyDictionary target, + TKey key) + where TKey : notnull + { + if (target.TryGetValue(key, out var result)) + { + return result; + } + + return default; + } + + /// + /// Tries to get the value associated with the specified key in the dictionary. + /// + /// A dictionary with keys of type TKey and values of type TValue. + /// The key of the value to get. + /// A dictionary with keys of type TKey and values of type TValue. + /// The type of the keys in the dictionary. + /// The type of the values in the dictionary. + /// + /// A TValue instance. When the method is successful, the returned object is the value associated with + /// the specified key. When the method fails, it returns the default value for TValue. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.getvalueordefault#system-collections-generic-collectionextensions-getvalueordefault-2(system-collections-generic-ireadonlydictionary((-0-1))-0-1) + public static TValue GetValueOrDefault( + this IReadOnlyDictionary target, + TKey key, + TValue defaultValue = default!) + where TKey : notnull + { + if (target.TryGetValue(key, out var result)) + { + return result!; + } + + return defaultValue; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_KeyValuePair.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_KeyValuePair.cs new file mode 100644 index 000000000..3c6386533 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_KeyValuePair.cs @@ -0,0 +1,28 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ + /// + /// Deconstructs the current + /// + /// The key of the current . + /// The value of the current . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2.deconstruct + public static void Deconstruct( + this KeyValuePair target, + out TKey key, + out TValue value) + { + key = target.Key; + value = target.Value; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_List.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_List.cs new file mode 100644 index 000000000..1ab3474d2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_List.cs @@ -0,0 +1,68 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +static partial class Polyfill +{ +#if !NET7_0_OR_GREATER + + /// Returns a read-only wrapper for the current collection. + /// An object that acts as a read-only wrapper around the current . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.asreadonly#system-collections-generic-collectionextensions-asreadonly-1(system-collections-generic-ilist((-0))) + public static ReadOnlyCollection AsReadOnly(this IList target) => + new(target); +#endif + +#if !NET8_0_OR_GREATER && FeatureMemory + /// Adds the elements of the specified span to the end of the . + /// The type of elements in the list. + /// The list to which the elements should be added. + /// The span whose elements should be added to the end of the . + /// The is null. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.addrange + public static void AddRange(this List target, ReadOnlySpan source) + { + foreach (var item in source) + { + target.Add(item); + } + } + + /// Inserts the elements of a span into the at the specified index. + /// The type of elements in the list. + /// The list into which the elements should be inserted. + /// The zero-based index at which the new elements should be inserted. + /// The span whose elements should be added to the . + /// The is null. + /// is less than 0 or greater than 's . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.insertrange + public static void InsertRange(this List target, int index, ReadOnlySpan source) + { + for (var i = 0; i < source.Length; i++) + { + var item = source[i]; + target.Insert(i + index, item); + } + } + + /// Copies the entire to a span. + /// The type of elements in the list. + /// The list from which the elements are copied. + /// The span that is the destination of the elements copied from . + /// The is null. + /// The number of elements in the source is greater than the number of elements that the destination span can contain. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.collectionextensions.copyto + public static void CopyTo(this List target, Span destination) + { + for (var index = 0; index < target.Count; index++) + { + destination[index] = target[index]; + } + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory.cs new file mode 100644 index 000000000..03b163884 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory.cs @@ -0,0 +1,173 @@ +// +#pragma warning disable + +#if FeatureMemory + +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ +#if !NET6_0_OR_GREATER + + /// + /// Returns an enumeration of lines over the provided span. + /// + /// + /// It is recommended that protocol parsers not utilize this API. See the documentation + /// for for more information on how newline + /// sequences are detected. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.enumeratelines#system-memoryextensions-enumeratelines(system-readonlyspan((system-char))) + public static SpanLineEnumerator EnumerateLines(this ReadOnlySpan target) => + new(target); + + /// + /// Returns an enumeration of lines over the provided span. + /// + /// + /// It is recommended that protocol parsers not utilize this API. See the documentation + /// for for more information on how newline + /// sequences are detected. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.enumeratelines#system-memoryextensions-enumeratelines(system-span((system-char))) + public static SpanLineEnumerator EnumerateLines(this Span target) => + new(target); + +#endif + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X + + /// + /// Removes all leading white-space characters from the span. + /// + /// The source span from which the characters are removed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.trimstart#system-memoryextensions-trimstart(system-span((system-char))) + public static Span TrimStart(this Span target) + => target.Slice(ClampStart(target)); + + /// + /// Removes all trailing white-space characters from the span. + /// + /// The source span from which the characters are removed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.trimend#system-memoryextensions-trimend(system-span((system-char))) + public static Span TrimEnd(this Span target) + => target.Slice(0, ClampEnd(target, 0)); + + /// + /// Delimits all leading occurrences of whitespace charecters from the span. + /// + /// The source span from which the characters are removed. + static int ClampStart(ReadOnlySpan target) + { + int start = 0; + + for (; start < target.Length; start++) + { + if (!char.IsWhiteSpace(target[start])) + { + break; + } + } + + return start; + } + + /// + /// Delimits all trailing occurrences of whitespace charecters from the span. + /// + /// The source span from which the characters are removed. + /// The start index from which to being searching. + static int ClampEnd(ReadOnlySpan target, int start) + { + int end = target.Length - 1; + + for (; end >= start; end--) + { + if (!char.IsWhiteSpace(target[end])) + { + break; + } + } + + return end - start + 1; + } + + /// + /// Indicates whether a specified value is found in a read-only span. Values are compared using IEquatable{T}.Equals(T). + /// + /// The value to search for. + /// true if found, false otherwise. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.contains#system-memoryextensions-contains-1(system-readonlyspan((-0))-0) + public static bool Contains( + this ReadOnlySpan target, + T value) + where T : IEquatable + { + for (var index = 0; index < target.Length; index++) + { + if (target[index].Equals(value)) + { + return true; + } + } + + return false; + } + + /// + /// Indicates whether a specified value is found in a only span. Values are compared using IEquatable{T}.Equals(T). + /// + /// The value to search for. + /// true if found, false otherwise. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.contains#system-memoryextensions-contains-1(system-span((-0))-0) + public static bool Contains( + this Span target, + T value) + where T : IEquatable + { + for (var index = 0; index < target.Length; index++) + { + if (target[index].Equals(value)) + { + return true; + } + } + + return false; + } + + /// + /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). + /// + /// The first sequence to compare. + /// The second sequence to compare. + /// true if the two sequences are equal; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.sequenceequal#system-memoryextensions-sequenceequal-1(system-readonlyspan((-0))-system-readonlyspan((-0))) + public static bool SequenceEqual( + this ReadOnlySpan target, + string other) => + target.SequenceEqual(other.AsSpan()); + + /// + /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). + /// + /// The first sequence to compare. + /// The second sequence to compare. + /// true if the two sequences are equal; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.sequenceequal#system-memoryextensions-sequenceequal-1(system-span((-0))-system-readonlyspan((-0))) + public static bool SequenceEqual( + this Span target, + string other) => + target.SequenceEqual(other.AsSpan()); + +#endif + +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_EndsWith.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_EndsWith.cs new file mode 100644 index 000000000..f60be216b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_EndsWith.cs @@ -0,0 +1,72 @@ +// + +#if FeatureMemory + +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Text; +using System.ComponentModel; +using System.Runtime.CompilerServices; + +static partial class Polyfill +{ + +#if !NET9_0_OR_GREATER + + /// + /// Determines whether the specified value appears at the end of the span. + /// + /// The span to search. + /// The value to compare. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.endswith#system-memoryextensions-endswith-1(system-readonlyspan((-0))-0) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool EndsWith(this ReadOnlySpan target, T value) + where T : IEquatable? + { + if (target.Length == 0) + { + return false; + } + + var last = target[target.Length-1]; + return last?.Equals(value) ?? (object?)value is null; + } + +#endif + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X + + /// + /// Determines whether the end of the span matches the specified value when compared using the specified option. + /// + /// The source span. + /// The sequence to compare to the end of the source span. + /// An enumeration value that determines how span and value are compared. + /// true if value matches the end of span; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.endswith#system-memoryextensions-endswith-1(system-readonlyspan((-0))-system-readonlyspan((-0))) + public static bool EndsWith( + this ReadOnlySpan target, + string other, + StringComparison comparison = StringComparison.CurrentCulture) => + target.EndsWith(other.AsSpan(), comparison); + + /// + /// Determines whether the specified sequence appears at the end of a span. + /// + /// The source span. + /// The sequence to compare to the end of the source span. + /// true if value matches the end of span; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.endswith#system-memoryextensions-endswith-1(system-span((-0))-system-readonlyspan((-0))) + public static bool EndsWith( + this Span target, + string other) => + target.EndsWith(other.AsSpan()); + +#endif + +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplit.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplit.cs new file mode 100644 index 000000000..baead155e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplit.cs @@ -0,0 +1,94 @@ +// +#pragma warning disable + +#if FeatureMemory && FeatureValueTuple + +namespace Polyfills; +using System; +using System.Buffers; +using System.Diagnostics.CodeAnalysis; + +static partial class Polyfill +{ + +#if !NET9_0_OR_GREATER + //https://github.com/bbartels/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs + + /// + /// Returns a type that allows for enumeration of each element within a split span + /// using the provided separator character. + /// + /// The type of the elements. + /// The source span to be enumerated. + /// The separator character to be used to split the provided span. + /// Returns a . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.split#system-memoryextensions-split-1(system-readonlyspan((-0))-0) + public static SpanSplitEnumerator Split(this ReadOnlySpan source, T separator) + where T : IEquatable => + new SpanSplitEnumerator(source, separator); + + /// + /// Returns a type that allows for enumeration of each element within a split span + /// using the provided separator span. + /// + /// The type of the elements. + /// The source span to be enumerated. + /// The separator span to be used to split the provided span. + /// Returns a . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.split#system-memoryextensions-split-1(system-readonlyspan((-0))-system-readonlyspan((-0))) + public static SpanSplitEnumerator Split(this ReadOnlySpan source, ReadOnlySpan separator) + where T : IEquatable => + new SpanSplitEnumerator(source, separator, treatAsSingleSeparator: true); + +#if LangVersion13 + + /// + /// Returns a type that allows for enumeration of each element within a split span + /// using any of the provided elements. + /// + /// The type of the elements. + /// The source span to be enumerated. + /// The separators to be used to split the provided span. + /// Returns a . + /// + /// If is and if is empty, + /// all Unicode whitespace characters are used as the separators. This matches the behavior of when + /// and related overloads are used with an empty separator array, + /// or when + /// is used with an empty separator span. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.splitany#system-memoryextensions-splitany-1(system-readonlyspan((-0))-system-readonlyspan((-0))) + public static SpanSplitEnumerator SplitAny(this ReadOnlySpan source, [UnscopedRef] params ReadOnlySpan separators) + where T : IEquatable => + new SpanSplitEnumerator(source, separators); + +#endif + +#if NET8_0 + + /// + /// Returns a type that allows for enumeration of each element within a split span + /// using the provided . + /// + /// The type of the elements. + /// The source span to be enumerated. + /// The to be used to split the provided span. + /// Returns a . + /// + /// Unlike , the is not checked for being empty. + /// An empty will result in no separators being found, regardless of the type of , + /// whereas will use all Unicode whitespace characters as separators if is + /// empty and is . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.splitany#system-memoryextensions-splitany-1(system-readonlyspan((-0))-system-buffers-searchvalues((-0))) + public static SpanSplitEnumerator SplitAny(this ReadOnlySpan source, SearchValues separators) + where T : IEquatable => + new SpanSplitEnumerator(source, separators); + +#endif + +#endif + +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumerator.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumerator.cs new file mode 100644 index 000000000..68f8380b1 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumerator.cs @@ -0,0 +1,220 @@ +// +#pragma warning disable + +#if FeatureMemory && !NET9_0_OR_GREATER && FeatureValueTuple + +namespace Polyfills; + +using System; +using System.Buffers; +using System.Linq; +using System.Runtime.CompilerServices; + +static partial class Polyfill +{ + /// + /// Enables enumerating each split within a that has been divided using one or more separators. + /// + //https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.spansplitenumerator-1")] + public ref struct SpanSplitEnumerator + where T : IEquatable + { + /// The input span being split. + readonly ReadOnlySpan _span; + + /// A single separator to use when is . + readonly T _separator = default!; + + /// + /// A separator span to use when is (in which case + /// it's treated as a single separator) or (in which case it's treated as a set of separators). + /// + readonly ReadOnlySpan _separatorBuffer; + +#if NET8_0 + /// A set of separators to use when is . + readonly SearchValues _searchValues = default!; +#endif + + /// Mode that dictates how the instance was configured and how its fields should be used in . + SpanSplitEnumeratorMode _splitMode; + + /// The inclusive starting index in of the current range. + int _startCurrent = 0; + + /// The exclusive ending index in of the current range. + int _endCurrent = 0; + + /// The index in from which the next separator search should start. + int _startNext = 0; + + /// Gets an enumerator that allows for iteration over the split span. + /// Returns a that can be used to iterate over the split span. + public SpanSplitEnumerator GetEnumerator() => this; + + /// Gets the current element of the enumeration. + /// Returns a instance that indicates the bounds of the current element withing the source span. + public Range Current => new Range(_startCurrent, _endCurrent); + +#if NET8_0 + /// Initializes the enumerator for . + internal SpanSplitEnumerator(ReadOnlySpan span, SearchValues searchValues) + { + _span = span; + _splitMode = SpanSplitEnumeratorMode.SearchValues; + _searchValues = searchValues; + } +#endif + + /// Initializes the enumerator for . + /// + /// If is empty and is , as an optimization + /// it will instead use with a cached + /// for all whitespace characters. + /// + internal SpanSplitEnumerator(ReadOnlySpan span, ReadOnlySpan separators) + { + _span = span; + + if (typeof(T) == typeof(char) && separators.Length == 0) + { +#if NET8_0 + _searchValues = Unsafe.As>(WhiteSpaceChars); + _splitMode = SpanSplitEnumeratorMode.SearchValues; +#else + _separatorBuffer = WhiteSpaceChars.AsSpan(); + _splitMode = SpanSplitEnumeratorMode.Any; +#endif + return; + } + + _separatorBuffer = separators; + _splitMode = SpanSplitEnumeratorMode.Any; + } + + /// Initializes the enumerator for (or if the separator is empty). + /// must be true. + internal SpanSplitEnumerator(ReadOnlySpan span, ReadOnlySpan separator, bool treatAsSingleSeparator) + { + _span = span; + _separatorBuffer = separator; + _splitMode = separator.Length == 0 ? SpanSplitEnumeratorMode.EmptySequence : SpanSplitEnumeratorMode.Sequence; + } + + /// Initializes the enumerator for . + internal SpanSplitEnumerator(ReadOnlySpan span, T separator) + { + _span = span; + _separator = separator; + _splitMode = SpanSplitEnumeratorMode.SingleElement; + } + + /// + /// Advances the enumerator to the next element of the enumeration. + /// + /// if the enumerator was successfully advanced to the next element; if the enumerator has passed the end of the enumeration. + public bool MoveNext() + { + // Search for the next separator index. + int separatorIndex, separatorLength; + switch (_splitMode) + { + case SpanSplitEnumeratorMode.None: + return false; + + case SpanSplitEnumeratorMode.SingleElement: + separatorLength = 1; + #if NETFRAMEWORK + if (_separator is null) + { + separatorIndex = -1; + for (int i = _startNext; i < _span.Length; i++) + { + if (_span[i] == null) + { + separatorIndex = i; + break; + } + } + break; + } + #endif + separatorIndex = _span.Slice(_startNext) + .IndexOf(_separator); + break; + + case SpanSplitEnumeratorMode.Any: + separatorLength = 1; +#if !NETCOREAPP + //https://github.com/dotnet/coreclr/pull/25075 + if (_separatorBuffer.Length == 0) + { + separatorIndex = -1; + break; + } +#endif + separatorIndex = _span.Slice(_startNext) + .IndexOfAny(_separatorBuffer); + break; + + case SpanSplitEnumeratorMode.Sequence: + separatorIndex = _span.Slice(_startNext) + .IndexOf(_separatorBuffer); + separatorLength = _separatorBuffer.Length; + break; + + case SpanSplitEnumeratorMode.EmptySequence: + separatorIndex = -1; + separatorLength = 1; + break; +#if NET8_0 + case SpanSplitEnumeratorMode.SearchValues: + separatorIndex = _span.Slice(_startNext).IndexOfAny(_searchValues); + separatorLength = 1; + break; +#endif + + default: + throw new Exception($"Invalid split mode: {_splitMode}"); + } + + _startCurrent = _startNext; + if (separatorIndex >= 0) + { + _endCurrent = _startCurrent + separatorIndex; + _startNext = _endCurrent + separatorLength; + } + else + { + _startNext = _endCurrent = _span.Length; + + // Set _splitMode to None so that subsequent MoveNext calls will return false. + _splitMode = SpanSplitEnumeratorMode.None; + } + + return true; + } + + const string whitespaces = "\t\n\v\f\r\u0020\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"; + +#if NET8_0 + public static readonly SearchValues WhiteSpaceChars = + SearchValues.Create(whitespaces.AsSpan()); +#else + public static readonly T[] WhiteSpaceChars; + + static SpanSplitEnumerator() + { + if (typeof(T) == typeof(char)) + { + WhiteSpaceChars = whitespaces + .Cast() + .ToArray(); + } + } +#endif + } +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumeratorMode.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumeratorMode.cs new file mode 100644 index 000000000..1e0ad78e0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_SpanSplitEnumeratorMode.cs @@ -0,0 +1,38 @@ +// +#pragma warning disable + +#if FeatureMemory && !NET9_0_OR_GREATER + +namespace Polyfills; + +static partial class Polyfill +{ + /// Indicates in which mode is operating, with regards to how it should interpret its state. + enum SpanSplitEnumeratorMode + { + /// Either a default was used, or the enumerator has finished enumerating and there's no more work to do. + None = 0, + + /// A single T separator was provided. + SingleElement, + + /// A span of separators was provided, each of which should be treated independently. + Any, + + /// The separator is a span of elements to be treated as a single sequence. + Sequence, + + /// The separator is an empty sequence, such that no splits should be performed. + EmptySequence, + +#if NET8_0 + /// + /// A was provided and should behave the same as with but with the separators in the + /// instance instead of in a . + /// + SearchValues +#endif + } +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_StartsWith.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_StartsWith.cs new file mode 100644 index 000000000..a3a1695d0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Memory_StartsWith.cs @@ -0,0 +1,64 @@ +// + +#pragma warning disable + +#if FeatureMemory + +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ +#if !NET9_0_OR_GREATER + + /// + /// Determines whether the specified value appears at the start of the span. + /// + /// The span to search. + /// The value to compare. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.endswith#system-memoryextensions-endswith-1(system-readonlyspan((-0))-0) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool StartsWith(this ReadOnlySpan target, T value) + where T : IEquatable? => + target.Length != 0 && (target[0]?.Equals(value) ?? (object?)value is null); + +#endif + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X + + /// + /// Determines whether a read-only character span begins with a specified value when compared using a specified value. + /// + /// The source span. + /// The sequence to compare to the beginning of the source span. + /// An enumeration value that determines how span and value are compared. + /// true if value matches the beginning of span; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.startswith#system-memoryextensions-startswith-1(system-readonlyspan((-0))-system-readonlyspan((-0))) + public static bool StartsWith( + this ReadOnlySpan target, + string other, + StringComparison comparison = StringComparison.CurrentCulture) => + target.StartsWith(other.AsSpan(), comparison); + + /// + /// Determines whether a specified sequence appears at the start of a span. + /// + /// The source span. + /// The sequence to compare to the beginning of the source span. + /// true if value matches the beginning of span; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.startswith#system-memoryextensions-startswith-1(system-span((-0))-system-readonlyspan((-0))) + public static bool StartsWith( + this Span target, + string other) => + target.StartsWith(other.AsSpan()); + +#endif + +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecond.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecond.cs new file mode 100644 index 000000000..ae2af28a2 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecond.cs @@ -0,0 +1,121 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; + +static partial class Polyfill +{ + +#if NET7_0_OR_GREATER + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.nanoseconds + public static int Nanoseconds(this TimeSpan target) => + target.Nanoseconds; + + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.nanosecond + public static int Nanosecond(this DateTime target) => + target.Nanosecond; + + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.nanosecond + public static int Nanosecond(this DateTimeOffset target) => + target.Nanosecond; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.microsecond + public static int Microseconds(this TimeSpan target) => + target.Microseconds; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.microsecond + public static int Microsecond(this DateTime target) => + target.Microsecond; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.microsecond + public static int Microsecond(this DateTimeOffset target) => + target.Microsecond; + +#else + + const long TicksPerMicrosecond = TimeSpan.TicksPerMillisecond * 1000; + + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.nanoseconds + public static int Nanoseconds(this TimeSpan target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 100; + + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.nanosecond + public static int Nanosecond(this DateTime target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 100; + + /// + /// Gets the nanosecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.nanosecond + public static int Nanosecond(this DateTimeOffset target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 100; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.microseconds + public static int Microseconds(this TimeSpan target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 1000; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.microsecond + public static int Microsecond(this DateTime target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 1000; + + /// + /// Gets the microsecond component of the time represented by the current object. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.microsecond + public static int Microsecond(this DateTimeOffset target) => + (int) (target.TicksComponent() % TicksPerMicrosecond) * 1000; + + static long TicksComponent(this TimeSpan target) + { + var noSeconds = new TimeSpan(target.Days, target.Hours, target.Minutes, 0); + var secondsPart = target - noSeconds; + return secondsPart.Ticks; + } + + static long TicksComponent(this DateTime target) + { + var noSeconds = new DateTime(target.Year, target.Month, target.Day, target.Hour, target.Minute, 0, target.Kind); + var secondsPart = target - noSeconds; + return secondsPart.Ticks; + } + + static long TicksComponent(this DateTimeOffset target) + { + var noSeconds = new DateTimeOffset(target.Year, target.Month, target.Day, target.Hour, target.Minute, 0, target.Offset); + var secondsPart = target - noSeconds; + return secondsPart.Ticks; + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecondAdd.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecondAdd.cs new file mode 100644 index 000000000..a3d638cac --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_MicroNanosecondAdd.cs @@ -0,0 +1,27 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; + +static partial class Polyfill +{ +#if !NET7_0_OR_GREATER + + /// + /// Returns a new object that adds a specified number of microseconds to the value of this instance.. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.addmicroseconds + public static DateTime AddMicroseconds(this DateTime target, double microseconds) => + target.AddMilliseconds(microseconds / 1000); + + /// + /// Returns a new object that adds a specified number of microseconds to the value of this instance.. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.addmicroseconds + public static DateTimeOffset AddMicroseconds(this DateTimeOffset target, double microseconds) => + target.AddMilliseconds(microseconds / 1000); + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Process.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Process.cs new file mode 100644 index 000000000..e1888abb6 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Process.cs @@ -0,0 +1,117 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + /// + /// Instructs the Process component to wait for the associated process to exit, or + /// for the to be canceled. + /// + /// + /// Calling this method will set to . + /// + /// + /// A task that will complete when the process has exited, cancellation has been requested, + /// or an error occurs. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexitasync + public static async Task WaitForExitAsync(this Process target, CancellationToken cancellationToken = default) + { + // Because the process has already started by the time this method is called, + // we're in a race against the process to set up our exit handlers before the process + // exits. As a result, there are several different flows that must be handled: + // + // CASE 1: WE ENABLE EVENTS + // This is the "happy path". In this case we enable events. + // + // CASE 1.1: PROCESS EXITS OR IS CANCELED AFTER REGISTERING HANDLER + // This case continues the "happy path". The process exits or waiting is canceled after + // registering the handler and no special cases are needed. + // + // CASE 1.2: PROCESS EXITS BEFORE REGISTERING HANDLER + // It's possible that the process can exit after we enable events but before we register + // the handler. In that case we must check for exit after registering the handler. + // + // + // CASE 2: PROCESS EXITS BEFORE ENABLING EVENTS + // The process may exit before we attempt to enable events. In that case EnableRaisingEvents + // will throw an exception like this: + // System.InvalidOperationException : Cannot process request because the process (42) has exited. + // In this case we catch the InvalidOperationException. If the process has exited, our work + // is done and we return. If for any reason (now or in the future) enabling events fails + // and the process has not exited, bubble the exception up to the user. + // + // + // CASE 3: USER ALREADY ENABLED EVENTS + // In this case the user has already enabled raising events. Re-enabling events is a no-op + // as the value hasn't changed. However, no-op also means that if the process has already + // exited, EnableRaisingEvents won't throw an exception. + // + // CASE 3.1: PROCESS EXITS OR IS CANCELED AFTER REGISTERING HANDLER + // (See CASE 1.1) + // + // CASE 3.2: PROCESS EXITS BEFORE REGISTERING HANDLER + // (See CASE 1.2) + + if (!target.HasExited) + { + // Early out for cancellation before doing more expensive work + cancellationToken.ThrowIfCancellationRequested(); + } + + try + { + // CASE 1: We enable events + // CASE 2: Process exits before enabling events (and throws an exception) + // CASE 3: User already enabled events (no-op) + target.EnableRaisingEvents = true; + } + catch (InvalidOperationException) + { + // CASE 2: If the process has exited, our work is done, otherwise bubble the + // exception up to the user + if (target.HasExited) + { + return; + } + + throw; + } + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + EventHandler handler = (_, _) => tcs.TrySetResult(null); + target.Exited += handler; + + try + { + if (target.HasExited) + { + // CASE 1.2 & CASE 3.2: Handle race where the process exits before registering the handler + } + else + { + // CASE 1.1 & CASE 3.1: Process exits or is canceled here + using (cancellationToken.UnsafeRegister(static (s, cancellationToken) => ((TaskCompletionSource)s!).TrySetCanceled(cancellationToken), tcs)) + { + await tcs.Task.ConfigureAwait(false); + } + } + } + finally + { + target.Exited -= handler; + } + } +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Random.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Random.cs new file mode 100644 index 000000000..1a3445c28 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Random.cs @@ -0,0 +1,89 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; + +static partial class Polyfill +{ +#if (NETSTANDARD || NETFRAMEWORK || NETCOREAPP2_0) && FeatureMemory + /// + /// Fills the elements of a specified span of bytes with random numbers. + /// + /// The array to be filled with random numbers. + /// Each element of the span of bytes is set to a random number greater than or equal to 0 and less than or equal to . + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes#system-random-nextbytes(system-span((system-byte))) + public static void NextBytes( + this Random target, + Span buffer) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + } +#endif + +#if !NET8_0_OR_GREATER + + /// + /// Performs an in-place shuffle of an array. + /// + /// The array to shuffle. + /// The type of array. + /// + /// This method uses to choose values for shuffling. + /// This method is an O(n) operation. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes#system-random-nextbytes(system-span((system-byte))) + public static void Shuffle( + this Random target, + T[] values) + { + int n = values.Length; + + for (int i = 0; i < n - 1; i++) + { + int j = target.Next(i, n); + + if (j != i) + { + T temp = values[i]; + values[i] = values[j]; + values[j] = temp; + } + } + } +#if FeatureMemory + + /// + /// Performs an in-place shuffle of a span. + /// + /// The span to shuffle. + /// The type of span. + /// + /// This method uses to choose values for shuffling. + /// This method is an O(n) operation. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes#system-random-nextbytes(system-span((system-byte))) + public static void Shuffle( + this Random target, + Span values) + { + int n = values.Length; + + for (int i = 0; i < n - 1; i++) + { + int j = target.Next(i, n); + + if (j != i) + { + T temp = values[i]; + values[i] = values[j]; + values[j] = temp; + } + } + } +#endif +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_SortedList.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_SortedList.cs new file mode 100644 index 000000000..63feb9e8e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_SortedList.cs @@ -0,0 +1,34 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Collections.Generic; + +static partial class Polyfill +{ + /// + /// Gets the key corresponding to the specified index. + /// + /// The zero-based index of the key within the entire . + /// The key corresponding to the specified index. + /// The specified index is out of range. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2.getkeyatindex + public static TKey GetKeyAtIndex( + this SortedList target, int index) => + target.Keys[index]; + + /// + /// Gets the value corresponding to the specified index. + /// + /// The zero-based index of the value within the entire . + /// The value corresponding to the specified index. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2.getvalueatindex + public static TValue GetValueAtIndex( + this SortedList target, int index) => + target.Values[index]; +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream.cs new file mode 100644 index 000000000..7bf87f647 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream.cs @@ -0,0 +1,89 @@ +// +#pragma warning disable + +#if (NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0) + +namespace Polyfills; + +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ +#if FeatureMemory && FeatureValueTask + + /// + /// Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by + /// the number of bytes read, and monitors cancellation requests. + /// + /// The region of memory to write the data into. + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// + /// A task that represents the asynchronous read operation. The value of its Result property contains the + /// total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in + /// the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has + /// been reached. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readasync#system-io-stream-readasync(system-memory((system-byte))-system-threading-cancellationtoken) + public static ValueTask ReadAsync( + this Stream target, + Memory buffer, + CancellationToken cancellationToken = default) + { + if (!MemoryMarshal.TryGetArray((ReadOnlyMemory) buffer, out var segment)) + { + segment = new(buffer.ToArray()); + } + + var task = target.ReadAsync(segment.Array!, segment.Offset, segment.Count, cancellationToken); + return new(task); + } + + /// + /// Asynchronously writes a sequence of bytes to the current stream, advances the current position + /// within this stream by the number of bytes written, and monitors cancellation requests. + /// + /// The region of memory to write data from. + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// A task that represents the asynchronous write operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.writeasync#system-io-stream-writeasync(system-readonlymemory((system-byte))-system-threading-cancellationtoken) + public static ValueTask WriteAsync( + this Stream target, + ReadOnlyMemory buffer, + CancellationToken cancellationToken = default) + { + if (!MemoryMarshal.TryGetArray(buffer, out var segment)) + { + segment = new(buffer.ToArray()); + } + + var task = target.WriteAsync(segment.Array!, segment.Offset, segment.Count, cancellationToken); + return new(task); + } + +#endif + + /// + /// Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified + /// cancellation token. Both streams positions are advanced by the number of bytes copied. + /// + /// The stream to which the contents of the current stream will be copied. + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// A task that represents the asynchronous copy operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copytoasync#system-io-stream-copytoasync(system-io-stream-system-threading-cancellationtoken) + public static Task CopyToAsync( + this Stream target, + Stream destination, + CancellationToken cancellationToken = default) => + target.CopyToAsync(destination, 81920, cancellationToken); +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream_DisposeAsync.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream_DisposeAsync.cs new file mode 100644 index 000000000..ea8e87755 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Stream_DisposeAsync.cs @@ -0,0 +1,32 @@ +// +#pragma warning disable + +#if (NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2X) && FeatureValueTask + +namespace Polyfills; + +using System; +using System.IO; +using System.Threading.Tasks; + +static partial class Polyfill +{ + //https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs#L174 + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.disposeasync + public static ValueTask DisposeAsync(this Stream target) + { + try + { + target.Dispose(); + return default; + } + catch (Exception exception) + { + return new ValueTask(Task.FromException(exception)); + } + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_String.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_String.cs new file mode 100644 index 000000000..d3ed6661d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_String.cs @@ -0,0 +1,139 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ +#if FeatureMemory && !NET6_0_OR_GREATER + + /// + /// Copies the contents of this string into the destination span. + /// + /// The span into which to copy this string's contents + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.copyto + public static void CopyTo(this string target, Span destination) => + target.AsSpan().CopyTo(destination); + + /// + /// Copies the contents of this string into the destination span. + /// + /// The span into which to copy this string's contents + /// true if the data was copied; false if the destination was too short to fit the contents of the string. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.trycopyto + public static bool TryCopyTo(this string target, Span destination) => + target.AsSpan().TryCopyTo(destination); +#endif + +#if NETFRAMEWORK || NETSTANDARD2_0 + + /// + /// Returns the hash code for this string using the specified rules. + /// + /// One of the enumeration values that specifies the rules to use in the comparison. + /// A 32-bit signed integer hash code. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.gethashcode#system-string-gethashcode(system-stringcomparison) + public static int GetHashCode(this string target, StringComparison comparisonType) => + FromComparison(comparisonType).GetHashCode(target); + + static StringComparer FromComparison(StringComparison comparison) => + comparison switch + { + StringComparison.CurrentCulture => StringComparer.CurrentCulture, + StringComparison.CurrentCultureIgnoreCase => StringComparer.CurrentCultureIgnoreCase, + StringComparison.InvariantCulture => StringComparer.InvariantCulture, + StringComparison.InvariantCultureIgnoreCase => StringComparer.InvariantCultureIgnoreCase, + StringComparison.Ordinal => StringComparer.Ordinal, + StringComparison.OrdinalIgnoreCase => StringComparer.OrdinalIgnoreCase, + _ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison, null) + }; + + /// + /// Returns a value indicating whether a specified string occurs within this string, using the specified comparison rules. + /// + /// The string to seek. + /// One of the enumeration values that specifies the rules to use in the comparison. + /// true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains#system-string-contains(system-string-system-stringcomparison) + public static bool Contains(this string target, string value, StringComparison comparisonType) => + target.IndexOf(value, comparisonType) >= 0; + + /// + /// Determines whether this string instance starts with the specified character. + /// + /// The character to compare. + /// This method performs an ordinal (case-sensitive and culture-insensitive) comparison. + /// true if value matches the beginning of this string; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains#system-string-contains(system-char) + public static bool StartsWith(this string target, char value) + { + if (target.Length == 0) + { + return false; + } + + return target[0] == value; + } + + /// + /// Returns a value indicating whether a specified character occurs within this string. + /// + /// The character to seek. + /// This method performs an ordinal (case-sensitive and culture-insensitive) comparison. + /// true if the value parameter occurs within this string; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains#system-string-contains(system-char) + public static bool EndsWith(this string target, char value) + { + if (target.Length == 0) + { + return false; + } + + var lastPos = target.Length - 1; + return lastPos < target.Length && + target[lastPos] == value; + } + + /// + /// Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, + /// options. Splits a string into a maximum number of substrings based on the provided character separator, + /// optionally omitting empty substrings from the result. + /// + /// A character that delimits the substrings in this instance. + /// A bitwise combination of the enumeration values that specifies whether to trim substrings + /// and include empty substrings. + /// An array that contains at most count substrings from this instance that are delimited by separator. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.split#system-string-split(system-char-system-stringsplitoptions) + public static string[] Split(this string target, char separator, StringSplitOptions options = StringSplitOptions.None) => + target.Split([separator], options); + + /// + /// Splits a string into a maximum number of substrings based on a specified delimiting character and, optionally, + /// options. Splits a string into a maximum number of substrings based on the provided character separator, + /// optionally omitting empty substrings from the result. + /// + /// A character that delimits the substrings in this instance. + /// The maximum number of elements expected in the array. + /// A bitwise combination of the enumeration values that specifies whether to trim substrings + /// and include empty substrings. + /// An array that contains at most count substrings from this instance that are delimited by separator. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.split#system-string-split(system-char-system-int32-system-stringsplitoptions) + public static string[] Split(this string target, char separator, int count, StringSplitOptions options = StringSplitOptions.None) => + target.Split([separator], count, options); +#endif + +#if NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0 + /// + /// Returns a value indicating whether a specified character occurs within this string. + /// + /// This method performs an ordinal (case-sensitive and culture-insensitive) comparison. + /// The character to seek. + /// true if the value parameter occurs within this string; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains#system-string-contains(system-char) + public static bool Contains(this string target, char value) => + target.IndexOf(value) >= 0; +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder.cs new file mode 100644 index 000000000..6e738f359 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder.cs @@ -0,0 +1,75 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ +#if FeatureMemory && (!NETSTANDARD2_1_OR_GREATER && !NETCOREAPP2_1_OR_GREATER) + + /// + /// Returns a value indicating whether the characters in this instance are equal to the characters in a specified + /// read-only character span. + /// + /// The character span to compare with the current instance. + /// + /// The Equals method performs an ordinal comparison to determine whether the characters in the current instance + /// and span are equal. + /// + /// true if the characters in this instance and span are the same; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.equals#system-text-stringbuilder-equals(system-readonlyspan((system-char))) + public static bool Equals(this StringBuilder target, ReadOnlySpan span) + { + if (target.Length != span.Length) + { + return false; + } + + for (var index = 0; index < target.Length; index++) + { + var ch1 = target[index]; + var ch2 = span[index]; + if (ch1 != ch2) + { + return false; + } + } + + return true; + } + +#endif + +#if !NET9_0_OR_GREATER && FeatureMemory + /// + /// Replaces all instances of one string with another in part of this builder. + /// + /// The string to replace. + /// The string to replace with. + /// The index to start in this builder. + /// The number of characters to read in this builder. + /// + /// If is null, instances of are removed from this builder. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.replace#system-text-stringbuilder-replace(system-readonlyspan((system-char))-system-readonlyspan((system-char))) + public static StringBuilder Replace(this StringBuilder target, ReadOnlySpan oldValue, ReadOnlySpan newValue) => + target.Replace(oldValue.ToString(), newValue.ToString()); + + /// + /// Replaces all instances of one read-only character span with another in part of this builder. + /// + /// The read-only character span to replace. + /// The read-only character span to replace with. + /// The index to start in this builder. + /// The number of characters to read in this builder. + /// + /// If is empty, instances of are removed from this builder. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.replace#system-text-stringbuilder-replace(system-char-system-char-system-int32-system-int32) + public static StringBuilder Replace(this StringBuilder target, ReadOnlySpan oldValue, ReadOnlySpan newValue, int startIndex, int count) => + target.Replace(oldValue.ToString(), newValue.ToString(), startIndex, count); +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_Append.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_Append.cs new file mode 100644 index 000000000..91bc79873 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_Append.cs @@ -0,0 +1,87 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Text; + +static partial class Polyfill +{ +#if FeatureMemory && (!NETSTANDARD2_1_OR_GREATER && !NETCOREAPP2_1_OR_GREATER) + + /// + /// Appends the string representation of a specified read-only character span to this instance. + /// + /// The read-only character span to append. + /// A reference to this instance after the append operation is completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append#system-text-stringbuilder-append(system-readonlyspan((system-char))) + public static StringBuilder Append(this StringBuilder target, ReadOnlySpan value) + { + if (value.Length <= 0) + { + return target; + } + +#if AllowUnsafeBlocks + unsafe + { + fixed (char* valueChars = value) + { + target.Append(valueChars, value.Length); + } + } +#else + target.Append(value.ToString()); +#endif + return target; + } + +#endif + +#if FeatureMemory && !NET6_0_OR_GREATER + /// Appends the specified interpolated string to this instance. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append#system-text-stringbuilder-append(system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder Append( + StringBuilder target, + [InterpolatedStringHandlerArgument(nameof(target))] + ref AppendInterpolatedStringHandler handler) => target; + + /// Appends the specified interpolated string to this instance. + /// An object that supplies culture-specific formatting information. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append#system-text-stringbuilder-append(system-iformatprovider-system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder Append( + StringBuilder target, + IFormatProvider? provider, + [InterpolatedStringHandlerArgument(nameof(target), nameof(provider))] + ref AppendInterpolatedStringHandler handler) => target; + +#elif NET6_0_OR_GREATER + + /// Appends the specified interpolated string to this instance. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append#system-text-stringbuilder-append(system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder Append( + StringBuilder target, + [InterpolatedStringHandlerArgument(nameof(target))] ref StringBuilder.AppendInterpolatedStringHandler handler) => + target.Append(ref handler); + + /// Appends the specified interpolated string to this instance. + /// An object that supplies culture-specific formatting information. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append#system-text-stringbuilder-append(system-iformatprovider-system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder Append( + StringBuilder target, + IFormatProvider? provider, + [InterpolatedStringHandlerArgument(nameof(target), nameof(provider))] ref StringBuilder.AppendInterpolatedStringHandler handler) => + target.Append(provider, ref handler); + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendJoin.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendJoin.cs new file mode 100644 index 000000000..6357535b0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendJoin.cs @@ -0,0 +1,81 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ + +#if NETSTANDARD2_0|| NETFRAMEWORK + + /// Concatenates the strings of the provided array, using the specified separator between each string, then appends the result to the current instance of the string builder. + /// The string to use as a separator. separator is included in the joined strings only if values has more than one element. + /// An array that contains the strings to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin(system-string-system-string()) + public static StringBuilder AppendJoin( + this StringBuilder target, + string separator, + params string[] values) => + target.Append(string.Join(separator, values)); + + /// Concatenates the string representations of the elements in the provided array of objects, using the specified separator between each member, then appends the result to the current instance of the string builder. + /// The string to use as a separator. separator is included in the joined strings only if values has more than one element. + /// An array that contains the strings to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin(system-string-system-object()) + public static StringBuilder AppendJoin( + this StringBuilder target, + string separator, + params Object[] values) => + target.Append(string.Join(separator, values)); + + /// Concatenates the strings of the provided array, using the specified char separator between each string, then appends the result to the current instance of the string builder. + /// The character to use as a separator. separator is included in the joined strings only if values has more than one element. + /// An array that contains the strings to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin(system-char-system-string()) + public static StringBuilder AppendJoin( + this StringBuilder target, + char separator, + params string[] values) => + target.Append(string.Join(separator.ToString(), values)); + + /// Concatenates the string representations of the elements in the provided array of objects, using the specified char separator between each member, then appends the result to the current instance of the string builder. + /// The character to use as a separator. separator is included in the joined strings only if values has more than one element. + /// An array that contains the strings to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin(system-char-system-object()) + public static StringBuilder AppendJoin( + this StringBuilder target, + char separator, + params object[] values) => + target.Append(string.Join(separator.ToString(), values)); + + /// Concatenates and appends the members of a collection, using the specified char separator between each member. + /// The character to use as a separator. separator is included in the joined strings only if values has more than one element. + /// A collection that contains the objects to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin-1(system-char-system-collections-generic-ienumerable((-0))) + public static StringBuilder AppendJoin( + this StringBuilder target, + char separator, + params T[] values) => + target.Append(string.Join(separator.ToString(), values)); + + /// Concatenates and appends the members of a collection, using the specified char separator between each member. + /// The string to use as a separator. separator is included in the concatenated and appended strings only if values has more than one element. + /// A collection that contains the objects to concatenate and append to the current instance of the string builder. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendjoin#system-text-stringbuilder-appendjoin-1(system-string-system-collections-generic-ienumerable((-0))) + public static StringBuilder AppendJoin( + this StringBuilder target, + string separator, + params T[] values) => + target.Append(string.Join(separator.ToString(), values)); + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendLine.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendLine.cs new file mode 100644 index 000000000..6c7af828d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_AppendLine.cs @@ -0,0 +1,59 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Runtime.CompilerServices; +using System.Text; + +static partial class Polyfill +{ +#if FeatureMemory && !NET6_0_OR_GREATER + + /// Appends the specified interpolated string followed by the default line terminator to the end of the current StringBuilder object. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendline#system-text-stringbuilder-appendline(system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder AppendLine( + StringBuilder target, + [InterpolatedStringHandlerArgument(nameof(target))] + ref AppendInterpolatedStringHandler handler) => + target.AppendLine(); + + /// Appends the specified interpolated string followed by the default line terminator to the end of the current StringBuilder object. + /// An object that supplies culture-specific formatting information. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendline#system-text-stringbuilder-appendline(system-iformatprovider-system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder AppendLine( + StringBuilder target, + IFormatProvider? provider, + [InterpolatedStringHandlerArgument(nameof(target), nameof(provider))] + ref AppendInterpolatedStringHandler handler) => + target.AppendLine(); + +#elif NET6_0_OR_GREATER + + /// Appends the specified interpolated string followed by the default line terminator to the end of the current StringBuilder object. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendline#system-text-stringbuilder-appendline(system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder AppendLine( + StringBuilder target, + [InterpolatedStringHandlerArgument(nameof(target))] ref StringBuilder.AppendInterpolatedStringHandler handler) => + target.AppendLine(ref handler); + + /// Appends the specified interpolated string followed by the default line terminator to the end of the current StringBuilder object. + /// An object that supplies culture-specific formatting information. + /// The interpolated string to append. + /// A reference to this instance after the append operation has completed. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendline#system-text-stringbuilder-appendline(system-iformatprovider-system-text-stringbuilder-appendinterpolatedstringhandler@) + public static StringBuilder AppendLine( + StringBuilder target, + IFormatProvider? provider, + [InterpolatedStringHandlerArgument(nameof(target), nameof(provider))] ref StringBuilder.AppendInterpolatedStringHandler handler) => + target.AppendLine(provider, ref handler); +#endif + +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_CopyTo.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_CopyTo.cs new file mode 100644 index 000000000..94579c619 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_CopyTo.cs @@ -0,0 +1,46 @@ +// +#pragma warning disable + +#if FeatureMemory && (!NETSTANDARD2_1_OR_GREATER && !NETCOREAPP2_1_OR_GREATER) + +namespace Polyfills; + +using System; +using System.Text; + +static partial class Polyfill +{ + /// + /// Copies the characters from a specified segment of this instance to a destination Char span. + /// + /// The starting position in this instance where characters will be copied from. The index is zero-based. + /// The writable span where characters will be copied. + /// The number of characters to be copied. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.copyto#system-text-stringbuilder-copyto(system-int32-system-span((system-char))-system-int32) + public static void CopyTo( + this StringBuilder target, + int sourceIndex, + Span destination, + int count) + { + var destinationIndex = 0; + while (true) + { + if (sourceIndex == target.Length) + { + break; + } + + if (destinationIndex == count) + { + break; + } + + destination[destinationIndex] = target[sourceIndex]; + destinationIndex++; + sourceIndex++; + } + } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_GetChunks.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_GetChunks.cs new file mode 100644 index 000000000..5ccd3cac0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_StringBuilder_GetChunks.cs @@ -0,0 +1,209 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER && FeatureMemory + +namespace Polyfills; + +using System; +using System.ComponentModel; +using System.Reflection; +using System.Text; + +static partial class Polyfill +{ + static FieldInfo chunkCharsField = GetStringBuilderField("m_ChunkChars"); + static FieldInfo chunkPreviousField = GetStringBuilderField("m_ChunkPrevious"); + static FieldInfo chunkLengthField = GetStringBuilderField("m_ChunkLength"); + + static FieldInfo GetStringBuilderField(string name) + { + var field = typeof(StringBuilder).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); + if (field != null) + { + return field; + } + + throw new($"Expected to find field '{name}' on StringBuilder"); + } + + static int GetChunkLength(StringBuilder stringBuilder) => + (int) chunkLengthField.GetValue(stringBuilder)!; + + static char[] GetChunkChars(StringBuilder stringBuilder) => + (char[]) chunkCharsField.GetValue(stringBuilder)!; + + static StringBuilder? GetChunkPrevious(StringBuilder stringBuilder) => + (StringBuilder?) chunkPreviousField.GetValue(stringBuilder); + + /// + /// GetChunks returns ChunkEnumerator that follows the IEnumerable pattern and + /// thus can be used in a C# 'foreach' statements to retrieve the data in the StringBuilder + /// as chunks (ReadOnlyMemory) of characters. An example use is: + /// + /// foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) + /// foreach (char c in chunk.Span) + /// { /* operation on c } + /// + /// It is undefined what happens if the StringBuilder is modified while the chunk + /// enumeration is incomplete. StringBuilder is also not thread-safe, so operating + /// on it with concurrent threads is illegal. Finally the ReadOnlyMemory chunks returned + /// are NOT guaranteed to remain unchanged if the StringBuilder is modified, so do + /// not cache them for later use either. This API's purpose is efficiently extracting + /// the data of a CONSTANT StringBuilder. + /// + /// Creating a ReadOnlySpan from a ReadOnlyMemory (the .Span property) is expensive + /// compared to the fetching of the character, so create a local variable for the SPAN + /// if you need to use it in a nested for statement. For example + /// + /// foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) + /// { + /// var span = chunk.Span; + /// for (int i = 0; i < span.Length; i++) + /// { /* operation on span[i] */ } + /// } + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.getchunks + public static ChunkEnumerator GetChunks(this StringBuilder target) => + new(target); + + /// + /// ChunkEnumerator supports both the IEnumerable and IEnumerator pattern so foreach + /// works (see GetChunks). It needs to be public (so the compiler can use it + /// when building a foreach statement) but users typically don't use it explicitly. + /// (which is why it is a nested type). + /// + public struct ChunkEnumerator + { + // The first Stringbuilder chunk (which is the end of the logical string) + StringBuilder _firstChunk; + + // The chunk that this enumerator is currently returning (Current). + StringBuilder? _currentChunk; + + // Only used for long string builders with many chunks (see constructor) + ManyChunkInfo? _manyChunks; + + // Only here to make foreach work + /// + /// Implement IEnumerable.GetEnumerator() to return 'this' as the IEnumerator + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public ChunkEnumerator GetEnumerator() => + this; + + /// + /// Implements the IEnumerator pattern. + /// + public bool MoveNext() + { + if (_currentChunk == _firstChunk) + { + return false; + } + + if (_manyChunks != null) + { + return _manyChunks.MoveNext(ref _currentChunk); + } + + var next = _firstChunk; + while (true) + { + var chunkPrevious = GetChunkPrevious(next); + if (chunkPrevious == _currentChunk) + { + break; + } + + next = chunkPrevious; + } + + _currentChunk = next; + return true; + } + + /// + /// Implements the IEnumerator pattern. + /// + public ReadOnlyMemory Current + { + get + { + if (_currentChunk == null) + { + throw new InvalidOperationException("Enumeration operation cant happen"); + } + + return new ReadOnlyMemory(GetChunkChars(_currentChunk), 0, GetChunkLength(_currentChunk)); + } + } + + internal ChunkEnumerator(StringBuilder builder) + { + _firstChunk = builder; + // MoveNext will find the last chunk if we do this. + _currentChunk = null; + _manyChunks = null; + + // There is a performance-vs-allocation tradeoff. Because the chunks + // are a linked list with each chunk pointing to its PREDECESSOR, walking + // the list FORWARD is not efficient. If there are few chunks (< 8) we + // simply scan from the start each time, and tolerate the N*N behavior. + // However above this size, we allocate an array to hold reference to all + // the chunks and we can be efficient for large N. + var chunkCount = ChunkCount(builder); + if (8 < chunkCount) + { + _manyChunks = new ManyChunkInfo(builder, chunkCount); + } + } + + static int ChunkCount(StringBuilder? builder) + { + var ret = 0; + while (builder != null) + { + ret++; + builder = GetChunkPrevious(builder); + } + + return ret; + } + + /// + /// Used to hold all the chunks indexes when you have many chunks. + /// + class ManyChunkInfo + { + // These are in normal order (first chunk first) + StringBuilder[] _chunks; + int _chunkPos; + + public bool MoveNext(ref StringBuilder? current) + { + int pos = ++_chunkPos; + if (_chunks.Length <= pos) + { + return false; + } + + current = _chunks[pos]; + return true; + } + + public ManyChunkInfo(StringBuilder? builder, int chunkCount) + { + _chunks = new StringBuilder[chunkCount]; + while (0 <= --chunkCount) + { + _chunks[chunkCount] = builder; + builder = GetChunkPrevious(builder); + } + + _chunkPos = -1; + } + } + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Task.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Task.cs new file mode 100644 index 000000000..8903335a1 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Task.cs @@ -0,0 +1,127 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPPX || NET5_0 + +namespace Polyfills; + +using System; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + // Copied from .NET library const Timer.MaxSupportedTimeout + const uint MaxSupportedTimeout = 0xfffffffe; + + /// Gets a that will complete when this completes or when the specified has cancellation requested. + /// The to monitor for a cancellation request. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync#system-threading-tasks-task-waitasync(system-threading-cancellationtoken) + public static Task WaitAsync(this Task target, CancellationToken cancellationToken) => + target.WaitAsync(Timeout.InfiniteTimeSpan, cancellationToken); + + /// Gets a that will complete when this completes or when the specified timeout expires. + /// The timeout after which the should be faulted with a if it hasn't otherwise completed. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync#system-threading-tasks-task-waitasync(system-timespan) + public static Task WaitAsync( + this Task target, + TimeSpan timeout) => + target.WaitAsync(timeout, default); + + /// Gets a that will complete when this completes, when the specified timeout expires, or when the specified has cancellation requested. + /// The timeout after which the should be faulted with a if it hasn't otherwise completed. + /// The to monitor for a cancellation request. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync#system-threading-tasks-task-waitasync(system-timespan-system-threading-cancellationtoken) + public static Task WaitAsync( + this Task target, + TimeSpan timeout, + CancellationToken cancellationToken) + { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + + long totalMilliseconds = (long) timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > MaxSupportedTimeout) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + if (target.IsCompleted || (!cancellationToken.CanBeCanceled && timeout == Timeout.InfiniteTimeSpan)) + { + return target; + } + + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + + if (timeout == TimeSpan.Zero) + { + return Task.FromException(new TimeoutException()); + } + + var delayTask = Task.Delay(timeout, cancellationToken); + + Func, Task> continueFunc = completedTask => + { + if (cancellationToken.IsCancellationRequested) + { + throw new TaskCanceledException(); + } + else if (completedTask.Result == delayTask) + { + throw new TimeoutException($"Execution did not complete within the time allotted {timeout.TotalMilliseconds} ms"); + } + + return target; + }; + + return Task.WhenAny(target, delayTask).ContinueWith(continueFunc, TaskContinuationOptions.OnlyOnRanToCompletion); + } + + /// + /// Gets a that will complete when this completes, or when the specified has cancellation requested. + /// + /// The to monitor for a cancellation request. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitasync#system-threading-tasks-task-waitasync(system-threading-cancellationtoken) + public static Task WaitAsync( + this Task target, + CancellationToken cancellationToken) => + target.WaitAsync(Timeout.InfiniteTimeSpan, cancellationToken); + + /// + /// Gets a that will complete when this completes, or when the specified timeout expires. + /// + /// The timeout after which the should be faulted with a if it hasn't otherwise completed. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.waitasync#system-threading-tasks-task-1-waitasync(system-timespan) + public static Task WaitAsync( + this Task target, + TimeSpan timeout) => + target.WaitAsync(timeout, default); + + /// + /// Gets a that will complete when this completes, when the specified timeout expires, or when the specified has cancellation requested. + /// + /// The timeout after which the should be faulted with a if it hasn't otherwise completed. + /// The to monitor for a cancellation request. + /// The representing the asynchronous wait. It may or may not be the same instance as the current instance. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.waitasync#system-threading-tasks-task-1-waitasync(system-timespan-system-threading-cancellationtoken) + public static async Task WaitAsync( + this Task target, + TimeSpan timeout, + CancellationToken cancellationToken) + { + await ((Task) target).WaitAsync(timeout, cancellationToken); + return target.Result; + } +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TaskCompletionSource.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TaskCompletionSource.cs new file mode 100644 index 000000000..0886015fa --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TaskCompletionSource.cs @@ -0,0 +1,38 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace Polyfills; + +using System; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ + /// + /// Transitions the underlying into the state + /// using the specified token. + /// + /// The cancellation token with which to cancel the . + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1.setcanceled#system-threading-tasks-taskcompletionsource-1-setcanceled(system-threading-cancellationtoken) + public static void SetCanceled( + this TaskCompletionSource target, + CancellationToken cancellationToken) + { + if (target.TrySetCanceled(cancellationToken)) + { + return; + } + + throw new InvalidOperationException("An attempt was made to transition a task to a final state when it had already completed."); + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextReader.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextReader.cs new file mode 100644 index 000000000..f72d88c1e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextReader.cs @@ -0,0 +1,91 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +static partial class Polyfill +{ +#if FeatureValueTask && FeatureMemory && (NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0) + /// + /// Asynchronously reads the characters from the current stream into a memory block. + /// + /// + /// When this method returns, contains the specified memory block of characters replaced by the characters read + /// from the current source. + /// + /// + /// The token to monitor for cancellation requests. The default value is . + /// + /// + /// A value task that represents the asynchronous read operation. The value of the type parameter of the value task + /// contains the number of characters that have been read, or 0 if at the end of the stream and no data was read. + /// The number will be less than or equal to the length, depending on whether the data is + /// available within the stream. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textreader.readasync#system-io-textreader-readasync(system-memory((system-char))-system-threading-cancellationtoken) + public static ValueTask ReadAsync( + this TextReader target, + Memory buffer, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (!MemoryMarshal.TryGetArray((ReadOnlyMemory)buffer, out var segment)) + { + segment = new(buffer.ToArray()); + } + + var task = target.ReadAsync(segment.Array!, segment.Offset, segment.Count) + .WaitAsync(cancellationToken); + return new(task); + } +#endif + +#if !NET7_0_OR_GREATER + /// + /// Reads all characters from the current position to the end of the stream asynchronously and returns them as one string. + /// + /// The token to monitor for cancellation requests. + /// A task that represents the asynchronous read operation. The value of the TResult parameter contains + /// a string with the characters from the current position to the end of the stream. + /// The number of characters is larger than . + /// The stream reader has been disposed. + /// The reader is currently in use by a previous read operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textreader.readtoendasync#system-io-textreader-readtoendasync(system-threading-cancellationtoken) + public static Task ReadToEndAsync( + this TextReader target, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + return target.ReadToEndAsync() + .WaitAsync(cancellationToken); + } + + /// + /// Reads a line of characters asynchronously and returns the data as a string. + /// + /// The token to monitor for cancellation requests. + /// A value task that represents the asynchronous read operation. The value of the TResult + /// parameter contains the next line from the text reader, or is if all of the characters have been read. + /// The number of characters in the next line is larger than . + /// The text reader has been disposed. + /// The reader is currently in use by a previous read operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textreader.readtoendasync#system-io-textreader-readlineasync(system-threading-cancellationtoken) + public static Task ReadLineAsync( + this TextReader target, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + return target.ReadLineAsync() + .WaitAsync(cancellationToken); + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextWriter.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextWriter.cs new file mode 100644 index 000000000..83fd20b98 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TextWriter.cs @@ -0,0 +1,211 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Text; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +#if FeatureMemory +using System.Buffers; +#endif + +static partial class Polyfill +{ +#if !NET8_0_OR_GREATER + + //https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs#L670 + + /// + /// Asynchronously clears all buffers for the current writer and causes any buffered data to + /// be written to the underlying device. + /// + /// The to monitor for cancellation requests. + /// A that represents the asynchronous flush operation. + /// The text writer is disposed. + /// The writer is currently in use by a previous write operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.flushasync#system-io-textwriter-flushasync(system-threading-cancellationtoken) + public static Task FlushAsync(this TextWriter target, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + + return target.FlushAsync() + .WaitAsync(cancellationToken); + } + +#endif + +#if !NETCOREAPP3_0_OR_GREATER + /// + /// Equivalent to Write(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + /// The string (as a StringBuilder) to write to the stream + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.write#system-io-textwriter-write(system-text-stringbuilder) + public static void Write(this TextWriter target, StringBuilder? value) + { + if (value == null) + { + return; + } + +#if FeatureMemory + foreach (ReadOnlyMemory chunk in value.GetChunks()) + { + target.Write(chunk.Span); + } +#else + target.Write(value.ToString()); +#endif + } + + /// + /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the + /// StringBuilder.GetChunks() method to avoid creating the intermediate string + /// + /// The string (as a StringBuilder) to write to the stream + /// The token to monitor for cancellation requests. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.writeasync#system-io-textwriter-writeasync(system-readonlymemory((system-char))-system-threading-cancellationtoken) + public static Task WriteAsync(this TextWriter target, StringBuilder? value, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + + if (value == null) + { + return Task.CompletedTask; + } + + return WriteAsyncCore(value, cancellationToken); + + async Task WriteAsyncCore(StringBuilder builder, CancellationToken cancel) + { +#if FeatureValueTask && FeatureMemory + foreach (ReadOnlyMemory chunk in builder.GetChunks()) + { + await target.WriteAsync(chunk, cancel).ConfigureAwait(false); + } +#else + await target.WriteAsync(builder.ToString()) + .WaitAsync(cancellationToken); +#endif + } + } +#endif + +#if (NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0) && FeatureMemory +#if FeatureValueTask + + /// + /// Asynchronously writes a character memory region to the stream. + /// + /// The character memory region to write to the stream. + /// + /// The token to monitor for cancellation requests. + /// The default value is . + /// + /// A task that represents the asynchronous write operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.writeasync#system-io-textwriter-writeasync(system-readonlymemory((system-char))-system-threading-cancellationtoken) + public static ValueTask WriteAsync( + this TextWriter target, + ReadOnlyMemory buffer, + CancellationToken cancellationToken = default) + { + // StreamReader doesn't accept cancellation token (pre-netstd2.1) + cancellationToken.ThrowIfCancellationRequested(); + + if (!MemoryMarshal.TryGetArray(buffer, out var segment)) + { + segment = new(buffer.ToArray()); + } + + var task = target.WriteAsync(segment.Array!, segment.Offset, segment.Count) + .WaitAsync(cancellationToken); + return new(task); + } + + /// + /// Asynchronously writes the text representation of a character memory region to the stream, followed by a line terminator. + /// + /// The character memory region to write to the stream. + /// + /// The token to monitor for cancellation requests. + /// The default value is . + /// + /// A task that represents the asynchronous write operation. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.writelineasync#system-io-textwriter-writelineasync(system-readonlymemory((system-char))-system-threading-cancellationtoken) + public static ValueTask WriteLineAsync( + this TextWriter target, + ReadOnlyMemory buffer, + CancellationToken cancellationToken = default) + { + // StreamReader doesn't accept cancellation token (pre-netstd2.1) + cancellationToken.ThrowIfCancellationRequested(); + + if (!MemoryMarshal.TryGetArray(buffer, out var segment)) + { + segment = new(buffer.ToArray()); + } + + var task = target.WriteLineAsync(segment.Array!, segment.Offset, segment.Count) + .WaitAsync(cancellationToken); + return new(task); + } + +#endif + + /// + /// Writes a character span to the text stream. + /// + /// The character span to write. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.write#system-io-textwriter-write(system-readonlyspan((system-char))) + public static void Write( + this TextWriter target, + ReadOnlySpan buffer) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(buffer.Length); + + try + { + buffer.CopyTo(new(array)); + target.Write(array, 0, buffer.Length); + } + finally + { + pool.Return(array); + } + } + + /// + /// Writes the text representation of a character span to the text stream, followed by a line terminator. + /// + /// The char span value to write to the text stream. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.writeline#system-io-textwriter-writeline(system-readonlyspan((system-char))) + public static void WriteLine( + this TextWriter target, + ReadOnlySpan buffer) + { + var pool = ArrayPool.Shared; + var array = pool.Rent(buffer.Length); + + try + { + buffer.CopyTo(new(array)); + target.WriteLine(array, 0, buffer.Length); + } + finally + { + pool.Return(array); + } + } +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToByteSpan.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToByteSpan.cs new file mode 100644 index 000000000..693a81e59 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToByteSpan.cs @@ -0,0 +1,381 @@ +// + +#pragma warning disable + +#if FeatureMemory +namespace Polyfills; + +using System.Text; +using System; +using System.Diagnostics.CodeAnalysis; + +static partial class Polyfill +{ +#if !NET8_0_OR_GREATER + + static bool CopyToSpan(Span destination, out int bytesWritten, string result) + { + if (result.Length == 0) + { + bytesWritten = 0; + return true; + } + + var bytes = Encoding.UTF8.GetBytes(result); + + if (bytes.Length > destination.Length) + { + bytesWritten = 0; + return false; + } + + bytes.CopyTo(destination); + bytesWritten = bytes.Length; + return true; + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.tryformat#system-timespan-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this TimeSpan target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.TimeSpanFormat)] ReadOnlySpan format = default, IFormatProvider? formatProvider = null) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(null, formatProvider); + } + else + { + result = target.ToString(format.ToString(), formatProvider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat#system-guid-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))) + public static bool TryFormat(this Guid target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.GuidFormat)] ReadOnlySpan format = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(null); + } + else + { + result = target.ToString(format.ToString()); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat#system-sbyte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this sbyte target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat#system-byte-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this byte target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat#system-int16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this short target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat#system-uint16-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this ushort target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat#system-int32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this int target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat#system-uint32-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this uint target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat#system-int64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this long target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat#system-uint64-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this ulong target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat#system-single-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this float target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat#system-double-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this double target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat#system-decimal-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this decimal target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat#system-datetimeoffset-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateTimeOffset target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat#system-datetime-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateTime target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.DateOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + +#endif +#if NET6_0 || NET7_0 + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.dateonly.tryformat#system-dateonly-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateOnly target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.DateOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timeonly.tryformat#system-timeonly-tryformat(system-span((system-byte))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this TimeOnly target, Span utf8Destination, out int bytesWritten, [StringSyntax(StringSyntaxAttribute.TimeOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(utf8Destination, out bytesWritten, result); + } +#endif +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToCharSpan.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToCharSpan.cs new file mode 100644 index 000000000..631e3dfec --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_TryFormatToCharSpan.cs @@ -0,0 +1,389 @@ +// + +#pragma warning disable + +#if FeatureMemory +namespace Polyfills; + +using System; +using System.Diagnostics.CodeAnalysis; + +static partial class Polyfill +{ + static bool CopyToSpan(Span destination, out int charsWritten, string result) + { + if (result.Length == 0) + { + charsWritten = 0; + return true; + } + + if (result.Length > destination.Length) + { + charsWritten = 0; + return false; + } + + charsWritten = result.Length; + return result.TryCopyTo(destination); + } + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.tryformat#system-timespan-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this TimeSpan target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.TimeSpanFormat)] ReadOnlySpan format = default, IFormatProvider? formatProvider = null) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(null, formatProvider); + } + else + { + result = target.ToString(format.ToString(), formatProvider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat#system-guid-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))) + public static bool TryFormat(this Guid target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.GuidFormat)] ReadOnlySpan format = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(null); + } + else + { + result = target.ToString(format.ToString()); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.tryformat#system-sbyte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this sbyte target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.byte.tryformat#system-byte-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this byte target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int16.tryformat#system-int16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this short target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint16.tryformat#system-uint16-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this ushort target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryformat#system-int32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this int target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tryformat#system-uint32-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this uint target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryformat#system-int64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this long target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tryformat#system-uint64-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this ulong target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.single.tryformat#system-single-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this float target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryformat#system-double-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this double target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.decimal.tryformat#system-decimal-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this decimal target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.NumericFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.boolean.tryformat + public static bool TryFormat(this bool target, Span destination, out int charsWritten) + { + var result = target.ToString(); + return CopyToSpan(destination, out charsWritten, result); + } +#endif + +#if (NETFRAMEWORK || NETSTANDARD || NETCOREAPP2X) || NET6_0 + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tryformat#system-datetimeoffset-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateTimeOffset target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryformat#system-datetime-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateTime target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.DateOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + +#endif +#if NET6_0 + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.dateonly.tryformat#system-dateonly-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this DateOnly target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.DateOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } + + /// + /// Tries to format the value of the current instance into the provided span of characters. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.timeonly.tryformat#system-timeonly-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char))-system-iformatprovider) + public static bool TryFormat(this TimeOnly target, Span destination, out int charsWritten, [StringSyntax(StringSyntaxAttribute.TimeOnlyFormat)] ReadOnlySpan format = default, IFormatProvider? provider = default) + { + string result; + + if (format.Length == 0) + { + result = target.ToString(provider); + } + else + { + result = target.ToString(format.ToString(), provider); + } + + return CopyToSpan(destination, out charsWritten, result); + } +#endif +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Type.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Type.cs new file mode 100644 index 000000000..23f1f7f63 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_Type.cs @@ -0,0 +1,88 @@ +// + +using System.Linq; + +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; + +static partial class Polyfill +{ +#if NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0 + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.memberinfo.hassamemetadatadefinitionas + public static bool HasSameMetadataDefinitionAs(this MemberInfo target, MemberInfo other) => + target.MetadataToken == other.MetadataToken && + target.Module.Equals(other.Module); +#endif + +#if !NET9_0_OR_GREATER && !NETFRAMEWORK && !NETSTANDARD2_0 && !NETCOREAPP2_0 + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod#system-type-getmethod(system-string-system-int32-system-reflection-bindingflags-system-type()) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] + public static MethodInfo? GetMethod(this Type target, string name, int genericParameterCount, BindingFlags bindingAttr, Type[] types) => + target.GetMethod(name, genericParameterCount, bindingAttr, null, types, null); +#endif + + /// + /// Gets a value that indicates whether the current Type represents a type parameter in the definition of a generic method. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.type.isgenericmethodparameter + public static bool IsGenericMethodParameter(this Type target) => +#if NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0 + target.IsGenericParameter && + target.DeclaringMethod != null; +#else + target.IsGenericMethodParameter; +#endif + + /// + /// Generic version of Type.IsAssignableTo https://learn.microsoft.com/en-us/dotnet/api/system.type.isassignableto. + /// + public static bool IsAssignableTo(this Type target) => + typeof(T).IsAssignableFrom(target); + + /// + /// Generic version of Type.IsAssignableFrom https://learn.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom. + /// + public static bool IsAssignableFrom(this Type target) => + target.IsAssignableFrom(typeof(T)); + +#if NETFRAMEWORK || NETSTANDARD || NETCOREAPPX + /// + /// Determines whether the current type can be assigned to a variable of the specified targetType. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.type.isassignableto + public static bool IsAssignableTo(this Type target, [NotNullWhen(true)] Type? targetType) => + targetType?.IsAssignableFrom(target) ?? false; +#endif + +#if !NET6_0_OR_GREATER + + /// + /// Searches for the MemberInfo on the current Type that matches the specified MemberInfo. + /// + /// The MemberInfo to find on the current Type. + /// The MemberInfo to find on the current Type. + /// An object representing the member on the current Type that matches the specified member. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.type.getmemberwithsamemetadatadefinitionas + internal static MemberInfo GetMemberWithSameMetadataDefinitionAs( + this Type type, + MemberInfo member) + { + const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + foreach (var info in type.GetMembers(all)) + { + if (info.HasSameMetadataDefinitionAs(member)) + { + return info; + } + } + + throw new MissingMemberException(type.FullName, member.Name); + } + +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_XDocument.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_XDocument.cs new file mode 100644 index 000000000..a15eea7e4 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Polyfill_XDocument.cs @@ -0,0 +1,82 @@ +// +#pragma warning disable + +#if NETFRAMEWORK || NETSTANDARD2_0 + +namespace Polyfills; + +using System.Xml; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Xml.Linq; + +static partial class Polyfill +{ + /// + /// Output this to an . + /// + /// + /// The to output the XML to. + /// + /// + /// A cancellation token. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync#system-xml-linq-xdocument-saveasync(system-xml-xmlwriter-system-threading-cancellationtoken) + public static Task SaveAsync( + this XDocument target, + XmlWriter writer, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + target.Save(writer); + return Task.CompletedTask; + } + + /// + /// Output this to a . + /// + /// + /// The to output the XML to. + /// + /// + /// If SaveOptions.DisableFormatting is enabled the output is not indented. + /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. + /// + /// A cancellation token. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync#system-xml-linq-xdocument-saveasync(system-io-stream-system-xml-linq-saveoptions-system-threading-cancellationtoken) + public static Task SaveAsync( + this XDocument target, + Stream stream, + SaveOptions options, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + target.Save(stream, options); + return Task.CompletedTask; + } + + /// + /// Output this to a . + /// + /// + /// The to output the XML to. + /// + /// + /// If SaveOptions.DisableFormatting is enabled the output is not indented. + /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. + /// + /// A cancellation token. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument.saveasync#system-xml-linq-xdocument-saveasync(system-io-textwriter-system-xml-linq-saveoptions-system-threading-cancellationtoken) + public static Task SaveAsync( + this XDocument target, + TextWriter textWriter, + SaveOptions options, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + target.Save(textWriter, options); + return Task.CompletedTask; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/Polyfill_Regex.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/Polyfill_Regex.cs new file mode 100644 index 000000000..48f2e95c7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/Polyfill_Regex.cs @@ -0,0 +1,45 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER && FeatureMemory + +namespace Polyfills; + +using System; +using System.Text.RegularExpressions; + +static partial class Polyfill +{ + /// + /// Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input span. + /// + /// true if the regular expression finds a match; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-int32) + public static bool IsMatch(this Regex target, ReadOnlySpan input, int startat) => + target.IsMatch(input.ToString(), startat); + + /// + /// Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input span. + /// + /// true if the regular expression finds a match; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))) + public static bool IsMatch(this Regex target, ReadOnlySpan input) => + target.IsMatch(input.ToString()); + + /// + /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. + /// + /// A Regex.ValueMatchEnumerator to iterate over the matches. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))) + 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. + /// + /// A Regex.ValueMatchEnumerator to iterate over the matches. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-int32) + 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/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexCache.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexCache.cs new file mode 100644 index 000000000..9ab7d7f86 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexCache.cs @@ -0,0 +1,290 @@ +// +#pragma warning disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET7_0_OR_GREATER && FeatureMemory + +namespace System.Text.RegularExpressions; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; +using System.Threading; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +// 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 +{ + // The implementation is optimized to make cache hits fast and lock-free, only taking a global lock + // when adding a new Regex to the cache. Previous implementations of the cache took a global lock + // on all accesses, negatively impacting scalability, in order to minimize costs when the cache + // limit was hit and items needed to be dropped. In such situations, however, we're having to + // pay the relatively hefty cost of creating a new Regex, anyway, and if the consuming app cares + // about such costs, it should either increase Regex.CacheSize or do its own Regex instance caching. + + /// The default maximum number of items to store in the cache. + const int DefaultMaxCacheSize = 15; + /// The maximum number of cached items to examine when we need to replace an existing one in the cache with a new one. + /// This is a somewhat arbitrary value, chosen to be small but at least as large as DefaultMaxCacheSize. + const int MaxExamineOnDrop = 30; + + /// A read-through cache of one element, representing the most recently used regular expression. + static volatile Node? s_lastAccessed; + /// The thread-safe dictionary storing all the items in the cache. + /// + /// The concurrency level is initialized to 1 as we're using our own global lock for all mutations, so we don't need ConcurrentDictionary's + /// striped locking. Capacity is initialized to 31, which is the same as (the private) ConcurrentDictionary.DefaultCapacity. + /// + static ConcurrentDictionary s_cacheDictionary = new ConcurrentDictionary(concurrencyLevel: 1, capacity: 31); + /// A list of all the items in the cache. Protected by . + static List s_cacheList = new List(DefaultMaxCacheSize); + /// Random number generator used to examine a subset of items when we need to drop one from a large list. Protected by . + static Random s_random = new Random(); + /// The current maximum number of items allowed in the cache. This rarely changes. Mostly protected by . + static int s_maxCacheSize = DefaultMaxCacheSize; + + /// Lock used to protect shared state on mutations. + static object SyncObj => s_cacheDictionary; + + /// Gets or sets the maximum size of the cache. + public static int MaxCacheSize + { + get + { + lock (SyncObj) + { + return s_maxCacheSize; + } + } + set + { + Debug.Assert(value >= 0); + + lock (SyncObj) + { + // Store the new max cache size + s_maxCacheSize = value; + + if (value == 0) + { + // If the value is being changed to zero, just clear out the cache. + s_cacheDictionary.Clear(); + s_cacheList.Clear(); + s_lastAccessed = null; + } + else if (value < s_cacheList.Count) + { + // If the value is being changed to less than the number of items we're currently storing, + // just trim off the excess. This is almost never done in practice (if Regex.CacheSize is set + // at all, it's almost always done once towards the beginning of the process, and when it is done, + // it's typically to either 0 or to a larger value than the current limit), so we're not concerned + // with ensuring the actual oldest items are trimmed away. + s_lastAccessed = s_cacheList[0]; + for (int i = value; i < s_cacheList.Count; i++) + { + s_cacheDictionary.TryRemove(s_cacheList[i].Key, out _); + } + s_cacheList.RemoveRange(value, s_cacheList.Count - value); + + Debug.Assert(s_cacheList.Count == value); + Debug.Assert(s_cacheDictionary.Count == value); + } + } + } + } + + public static Regex GetOrAdd(string pattern) + { + // Does not delegate to GetOrAdd(..., RegexOptions, ...) in order to avoid having + // a statically-reachable path to the 'new Regex(..., RegexOptions, ...)', which + // will force the Regex compiler to be reachable and thus rooted for trimming. + + Key key = new Key(pattern, RegexOptions.None, Regex.InfiniteMatchTimeout); + + Regex? regex = Get(key); + if (regex is null) + { + regex = new Regex(pattern); + Add(key, regex); + } + + return regex; + } + + public static Regex GetOrAdd(string pattern, RegexOptions options, TimeSpan matchTimeout) + { + Key key = new Key(pattern, options, matchTimeout); + + Regex? regex = Get(key); + if (regex is null) + { + regex = new Regex(pattern, options, matchTimeout); + Add(key, regex); + } + + return regex; + } + + static Regex? Get(Key key) + { + long lastAccessedStamp = 0; + + // We optimize for repeated usage of the same regular expression over and over, + // by having a fast-path that stores the most recently used instance. Check + // to see if that instance is the one we want; if it is, we're done. + if (s_lastAccessed is Node lastAccessed) + { + if (key.Equals(lastAccessed.Key)) + { + return lastAccessed.Regex; + } + + // We had a last accessed item, but it didn't match the one being requested. + // In case we need to replace the last accessed node, remember this one's stamp; + // we'll use it to compute the new access value for the new node replacing it. + lastAccessedStamp = Volatile.Read(ref lastAccessed.LastAccessStamp); + } + + // Now consult the full cache. + if (s_maxCacheSize != 0 && // hot-read of s_maxCacheSize to try to avoid the cost of the dictionary lookup if the cache is disabled + s_cacheDictionary.TryGetValue(key, out Node? node)) + { + // We found our item in the cache. Make this node's last access stamp one higher than + // the previous one. It's ok if multiple threads racing to update the last access cause + // multiple nodes to have the same value; it's an approximate value meant only to help + // remove the least valuable items when an item needs to be dropped from the cache. We + // do, however, need to read the old value and write the new value using Volatile.Read/Write, + // in order to prevent tearing of the 64-bit value on 32-bit platforms, and to help ensure + // that another thread subsequently sees this updated value. + Volatile.Write(ref node.LastAccessStamp, lastAccessedStamp + 1); + + // Update our fast-path single-field cache. + s_lastAccessed = node; + + // Return the cached regex. + return node.Regex; + } + + // Not in the cache. + return null; + } + + static void Add(Key key, Regex regex) + { + lock (SyncObj) + { + Debug.Assert(s_cacheList.Count == s_cacheDictionary.Count); + + // If the cache has been disabled, there's nothing to add. And if between just checking + // the cache in the caller and taking the lock, another thread could have added the regex. + // If that occurred, there's also nothing to add, and we don't bother to update any of the + // time stamp / fast-path field information, because hitting this race condition means it + // was just updated, and we gain little by updating it again. + if (s_maxCacheSize == 0 || s_cacheDictionary.TryGetValue(key, out _)) + { + return; + } + + // If the cache is full, remove an item to make room for the new one. + if (s_cacheList.Count == s_maxCacheSize) + { + int itemsToExamine; + bool useRandom; + + if (s_maxCacheSize <= MaxExamineOnDrop) + { + // Our maximum cache size is <= the number of items we're willing to examine (which is kept small simply + // to avoid spending a lot of time). As such, we can just examine the whole list. + itemsToExamine = s_cacheList.Count; + useRandom = false; + } + else + { + // Our maximum cache size is > the number of items we're willing to examine, so we'll instead + // examine a random subset. This isn't perfect: if the size of the list is only a tiny bit + // larger than the max we're willing to examine, there's a good chance we'll look at some of + // the same items twice. That's fine; this doesn't need to be perfect. We do not need a perfect LRU + // cache, just one that generally gets rid of older things when new things come in. + itemsToExamine = MaxExamineOnDrop; + useRandom = true; + } + + // Pick the first item to use as the min. + int minListIndex = useRandom ? s_random.Next(s_cacheList.Count) : 0; + long min = Volatile.Read(ref s_cacheList[minListIndex].LastAccessStamp); + + // Now examine the rest, keeping track of the smallest access stamp we find. + for (int i = 1; i < itemsToExamine; i++) + { + int nextIndex = useRandom ? s_random.Next(s_cacheList.Count) : i; + long next = Volatile.Read(ref s_cacheList[nextIndex].LastAccessStamp); + if (next < min) + { + minListIndex = nextIndex; + min = next; + } + } + + // Remove the key found to have the smallest access stamp. + s_cacheDictionary.TryRemove(s_cacheList[minListIndex].Key, out _); + s_cacheList.RemoveAt(minListIndex); + } + + // Finally add the regex. + var node = new Node(key, regex); + s_lastAccessed = node; + s_cacheList.Add(node); + s_cacheDictionary.TryAdd(key, node); + + Debug.Assert(s_cacheList.Count <= s_maxCacheSize); + Debug.Assert(s_cacheList.Count == s_cacheDictionary.Count); + } + } + + /// Used as a key for . + internal readonly struct Key : IEquatable + { + readonly string _pattern; + readonly RegexOptions _options; + readonly TimeSpan _matchTimeout; + + public Key(string pattern, RegexOptions options, TimeSpan matchTimeout) + { + Debug.Assert(pattern != null, "Pattern must be provided"); + + _pattern = pattern; + _options = options; + _matchTimeout = matchTimeout; + } + + public override bool Equals([NotNullWhen(true)] object? obj) => + obj is Key other && Equals(other); + + public bool Equals(Key other) => + _pattern.Equals(other._pattern) && + _options == other._options && + _matchTimeout == other._matchTimeout; + + public override int GetHashCode() => + // Hash code only factors in pattern and options, as regex instances are unlikely to have + // the same pattern and options but different culture and timeout. + _pattern.GetHashCode() ^ (int)_options; + } + + /// Node for a cached Regex instance. + sealed class Node(Key key, Regex regex) + { + /// The key associated with this cached instance. + public readonly Key Key = key; + /// The cached Regex instance. + public readonly Regex Regex = regex; + /// A "time" stamp representing the approximate last access time for this Regex. + public long LastAccessStamp; + } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexPolyfill.cs new file mode 100644 index 000000000..70b48b9aa --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/RegexPolyfill.cs @@ -0,0 +1,111 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Text.RegularExpressions; + +#if FeatureMemory +#if NET7_0_OR_GREATER +using ValueMatchEnumerator = System.Text.RegularExpressions.Regex.ValueMatchEnumerator; +#else +using ValueMatchEnumerator = System.Text.RegularExpressions.ValueMatchEnumerator; +#endif +#endif + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif + static class RegexPolyfill +{ +#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. + /// + /// true if the regular expression finds a match; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch#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 + return Regex.IsMatch(input, pattern, options, timeout); +#else + return Regex.IsMatch(input.ToString(), pattern, options, timeout); +#endif + } + + /// + /// Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options. + /// + /// true if the regular expression finds a match; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch#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 + return Regex.IsMatch(input, pattern, options); +#else + return Regex.IsMatch(input.ToString(), pattern, options); +#endif + } + + /// + /// Indicates whether the specified regular expression finds a match in the specified input span. + /// + /// true if the regular expression finds a match; otherwise, false. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch#system-text-regularexpressions-regex-ismatch(system-readonlyspan((system-char))-system-string) + public static bool IsMatch(ReadOnlySpan input, string pattern) + { +#if NET7_0_OR_GREATER + return Regex.IsMatch(input, pattern); +#else + return Regex.IsMatch(input.ToString(), pattern); +#endif + } + + /// + /// Searches an input span for all occurrences of a regular expression and returns a Regex.ValueMatchEnumerator to iterate over the matches. + /// + /// A Regex.ValueMatchEnumerator to iterate over the matches. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches#system-text-regularexpressions-regex-enumeratematches(system-readonlyspan((system-char))-system-string) + public static ValueMatchEnumerator EnumerateMatches(ReadOnlySpan input, string pattern) + { +#if NET7_0_OR_GREATER + return Regex.EnumerateMatches(input, pattern); +#else + return 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. + /// + /// A Regex.ValueMatchEnumerator to iterate over the matches. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches#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 + return Regex.EnumerateMatches(input, pattern, options, timeout); +#else + return 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. + /// + /// A Regex.ValueMatchEnumerator to iterate over the matches. + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.enumeratematches#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 + return Regex.EnumerateMatches(input, pattern); +#else + return new Regex(pattern, options).EnumerateMatches(input); +#endif + } +#endif +} diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatch.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatch.cs new file mode 100644 index 000000000..139902039 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatch.cs @@ -0,0 +1,50 @@ +// +#pragma warning disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET7_0_OR_GREATER && FeatureMemory + +namespace System.Text.RegularExpressions; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +/// +/// Represents the results from a single regular expression match. +/// +/// +/// The type is immutable and has no public constructor. An instance of the struct is returned by the +/// method when iterating over the results from calling . +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +readonly ref struct ValueMatch +{ + /// + /// Crates an instance of the type based on the passed in and . + /// + /// The position in the original span where the first character of the captured sliced span is found. + /// The length of the captured sliced span. + internal ValueMatch(int index, int length) + { + Index = index; + Length = length; + } + + /// + /// Gets the position in the original span where the first character of the captured sliced span is found. + /// + public int Index { get; } + + /// + /// Gets the length of the captured sliced span. + /// + public int Length { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatchEnumerator.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatchEnumerator.cs new file mode 100644 index 000000000..fd200924f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Regex/ValueMatchEnumerator.cs @@ -0,0 +1,83 @@ +// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +#pragma warning disable + +#if !NET7_0_OR_GREATER && FeatureMemory + +namespace System.Text.RegularExpressions; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +//https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.EnumerateMatches.cs +/// +/// Represents an enumerator containing the set of successful matches found by iteratively applying a regular expression pattern to the input span. +/// +/// +/// The enumerator has no public constructor. The method returns a +/// object.The enumerator will lazily iterate over zero or more objects. If there is at least one successful match in the span, then +/// returns and will contain the first . If there are no successful matches, +/// then returns and throws an . +/// +/// This type is a ref struct since it stores the input span as a field in order to be able to lazily iterate over it. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +ref struct ValueMatchEnumerator +{ + ReadOnlySpan _input; + ValueMatch _current; + MatchCollection matchCollection; + int index = 0; + + /// + /// Creates an instance of the for the passed in which iterates over . + /// + /// The to use for finding matches. + /// The input span to iterate over. + /// The position where the engine should start looking for matches from. + internal ValueMatchEnumerator(Regex regex, ReadOnlySpan input, int startAt) + { + matchCollection = regex.Matches(input.ToString(), startAt); + _input = input; + _current = default; + } + + /// + /// Provides an enumerator that iterates through the matches in the input span. + /// + /// A copy of this enumerator. + public readonly ValueMatchEnumerator GetEnumerator() => this; + + /// + /// Advances the enumerator to the next match in the span. + /// + /// + /// if the enumerator was successfully advanced to the next element; if the enumerator cannot find additional matches. + /// + public bool MoveNext() + { + if (index == matchCollection.Count) + { + return false; + } + + var match = matchCollection[index]; + _current = new ValueMatch(match.Index, match.Length); + index++; + return true; + } + + /// + /// Gets the element at the current position of the enumerator. + /// + /// Enumeration has either not started or has already finished. + public readonly ValueMatch Current => _current; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiredMemberAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiredMemberAttribute.cs new file mode 100644 index 000000000..8564df41f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiredMemberAttribute.cs @@ -0,0 +1,29 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Specifies that a type has required members or that a member is required. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Class | + Targets.Struct | + Targets.Field | + Targets.Property, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class RequiredMemberAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiresPreviewFeaturesAttribute .cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiresPreviewFeaturesAttribute .cs new file mode 100644 index 000000000..b83f45d4e --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/RequiresPreviewFeaturesAttribute .cs @@ -0,0 +1,60 @@ +// +#pragma warning disable + +#nullable enable + +#if !NET6_0_OR_GREATER + +namespace System.Runtime.Versioning; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[AttributeUsage(AttributeTargets.Assembly | + AttributeTargets.Module | + AttributeTargets.Class | + AttributeTargets.Interface | + AttributeTargets.Delegate | + AttributeTargets.Struct | + AttributeTargets.Enum | + AttributeTargets.Constructor | + AttributeTargets.Method | + AttributeTargets.Property | + AttributeTargets.Field | + AttributeTargets.Event, + Inherited = false)] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.versioning.requirespreviewfeaturesattribute +#if PolyPublic +public +#endif +sealed class RequiresPreviewFeaturesAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class. + /// + public RequiresPreviewFeaturesAttribute() + { + } + + /// + /// Initializes a new instance of the class with the specified message. + /// + /// An optional message associated with this attribute instance. + public RequiresPreviewFeaturesAttribute(string? message) => + Message = message; + + /// + /// Returns the optional message associated with this attribute instance. + /// + public string? Message { get; } + + /// + /// Returns the optional URL associated with this attribute instance. + /// + public string? Url { get; set; } +} + +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ResolveHttpGlobalProblem.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ResolveHttpGlobalProblem.cs new file mode 100644 index 000000000..239e53419 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/ResolveHttpGlobalProblem.cs @@ -0,0 +1,17 @@ +// +#pragma warning disable + +#if NETFRAMEWORK + +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Net.Http; + +[EditorBrowsable(EditorBrowsableState.Never)] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +static class ResolveHttpGlobalProblem; + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SetsRequiredMembersAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SetsRequiredMembersAttribute.cs new file mode 100644 index 000000000..f3db64392 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SetsRequiredMembersAttribute.cs @@ -0,0 +1,20 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that this constructor sets all required members for the current type, and callers +/// do not need to set any required members themselves. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Constructor)] +#if PolyPublic +public +#endif +sealed class SetsRequiredMembersAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SkipLocalsInitAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SkipLocalsInitAttribute.cs new file mode 100644 index 000000000..fe4b48881 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SkipLocalsInitAttribute.cs @@ -0,0 +1,44 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Used to indicate to the compiler that the .locals init +/// flag should not be set in method headers. +/// +/// +/// This attribute is unsafe because it may reveal uninitialized memory to +/// the application in certain instances (e.g., reading from uninitialized +/// stackalloc'd memory). If applied to a method directly, the attribute +/// applies to that method and all nested functions (lambdas, local +/// functions) below it. If applied to a type or module, it applies to all +/// methods nested inside. This attribute is intentionally not permitted on +/// assemblies. Use at the module level instead to apply to multiple type +/// declarations. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Module | + Targets.Class | + Targets.Struct | + Targets.Interface | + Targets.Constructor | + Targets.Method | + Targets.Property | + Targets.Event, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class SkipLocalsInitAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SpanLineEnumerator.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SpanLineEnumerator.cs new file mode 100644 index 000000000..0d18e997d --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SpanLineEnumerator.cs @@ -0,0 +1,95 @@ +// +#pragma warning disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if FeatureMemory && !NET6_0_OR_GREATER + +namespace System.Text; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Enumerates the lines of a . +/// +/// +/// To get an instance of this type, use . +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.spanlineenumerator +#if PolyPublic +public +#endif +ref struct SpanLineEnumerator +{ + ReadOnlySpan remaining; + bool isActive; + ReadOnlySpan newlines = "\r\f\u0085\u2028\u2029\n".AsSpan(); + + internal SpanLineEnumerator(ReadOnlySpan buffer) + { + remaining = buffer; + Current = default; + isActive = true; + } + + /// + /// Gets the line at the current position of the enumerator. + /// + public ReadOnlySpan Current { get; private set; } + + /// + /// Returns this instance as an enumerator. + /// + public SpanLineEnumerator GetEnumerator() => this; + + /// + /// Advances the enumerator to the next line of the span. + /// + /// + /// True if the enumerator successfully advanced to the next line; false if + /// the enumerator has advanced past the end of the span. + /// + public bool MoveNext() + { + if (!isActive) + { + // EOF previously reached or enumerator was never initialized + return false; + } + + //TODO: revisit when SearchValues is implemented + var index = remaining.IndexOfAny(newlines); + + var remainingLength = (uint)remaining.Length; + if ((uint)index < remainingLength) + { + var stride = 1; + + if (remaining[index] == '\r' && + (uint)(index + 1) < remainingLength && + remaining[index + 1] == '\n') + { + stride = 2; + } + + // ReSharper disable ReplaceSliceWithRangeIndexer + //Dont use range indexer here since https://github.com/SimonCropp/Polyfill/pull/159 + Current = remaining.Slice(0, index); + remaining = remaining.Slice(index + stride); + // ReSharper restore ReplaceSliceWithRangeIndexer + return true; + } + + // We've reached EOF, but we still need to return 'true' for this final + // iteration so that the caller can query the Current property once more. + Current = remaining; + remaining = default; + isActive = false; + return true; + } +} +#endif diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StackTraceHiddenAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StackTraceHiddenAttribute.cs new file mode 100644 index 000000000..79f079aa3 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StackTraceHiddenAttribute.cs @@ -0,0 +1,28 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +namespace System.Diagnostics; + +using System.Diagnostics.CodeAnalysis; +using Targets = AttributeTargets; + +/// +/// Types and Methods attributed with StackTraceHidden will be omitted from the stack trace text shown in StackTrace.ToString() +/// and Exception.StackTrace +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Class | + Targets.Method | + Targets.Constructor | + Targets.Struct, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class StackTraceHiddenAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs new file mode 100644 index 000000000..7017ff2bf --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/AppendInterpolatedStringHandler.cs @@ -0,0 +1,351 @@ +// +#pragma warning disable + +#if FeatureMemory && !NET6_0_OR_GREATER + +#nullable enable + +namespace System.Text; + +using ComponentModel; +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Runtime.CompilerServices; + +//https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +/// Provides a handler used by the language compiler to append interpolated strings into instances. +[EditorBrowsable(EditorBrowsableState.Never)] +[InterpolatedStringHandler] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +struct AppendInterpolatedStringHandler +{ + // Implementation note: + // As this type is only intended to be targeted by the compiler, public APIs eschew argument validation logic + // in a variety of places, e.g. allowing a null input when one isn't expected to produce a NullReferenceException rather + // than an ArgumentNullException. + + const int StackallocCharBufferSizeLimit = 256; + + /// The associated StringBuilder to which to append. + StringBuilder _stringBuilder; + + /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls. + IFormatProvider? _provider; + + /// Whether provides an ICustomFormatter. + /// + /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive + /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field + /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider + /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a + /// formatter, we pay for the extra interface call on each AppendFormatted that needs it. + /// + bool _hasCustomFormatter; + + /// Creates a handler used to append an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// The associated StringBuilder to which to append. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder) + { + _stringBuilder = stringBuilder; + _provider = null; + _hasCustomFormatter = false; + } + + /// Creates a handler used to translate an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// The associated StringBuilder to which to append. + /// An object that supplies culture-specific formatting information. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder, IFormatProvider? provider) + { + _stringBuilder = stringBuilder; + _provider = provider; + _hasCustomFormatter = provider is not null && DefaultInterpolatedStringHandler.HasCustomFormatter(provider); + } + + /// Writes the specified string to the handler. + /// The string to write. + public void AppendLiteral(string value) => _stringBuilder.Append(value); + + #region AppendFormatted + + // Design note: + // This provides the same set of overloads and semantics as DefaultInterpolatedStringHandler. + + #region AppendFormatted T + + /// Writes the specified value to the handler. + /// The value to write. + /// The type of the value to write. + public void AppendFormatted(T value) + { + // This method could delegate to AppendFormatted with a null format, but explicitly passing + // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined, + // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format. + + if (_hasCustomFormatter) + { + // If there's a custom formatter, always use it. + AppendCustomFormatter(value, format: null); + } + else if (value is IFormattable fValue) + { + // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter + // requires the former. For value types, it won't matter as the type checks devolve into + // JIT-time constants. For reference types, they're more likely to implement IFormattable + // than they are to implement ISpanFormattable: if they don't implement either, we save an + // interface check over first checking for ISpanFormattable and then for IFormattable, and + // if it only implements IFormattable, we come out even: only if it implements both do we + // end up paying for an extra interface check. + + if (typeof(T).IsEnum || HasTryFormatExtension(typeof(T)) || fValue is ISpanFormattable) + { + // Formats into temporary space and then copies the result into the StringBuilder. + AppendFormattedWithTempSpace(value, 0, format: null); + } + else + { + // constrained call avoiding boxing for value types + _stringBuilder.Append(fValue.ToString(format: null, _provider)); + } + } + else if (value is not null) + { + _stringBuilder.Append(value.ToString()); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// The format string. + /// The type of the value to write. + public void AppendFormatted(T value, string? format) + { + if (_hasCustomFormatter) + { + // If there's a custom formatter, always use it. + AppendCustomFormatter(value, format); + } + else if (value is IFormattable fValue) + { + // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter + // requires the former. For value types, it won't matter as the type checks devolve into + // JIT-time constants. For reference types, they're more likely to implement IFormattable + // than they are to implement ISpanFormattable: if they don't implement either, we save an + // interface check over first checking for ISpanFormattable and then for IFormattable, and + // if it only implements IFormattable, we come out even: only if it implements both do we + // end up paying for an extra interface check. + + if (typeof(T).IsEnum || HasTryFormatExtension(typeof(T)) || fValue is ISpanFormattable) + { + // Formats into temporary space and then copies the result into the StringBuilder. + AppendFormattedWithTempSpace(value, 0, format); + } + else + { + // constrained call avoiding boxing for value types + _stringBuilder.Append(fValue.ToString(format, _provider)); + } + } + else if (value is not null) + { + _stringBuilder.Append(value.ToString()); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The type of the value to write. + public void AppendFormatted(T value, int alignment) => + AppendFormatted(value, alignment, format: null); + + /// Writes the specified value to the handler. + /// The value to write. + /// The format string. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The type of the value to write. + public void AppendFormatted(T value, int alignment, string? format) + { + if (alignment == 0) + { + // This overload is used as a fallback from several disambiguation overloads, so special-case 0. + AppendFormatted(value, format); + } + else if (alignment < 0) + { + // Left aligned: format into the handler, then append any additional padding required. + var start = _stringBuilder.Length; + AppendFormatted(value, format); + var paddingRequired = -alignment - (_stringBuilder.Length - start); + if (paddingRequired > 0) + { + _stringBuilder.Append(' ', paddingRequired); + } + } + else + { + // Right aligned: format into temporary space and then copy that into the handler, appropriately aligned. + AppendFormattedWithTempSpace(value, alignment, format); + } + } + + /// Formats into temporary space and then appends the result into the StringBuilder. + void AppendFormattedWithTempSpace(T value, int alignment, string? format) + { + // It's expected that either there's not enough space in the current chunk to store this formatted value, + // or we have a non-0 alignment that could require padding inserted. So format into temporary space and + // then append that written span into the StringBuilder: StringBuilder.Append(span) is able to split the + // span across the current chunk and any additional chunks required. + + var handler = new DefaultInterpolatedStringHandler(0, 0, _provider, stackalloc char[StackallocCharBufferSizeLimit]); + handler.AppendFormatted(value, format); + AppendFormatted(handler.Text, alignment); + handler.Clear(); + } + + #endregion + + #region AppendFormatted ReadOnlySpan + + /// Writes the specified character span to the handler. + /// The span to write. + public void AppendFormatted(ReadOnlySpan value) => _stringBuilder.Append(value); + + /// Writes the specified string of chars to the handler. + /// The span to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) + { + if (alignment == 0) + { + _stringBuilder.Append(value); + } + else + { + var leftAlign = false; + if (alignment < 0) + { + leftAlign = true; + alignment = -alignment; + } + + var paddingRequired = alignment - value.Length; + if (paddingRequired <= 0) + { + _stringBuilder.Append(value); + } + else if (leftAlign) + { + _stringBuilder.Append(value); + _stringBuilder.Append(' ', paddingRequired); + } + else + { + _stringBuilder.Append(' ', paddingRequired); + _stringBuilder.Append(value); + } + } + } + + #endregion + + #region AppendFormatted string + + /// Writes the specified value to the handler. + /// The value to write. + public void AppendFormatted(string? value) + { + if (!_hasCustomFormatter) + { + _stringBuilder.Append(value); + } + else + { + AppendFormatted(value); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(string? value, int alignment = 0, string? format = null) => + // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload + // simply to disambiguate between ROS and object, just in case someone does specify a format, as + // string is implicitly convertible to both. Just delegate to the T-based implementation. + AppendFormatted(value, alignment, format); + + #endregion + + #region AppendFormatted object + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(object? value, int alignment = 0, string? format = null) => + // This overload is expected to be used rarely, only if either a) something strongly typed as object is + // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It + // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation. + AppendFormatted(value, alignment, format); + + #endregion + + #endregion + + /// Formats the value using the custom formatter from the provider. + /// The value to write. + /// The format string. + /// The type of the value to write. + [MethodImpl(MethodImplOptions.NoInlining)] + void AppendCustomFormatter(T value, string? format) + { + // This case is very rare, but we need to handle it prior to the other checks in case + // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value. + // We do the cast here rather than in the ctor, even though this could be executed multiple times per + // formatting, to make the cast pay for play. + Debug.Assert(_hasCustomFormatter); + Debug.Assert(_provider != null); + + var formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter)); + Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't"); + + if (formatter is not null) + { + _stringBuilder.Append(formatter.Format(format, value, _provider)); + } + } + + static bool HasTryFormatExtension(Type type) => + type == typeof(int) || type == typeof(bool) || type == typeof(byte) || type == typeof(float) || + type == typeof(double) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || + type == typeof(decimal) || type == typeof(long) || type == typeof(short) || type == typeof(ushort) || + type == typeof(uint) || type == typeof(ulong) || type == typeof(sbyte); +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs new file mode 100644 index 000000000..7316298f7 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/DefaultInterpolatedStringHandler.cs @@ -0,0 +1,816 @@ +// +#pragma warning disable + +#if FeatureMemory && !NET6_0_OR_GREATER + +#nullable enable + +namespace System.Runtime.CompilerServices; + +using System; +using Buffers; +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Globalization; +using Link = ComponentModel.DescriptionAttribute; + +/// Provides a handler used by the language compiler to process interpolated strings into instances. +[InterpolatedStringHandler] +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.defaultinterpolatedstringhandler +#if PolyPublic +public +#endif +ref struct DefaultInterpolatedStringHandler +{ + // Implementation note: + // As this type lives in CompilerServices and is only intended to be targeted by the compiler, + // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input + // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException. + + /// Expected average length of formatted data used for an individual interpolation expression result. + /// + /// This is inherited from string.Format, and could be changed based on further data. + /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length + /// includes the format items themselves, e.g. "{0}", and since it's rare to have double-digit + /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in "{d}", + /// since the compiler-provided base length won't include the equivalent character count. + /// + const int GuessedLengthPerHole = 11; + /// Minimum size array to rent from the pool. + /// Same as stack-allocation size used today by string.Format. + const int MinimumArrayPoolLength = 256; + + /// Maximum length allowed for a string. + /// Keep in sync with AllocateString in gchelpers.cpp. + const int StringMaxLength = 0x3FFFFFDF; + + /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls. + readonly IFormatProvider? _provider; + /// Array rented from the array pool and used to back . + char[]? _arrayToReturnToPool; + /// The span to write into. + Span _chars; + /// Position at which to write the next character. + int _pos; + /// Whether provides an ICustomFormatter. + /// + /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive + /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field + /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider + /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a + /// formatter, we pay for the extra interface call on each AppendFormatted that needs it. + /// + bool _hasCustomFormatter; + + /// Creates a handler used to translate an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) + { + _provider = null; + _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount)); + _pos = 0; + _hasCustomFormatter = false; + } + + /// Creates a handler used to translate an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// An object that supplies culture-specific formatting information. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider) + { + _provider = provider; + _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount)); + _pos = 0; + _hasCustomFormatter = provider is not null && HasCustomFormatter(provider); + } + + /// Creates a handler used to translate an interpolated string into a . + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + /// An object that supplies culture-specific formatting information. + /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten. + /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. + public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer) + { + _provider = provider; + _chars = initialBuffer; + _arrayToReturnToPool = null; + _pos = 0; + _hasCustomFormatter = provider is not null && HasCustomFormatter(provider); + } + + /// Derives a default length with which to seed the handler. + /// The number of constant characters outside of interpolation expressions in the interpolated string. + /// The number of interpolation expressions in the interpolated string. + [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant + internal static int GetDefaultLength(int literalLength, int formattedCount) => + Math.Max(MinimumArrayPoolLength, literalLength + formattedCount * GuessedLengthPerHole); + + /// Gets the built . + /// The built string. + public override string ToString() => Text.ToString(); + + /// Gets the built and clears the handler. + /// The built string. + /// + /// This releases any resources used by the handler. The method should be invoked only + /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined, + /// and may destabilize the process, as may using any other copies of the handler after ToStringAndClear + /// is called on any one of them. + /// + public string ToStringAndClear() + { + var result = Text.ToString(); + Clear(); + return result; + } + + /// Clears the handler, returning any rented array to the pool. + [MethodImpl(MethodImplOptions.AggressiveInlining)] // used only on a few hot paths + internal void Clear() + { + var toReturn = _arrayToReturnToPool; + this = default; // defensive clear + if (toReturn is not null) + { + ArrayPool.Shared.Return(toReturn); + } + } + + /// Gets a span of the written characters thus far. + internal ReadOnlySpan Text => _chars.Slice(0, _pos); + + /// Writes the specified string to the handler. + /// The string to write. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AppendLiteral(string value) + { + if (value.TryCopyTo(_chars.Slice(_pos))) + { + _pos += value.Length; + } + else + { + GrowThenCopyString(value); + } + } + + #region AppendFormatted + // Design note: + // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression; + // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile. + // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to + // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case, + // interpolated strings will still work, but it has the downside that a developer generally won't know + // if the fallback is happening and they're paying more.) + // + // At a minimum, then, we would need an overload that accepts: + // (object value, int alignment = 0, string? format = null) + // Such an overload would provide the same expressiveness as string.Format. However, this has several + // shortcomings: + // - Every value type in an interpolation expression would be boxed. + // - ReadOnlySpan could not be used in interpolation expressions. + // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further. + // - Every invocation would be more expensive, due to lack of specialization, every call needing to account + // for alignment and format, etc. + // + // To address that, we could just have overloads for T and ReadOnlySpan: + // (T) + // (T, int alignment) + // (T, string? format) + // (T, int alignment, string? format) + // (ReadOnlySpan) + // (ReadOnlySpan, int alignment) + // (ReadOnlySpan, string? format) + // (ReadOnlySpan, int alignment, string? format) + // but this also has shortcomings: + // - Some expressions that would have worked with an object overload will now force a fallback to string.Format + // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler + // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully + // be passed as an argument of type `object` but not of type `T`. + // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads + // from doing so. + // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate + // at compile time for value types but don't (currently) if the Nullable goes through the same code paths + // (see https://github.com/dotnet/runtime/issues/50915). + // + // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common + // handler and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads + // for each of: + // (T, ...) where T : struct + // (T?, ...) where T : struct + // (object, ...) + // (ReadOnlySpan, ...) + // (string, ...) + // but this also has shortcomings, most importantly: + // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object + // overload. This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, + // so without those they'd all map to the object overloads as well. + // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the + // overloads. string is one such type, hence needing dedicated overloads for it that can be bound to more tightly. + // + // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, + // would be the set: + // (T, ...) with no constraint + // (ReadOnlySpan) and (ReadOnlySpan, int) + // (object, int alignment = 0, string? format = null) + // (string) and (string, int) + // This would address most of the concerns, at the expense of: + // - Most reference types going through the generic code paths and so being a bit more expensive. + // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed. + // We could choose to add a T? where T : struct set of overloads if necessary. + // Strings don't require their own overloads here, but as they're expected to be very common and as we can + // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't + // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them. + // + // Hole values are formatted according to the following policy: + // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if + // the value is null). + // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat. + // 3. If the type implements IFormattable, use IFormattable.ToString. + // 4. Otherwise, use object.ToString. + // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this + // doesn't apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, + // but more importantly which can't be boxed to be passed to ICustomFormatter.Format. + + #region AppendFormatted T + /// Writes the specified value to the handler. + /// The value to write. + /// The type of the value to write. + public void AppendFormatted(T value) + { + // This method could delegate to AppendFormatted with a null format, but explicitly passing + // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined, + // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format. + + // If there's a custom formatter, always use it. + if (_hasCustomFormatter) + { + AppendCustomFormatter(value, format: null); + return; + } + + // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter + // requires the former. For value types, it won't matter as the type checks devolve into + // JIT-time constants. For reference types, they're more likely to implement IFormattable + // than they are to implement ISpanFormattable: if they don't implement either, we save an + // interface check over first checking for ISpanFormattable and then for IFormattable, and + // if it only implements IFormattable, we come out even: only if it implements both do we + // end up paying for an extra interface check. + string? s; + if (value is IFormattable fValue) + { + // If the value can format itself directly into our buffer, do so. + + if (TryFormatWithExtensions(value, default)) + { + return; + } + else if (fValue is ISpanFormattable sfValue) + { + int charsWritten; + // constrained call avoiding boxing for value types + while (!sfValue.TryFormat(_chars.Slice(_pos), out charsWritten, default, _provider)) + { + Grow(); + } + + _pos += charsWritten; + return; + } + + s = fValue.ToString(format: null, _provider); // constrained call avoiding boxing for value types + } + else + { + s = value?.ToString(); + } + + if (s is not null) + { + AppendLiteral(s); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// The format string. + /// The type of the value to write. + public void AppendFormatted(T value, string? format) + { + // If there's a custom formatter, always use it. + if (_hasCustomFormatter) + { + AppendCustomFormatter(value, format); + return; + } + + // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter + // requires the former. For value types, it won't matter as the type checks devolve into + // JIT-time constants. For reference types, they're more likely to implement IFormattable + // than they are to implement ISpanFormattable: if they don't implement either, we save an + // interface check over first checking for ISpanFormattable and then for IFormattable, and + // if it only implements IFormattable, we come out even: only if it implements both do we + // end up paying for an extra interface check. + string? s; + if (value is IFormattable fValue) + { + // If the value can format itself directly into our buffer, do so. + + if (TryFormatWithExtensions(value, format.AsSpan())) + { + return; + } + else if (fValue is ISpanFormattable sfValue) + { + int charsWritten; + // constrained call avoiding boxing for value types + while (!sfValue.TryFormat(_chars.Slice(_pos), out charsWritten, format.AsSpan(), _provider)) + { + Grow(); + } + + _pos += charsWritten; + return; + } + + s = fValue.ToString(format, _provider); // constrained call avoiding boxing for value types + } + else + { + s = value?.ToString(); + } + + if (s is not null) + { + AppendLiteral(s); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The type of the value to write. + public void AppendFormatted(T value, int alignment) + { + var startingPos = _pos; + AppendFormatted(value); + if (alignment != 0) + { + AppendOrInsertAlignmentIfNeeded(startingPos, alignment); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// The format string. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The type of the value to write. + public void AppendFormatted(T value, int alignment, string? format) + { + var startingPos = _pos; + AppendFormatted(value, format); + if (alignment != 0) + { + AppendOrInsertAlignmentIfNeeded(startingPos, alignment); + } + } + #endregion + + #region AppendFormatted ReadOnlySpan + /// Writes the specified character span to the handler. + /// The span to write. + public void AppendFormatted(scoped ReadOnlySpan value) + { + // Fast path for when the value fits in the current buffer + if (value.TryCopyTo(_chars.Slice(_pos))) + { + _pos += value.Length; + } + else + { + GrowThenCopySpan(value); + } + } + + /// Writes the specified string of chars to the handler. + /// The span to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null) + { + var leftAlign = false; + if (alignment < 0) + { + leftAlign = true; + alignment = -alignment; + } + + var paddingRequired = alignment - value.Length; + if (paddingRequired <= 0) + { + // The value is as large or larger than the required amount of padding, + // so just write the value. + AppendFormatted(value); + return; + } + + // Write the value along with the appropriate padding. + EnsureCapacityForAdditionalChars(value.Length + paddingRequired); + if (leftAlign) + { + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + _chars.Slice(_pos, paddingRequired).Fill(' '); + _pos += paddingRequired; + } + else + { + _chars.Slice(_pos, paddingRequired).Fill(' '); + _pos += paddingRequired; + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + } + } + #endregion + + #region AppendFormatted string + /// Writes the specified value to the handler. + /// The value to write. + public void AppendFormatted(string? value) + { + // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer. + if (!_hasCustomFormatter && + value is not null && + value.TryCopyTo(_chars.Slice(_pos))) + { + _pos += value.Length; + } + else + { + AppendFormattedSlow(value); + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Slow path to handle a custom formatter, potentially null value, + /// or a string that doesn't fit in the current buffer. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + void AppendFormattedSlow(string? value) + { + if (_hasCustomFormatter) + { + AppendCustomFormatter(value, format: null); + } + else if (value is not null) + { + EnsureCapacityForAdditionalChars(value.Length); + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + } + } + + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(string? value, int alignment = 0, string? format = null) => + // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload + // simply to disambiguate between ROS and object, just in case someone does specify a format, as + // string is implicitly convertible to both. Just delegate to the T-based implementation. + AppendFormatted(value, alignment, format); + #endregion + + #region AppendFormatted object + /// Writes the specified value to the handler. + /// The value to write. + /// + /// Minimum number of characters that should be written for this value. If the value is negative, it indicates + /// left-aligned and the required minimum is the absolute value. + /// + /// The format string. + public void AppendFormatted(object? value, int alignment = 0, string? format = null) => + // This overload is expected to be used rarely, only if either a) something strongly typed as object is + // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It + // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation. + AppendFormatted(value, alignment, format); + #endregion + #endregion + + /// Gets whether the provider provides a custom formatter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites + internal static bool HasCustomFormatter(IFormatProvider provider) + { + Debug.Assert(provider is not null); + Debug.Assert( + provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, + "Expected CultureInfo to not provide a custom formatter"); + + return + provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case + provider.GetFormat(typeof(ICustomFormatter)) != null; + } + + /// Formats the value using the custom formatter from the provider. + /// The value to write. + /// The format string. + /// The type of the value to write. + [MethodImpl(MethodImplOptions.NoInlining)] + void AppendCustomFormatter(T value, string? format) + { + // This case is very rare, but we need to handle it prior to the other checks in case + // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value. + // We do the cast here rather than in the ctor, even though this could be executed multiple times per + // formatting, to make the cast pay for play. + Debug.Assert(_hasCustomFormatter); + Debug.Assert(_provider != null); + + var formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter)); + Debug.Assert( + formatter != null, + "An incorrectly written provider said it implemented ICustomFormatter, and then didn't"); + + if (formatter?.Format(format, value, _provider) is { } customFormatted) + { + AppendLiteral(customFormatted); + } + } + + /// Handles adding any padding required for aligning a formatted value in an interpolation expression. + /// The position at which the written value started. + /// + /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it + /// indicates left-aligned and the required minimum is the absolute value. + /// + void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) + { + Debug.Assert(startingPos >= 0 && startingPos <= _pos); + Debug.Assert(alignment != 0); + + var charsWritten = _pos - startingPos; + + var leftAlign = false; + if (alignment < 0) + { + leftAlign = true; + alignment = -alignment; + } + + var paddingNeeded = alignment - charsWritten; + if (paddingNeeded > 0) + { + EnsureCapacityForAdditionalChars(paddingNeeded); + + if (leftAlign) + { + _chars.Slice(_pos, paddingNeeded).Fill(' '); + } + else + { + _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded)); + _chars.Slice(startingPos, paddingNeeded).Fill(' '); + } + + _pos += paddingNeeded; + } + } + + /// + /// Ensures has the capacity to store beyond . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void EnsureCapacityForAdditionalChars(int additionalChars) + { + if (_chars.Length - _pos < additionalChars) + { + Grow(additionalChars); + } + } + + /// + /// Fallback for fast path in when there's not enough space in the destination. + /// + /// The string to write. + [MethodImpl(MethodImplOptions.NoInlining)] + void GrowThenCopyString(string value) + { + Grow(value.Length); + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + } + + /// + /// Fallback for for when not enough space exists in the current buffer. + /// + /// The span to write. + [MethodImpl(MethodImplOptions.NoInlining)] + void GrowThenCopySpan(scoped ReadOnlySpan value) + { + Grow(value.Length); + value.CopyTo(_chars.Slice(_pos)); + _pos += value.Length; + } + + /// + /// Grows to have the capacity to store at least + /// beyond . + /// + [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible + void Grow(int additionalChars) + { + // This method is called when the remaining space (_chars.Length - _pos) is + // insufficient to store a specific number of additional characters. Thus, we + // need to grow to at least that new total. GrowCore will handle growing by more + // than that if possible. + Debug.Assert(additionalChars > _chars.Length - _pos); + GrowCore((uint)_pos + (uint)additionalChars); + } + + /// Grows the size of . + [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible + void Grow() => + // This method is called when the remaining space in _chars isn't sufficient to continue + // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore + // will handle growing by more than that if possible. + GrowCore((uint)_chars.Length + 1); + + /// + /// Grow the size of to at least the specified . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines + void GrowCore(uint requiredMinCapacity) + { + // We want the max of how much space we actually required and doubling our capacity (without going beyond + // the max allowed length). We also want to avoid asking for small arrays, to reduce the number of times we + // need to grow, and since we're working with unsigned ints that could technically overflow if someone tried + // to, for example, append a huge string to a huge string, we also clamp to int.MaxValue. + // Even if the array creation fails in such a case, we may later fail in ToStringAndClear. + + var newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength)); + var arraySize = (int)InternalMath.Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue); + + var newArray = ArrayPool.Shared.Rent(arraySize); + _chars.Slice(0, _pos).CopyTo(newArray); + + var toReturn = _arrayToReturnToPool; + _chars = _arrayToReturnToPool = newArray; + + if (toReturn is not null) + { + ArrayPool.Shared.Return(toReturn); + } + } + + bool TryFormatWithExtensions(T value, ReadOnlySpan format) + { + int charsWritten; + switch (value) + { + case int cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case bool cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten)) + { + Grow(); + } + break; + case byte cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case float cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case double cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case DateTime cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case DateTimeOffset cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case decimal cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case long cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case short cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case ushort cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case uint cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case ulong cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + case sbyte cval: + while (!cval.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) + { + Grow(); + } + break; + default: + return false; + } + + _pos += charsWritten; + return true; + } +} + +[ExcludeFromCodeCoverage] +static file class InternalMath +{ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint Clamp(uint value, uint min, uint max) + { + if (min > max) + { + ThrowMinMaxException(min, max); + } + + if (value < min) + { + return min; + } + else if (value > max) + { + return max; + } + + return value; + } + + [DoesNotReturn] + static void ThrowMinMaxException(T min, T max) => + throw new ArgumentException(string.Format(SR.Argument_MinMaxValue, min, max)); +} + +[ExcludeFromCodeCoverage] +static file class SR +{ + public const string Argument_MinMaxValue = "'{0}' cannot be greater than {1}."; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/ISpanFormattable.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/ISpanFormattable.cs new file mode 100644 index 000000000..85489b421 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/ISpanFormattable.cs @@ -0,0 +1,31 @@ +// +#pragma warning disable + +#if FeatureMemory && !NET6_0_OR_GREATER + +#nullable enable + +namespace System; + +/// Provides functionality to format the string representation of an object into a span. +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.ispanformattable +#if PolyPublic +public +#endif +interface ISpanFormattable : IFormattable +{ + /// Tries to format the value of the current instance into the provided span of characters. + /// When this method returns, this instance's value formatted as a span of characters. + /// When this method returns, the number of characters that were written in . + /// A span containing the characters that represent a standard or custom format string that defines the acceptable format for . + /// An optional object that supplies culture-specific formatting information for . + /// if the formatting was successful; otherwise, . + /// + /// An implementation of this interface should produce the same string of characters as an implementation of + /// on the same type. + /// TryFormat should return false only if there is not enough space in the destination buffer. Any other failures should throw an exception. + /// + bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider); +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs new file mode 100644 index 000000000..26740af6b --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerArgumentAttribute.cs @@ -0,0 +1,45 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using Diagnostics; +using Diagnostics.CodeAnalysis; +using Link = ComponentModel.DescriptionAttribute; + +/// +/// Indicates which arguments to a method involving an interpolated string handler should be passed to that handler. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.interpolatedstringhandlerargumentattribute +#if PolyPublic +public +#endif +sealed class InterpolatedStringHandlerArgumentAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class. + /// + /// The name of the argument that should be passed to the handler. + /// may be used as the name of the receiver in an instance method. + public InterpolatedStringHandlerArgumentAttribute(string argument) => Arguments = [argument]; + + /// + /// Initializes a new instance of the class. + /// + /// The names of the arguments that should be passed to the handler. + /// may be used as the name of the receiver in an instance method. + public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) => Arguments = arguments; + + /// Gets the names of the arguments that should be passed to the handler. + /// + /// may be used as the name of the receiver in an instance method. + /// + public string[] Arguments { get; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs new file mode 100644 index 000000000..f898e8379 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringInterpolation/InterpolatedStringHandlerAttribute.cs @@ -0,0 +1,27 @@ +// +#pragma warning disable + +#if !NET6_0_OR_GREATER + +namespace System.Runtime.CompilerServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Targets = AttributeTargets; + +/// +/// Indicates the attributed type is to be used as an interpolated string handler. +/// +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.interpolatedstringhandlerargumentattribute +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Class | + Targets.Struct, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class InterpolatedStringHandlerAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringPolyfill.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringPolyfill.cs new file mode 100644 index 000000000..8ef4c2153 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringPolyfill.cs @@ -0,0 +1,60 @@ +// +#pragma warning disable + +namespace Polyfills; + +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +static partial class StringPolyfill +{ + /// + /// Concatenates an array of strings, using the specified separator between each member. + /// + //Link: https://learn.microsoft.com/en-us/dotnet/api/system.string.join#system-string-join(system-char-system-string()) + public static string Join(char separator, string[] values) => +#if NETSTANDARD2_0 || NETFRAMEWORK + string.Join(new([separator]), values); +#else + string.Join(separator, 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#system-string-join(system-char-system-object()) + public static string Join(char separator, object[] values) => +#if NETSTANDARD2_0 || NETFRAMEWORK + string.Join(new([separator]), values); +#else + string.Join(separator, values); +#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#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 + string.Join(new([separator]), value, startIndex, count); +#else + string.Join(separator, 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#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]), values); +#else + string.Join(separator, values); +#endif +} \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringSyntaxAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringSyntaxAttribute.cs new file mode 100644 index 000000000..07d0a4827 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/StringSyntaxAttribute.cs @@ -0,0 +1,89 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics.CodeAnalysis; + +using System.Diagnostics; +using Targets = AttributeTargets; + +/// +/// Specifies the syntax used in a string. +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Parameter | + Targets.Field | + Targets.Property)] +#if PolyPublic +public +#endif +sealed class StringSyntaxAttribute : + Attribute +{ + /// + /// Initializes the with the identifier of the syntax used. + /// The syntax identifier. + public StringSyntaxAttribute(string syntax) + { + Syntax = syntax; + Arguments = []; + } + + /// + /// Initializes the with the identifier of the syntax used. + /// The syntax identifier. + /// Optional arguments associated with the specific syntax employed. + public StringSyntaxAttribute(string syntax, params object?[] arguments) + { + Syntax = syntax; + Arguments = arguments; + } + + /// Gets the identifier of the syntax used. + public string Syntax { get; } + + /// Optional arguments associated with the specific syntax employed. + public object?[] Arguments { get; } + + /// The syntax identifier for strings containing composite formats for string formatting. + public const string CompositeFormat = nameof(CompositeFormat); + + /// The syntax identifier for strings containing date format specifiers. + public const string DateOnlyFormat = nameof(DateOnlyFormat); + + /// The syntax identifier for strings containing date and time format specifiers. + public const string DateTimeFormat = nameof(DateTimeFormat); + + /// The syntax identifier for strings containing format specifiers. + public const string EnumFormat = nameof(EnumFormat); + + /// The syntax identifier for strings containing format specifiers. + public const string GuidFormat = nameof(GuidFormat); + + /// The syntax identifier for strings containing JavaScript Object Notation (JSON). + public const string Json = nameof(Json); + + /// The syntax identifier for strings containing numeric format specifiers. + public const string NumericFormat = nameof(NumericFormat); + + /// The syntax identifier for strings containing regular expressions. + public const string Regex = nameof(Regex); + + /// The syntax identifier for strings containing time format specifiers. + public const string TimeOnlyFormat = nameof(TimeOnlyFormat); + + /// The syntax identifier for strings containing format specifiers. + public const string TimeSpanFormat = nameof(TimeSpanFormat); + + /// The syntax identifier for strings containing URIs. + public const string Uri = nameof(Uri); + + /// The syntax identifier for strings containing XML. + public const string Xml = nameof(Xml); +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SuppressGCTransitionAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SuppressGCTransitionAttribute.cs new file mode 100644 index 000000000..809b12ae0 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/SuppressGCTransitionAttribute.cs @@ -0,0 +1,75 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Runtime.InteropServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +/// +/// An attribute used to indicate a GC transition should be skipped when making an unmanaged function call. +/// +/// +/// Example of a valid use case. The Win32 `GetTickCount()` function is a small performance related function +/// that reads some global memory and returns the value. In this case, the GC transition overhead is significantly +/// more than the memory read. +/// +/// using System; +/// using System.Runtime.InteropServices; +/// class Program +/// { +/// [DllImport("Kernel32")] +/// [SuppressGCTransition] +/// static extern int GetTickCount(); +/// static void Main() +/// { +/// Console.WriteLine($"{GetTickCount()}"); +/// } +/// } +/// +/// +/// +/// This attribute is ignored if applied to a method without the . +/// +/// Forgoing this transition can yield benefits when the cost of the transition is more than the execution time +/// of the unmanaged function. However, avoiding this transition removes some of the guarantees the runtime +/// provides through a normal P/Invoke. When exiting the managed runtime to enter an unmanaged function the +/// GC must transition from Cooperative mode into Preemptive mode. Full details on these modes can be found at +/// https://github.com/dotnet/runtime/blob/master/docs/coding-guidelines/clr-code-guide.md#2.1.8. +/// Suppressing the GC transition is an advanced scenario and should not be done without fully understanding +/// potential consequences. +/// +/// One of these consequences is an impact to Mixed-mode debugging (https://docs.microsoft.com/visualstudio/debugger/how-to-debug-in-mixed-mode). +/// During Mixed-mode debugging, it is not possible to step into or set breakpoints in a P/Invoke that +/// has been marked with this attribute. A workaround is to switch to native debugging and set a breakpoint in the native function. +/// In general, usage of this attribute is not recommended if debugging the P/Invoke is important, for example +/// stepping through the native code or diagnosing an exception thrown from the native code. +/// +/// The runtime may load the native library for method marked with this attribute in advance before the method is called for the first time. +/// Usage of this attribute is not recommended for platform neutral libraries with conditional platform specific code. +/// +/// The P/Invoke method that this attribute is applied to must have all of the following properties: +/// * Native function always executes for a trivial amount of time (less than 1 microsecond). +/// * Native function does not perform a blocking syscall (e.g. any type of I/O). +/// * Native function does not call back into the runtime (e.g. Reverse P/Invoke). +/// * Native function does not throw exceptions. +/// * Native function does not manipulate locks or other concurrency primitives. +/// +/// Consequences of invalid uses of this attribute: +/// * GC starvation. +/// * Immediate runtime termination. +/// * Data corruption. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: AttributeTargets.Method, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class SuppressGCTransitionAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/TaskCompletionSource.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/TaskCompletionSource.cs new file mode 100644 index 000000000..a5a3d95db --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/TaskCompletionSource.cs @@ -0,0 +1,227 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics; + +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +/// +/// Represents the producer side of a unbound to a +/// delegate, providing access to the consumer side through the property. +/// +/// +/// +/// It is often the case that a is desired to +/// represent another asynchronous operation. +/// TaskCompletionSource is provided for this purpose. It enables +/// the creation of a task that can be handed out to consumers, and those consumers can use the members +/// of the task as they would any other. However, unlike most tasks, the state of a task created by a +/// TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. This enables the +/// completion of the external asynchronous operation to be propagated to the underlying Task. The +/// separation also ensures that consumers are not able to transition the state without access to the +/// corresponding TaskCompletionSource. +/// +/// +/// All members of are thread-safe +/// and may be used from multiple threads concurrently. +/// +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +//Link: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource +#if PolyPublic +public +#endif +class TaskCompletionSource +{ + TaskCompletionSource inner; + + /// Creates a . + public TaskCompletionSource() => + inner = new TaskCompletionSource(); + + /// Creates a with the specified options. + /// + /// The created by this instance and accessible through its property + /// will be instantiated using the specified . + /// + /// The options to use when creating the underlying . + /// + /// The represent options invalid for use + /// with a . + /// + public TaskCompletionSource(TaskCreationOptions creationOptions) : + this(null, creationOptions) + { + } + + /// Creates a with the specified state. + /// The state to use as the underlying + /// 's AsyncState. + public TaskCompletionSource(object? state) : + this(state, TaskCreationOptions.None) + { + } + + /// Creates a with the specified state and options. + /// The options to use when creating the underlying . + /// The state to use as the underlying 's AsyncState. + /// The represent options invalid for use with a . + public TaskCompletionSource(object? state, TaskCreationOptions creationOptions) => + inner = new(state, creationOptions); + + /// + /// Gets the created + /// by this . + /// + /// + /// This property enables a consumer access to the that is controlled by this instance. + /// The , , , + /// and methods (and their "Try" variants) on this instance all result in the relevant state + /// transitions on this underlying Task. + /// + public Task Task => inner.Task; + + /// Transitions the underlying into the state. + /// The exception to bind to this . + /// The argument is null. + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + public void SetException(Exception exception) => + inner.SetException(exception); + + /// Transitions the underlying into the state. + /// The collection of exceptions to bind to this . + /// The argument is null. + /// There are one or more null elements in . + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + public void SetException(IEnumerable exceptions) => + inner.SetException(exceptions); + + /// + /// Attempts to transition the underlying into the state. + /// + /// The exception to bind to this . + /// True if the operation was successful; otherwise, false. + /// + /// This operation will return false if the is already in one of the three final states: + /// , + /// , or + /// . + /// + /// The argument is null. + public bool TrySetException(Exception exception) => + inner.TrySetException(exception); + + /// + /// Attempts to transition the underlying into the state. + /// + /// The collection of exceptions to bind to this . + /// True if the operation was successful; otherwise, false. + /// + /// This operation will return false if the is already in one of the three final states: + /// , + /// , or + /// . + /// + /// The argument is null. + /// There are one or more null elements in . + /// The collection is empty. + public bool TrySetException(IEnumerable exceptions) => + inner.TrySetException(exceptions); + + /// + /// Transitions the underlying into the state. + /// + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + public void SetResult() => + inner.SetResult(null); + + /// + /// Attempts to transition the underlying into the state. + /// + /// True if the operation was successful; otherwise, false. + /// + /// This operation will return false if the is already in one of the three final states: + /// , + /// , or + /// . + /// + public bool TrySetResult() => + inner.TrySetResult(null); + + /// + /// Transitions the underlying into the state. + /// + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + public void SetCanceled() => SetCanceled(default); + + /// + /// Transitions the underlying into the state + /// using the specified token. + /// + /// The cancellation token with which to cancel the . + /// + /// The underlying is already in one of the three final states: + /// , + /// , or + /// . + /// + public void SetCanceled(CancellationToken cancellationToken) => + inner.SetCanceled(cancellationToken); + + /// + /// Attempts to transition the underlying into the state. + /// + /// True if the operation was successful; otherwise, false. + /// + /// This operation will return false if the is already in one of the three final states: + /// , + /// , or + /// . + /// + public bool TrySetCanceled() => + TrySetCanceled(default); + + /// + /// Attempts to transition the underlying into the state. + /// + /// The cancellation token with which to cancel the . + /// True if the operation was successful; otherwise, false. + /// + /// This operation will return false if the is already in one of the three final states: + /// , + /// , or + /// . + /// + public bool TrySetCanceled(CancellationToken cancellationToken) => + inner.TrySetCanceled(default); +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicDependencyAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicDependencyAttribute.cs new file mode 100644 index 000000000..4c420aa9a --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicDependencyAttribute.cs @@ -0,0 +1,142 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// States a dependency that one member has on another. +/// +/// +/// This can be used to inform tooling of a dependency that is otherwise not evident purely from +/// metadata and IL, for example a member relied on via reflection. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Constructor | + Targets.Field | + Targets.Method, + AllowMultiple = true, Inherited = false)] +#if PolyPublic +public +#endif +sealed class DynamicDependencyAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on the same type as the consumer. + /// + /// The signature of the member depended on. + public DynamicDependencyAttribute(string memberSignature) => + MemberSignature = memberSignature; + + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on a . + /// + /// The signature of the member depended on. + /// The containing . + public DynamicDependencyAttribute(string memberSignature, Type type) + { + MemberSignature = memberSignature; + Type = type; + } + + /// + /// Initializes a new instance of the class + /// with the specified signature of a member on a type in an assembly. + /// + /// The signature of the member depended on. + /// The full name of the type containing the specified member. + /// The assembly name of the type containing the specified member. + public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) + { + MemberSignature = memberSignature; + TypeName = typeName; + AssemblyName = assemblyName; + } + + /// + /// Initializes a new instance of the class + /// with the specified types of members on a . + /// + /// The types of members depended on. + /// The containing the specified members. + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) + { + MemberTypes = memberTypes; + Type = type; + } + + /// + /// Initializes a new instance of the class + /// with the specified types of members on a type in an assembly. + /// + /// The types of members depended on. + /// The full name of the type containing the specified members. + /// The assembly name of the type containing the specified members. + public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) + { + MemberTypes = memberTypes; + TypeName = typeName; + AssemblyName = assemblyName; + } + + /// + /// Gets the signature of the member depended on. + /// + /// + /// Either must be a valid string or + /// must not equal , but not both. + /// + public string? MemberSignature { get; } + + /// + /// Gets the which specifies the type + /// of members depended on. + /// + /// + /// Either must be a valid string or + /// must not equal , but not both. + /// + public DynamicallyAccessedMemberTypes MemberTypes { get; } + + /// + /// Gets the containing the specified member. + /// + /// + /// If neither nor are specified, + /// the type of the consumer is assumed. + /// + public Type? Type { get; } + + /// + /// Gets the full name of the type containing the specified member. + /// + /// + /// If neither nor are specified, + /// the type of the consumer is assumed. + /// + public string? TypeName { get; } + + /// + /// Gets the assembly name of the specified type. + /// + /// + /// is only valid when is specified. + /// + public string? AssemblyName { get; } + + /// + /// Gets or sets the condition in which the dependency is applicable, e.g. "DEBUG". + /// + public string? Condition { get; set; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs new file mode 100644 index 000000000..25480da76 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMemberTypes.cs @@ -0,0 +1,100 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies the types of members that are dynamically accessed. +/// +/// This enumeration has a attribute that allows a +/// bitwise combination of its member values. +/// +[Flags] +#if PolyPublic +public +#endif +enum DynamicallyAccessedMemberTypes +{ + /// + /// Specifies no members. + /// + None = 0, + + /// + /// Specifies the default, parameterless public constructor. + /// + PublicParameterlessConstructor = 0x0001, + + /// + /// Specifies all public constructors. + /// + PublicConstructors = 0x0002 | PublicParameterlessConstructor, + + /// + /// Specifies all non-public constructors. + /// + NonPublicConstructors = 0x0004, + + /// + /// Specifies all public methods. + /// + PublicMethods = 0x0008, + + /// + /// Specifies all non-public methods. + /// + NonPublicMethods = 0x0010, + + /// + /// Specifies all public fields. + /// + PublicFields = 0x0020, + + /// + /// Specifies all non-public fields. + /// + NonPublicFields = 0x0040, + + /// + /// Specifies all public nested types. + /// + PublicNestedTypes = 0x0080, + + /// + /// Specifies all non-public nested types. + /// + NonPublicNestedTypes = 0x0100, + + /// + /// Specifies all public properties. + /// + PublicProperties = 0x0200, + + /// + /// Specifies all non-public properties. + /// + NonPublicProperties = 0x0400, + + /// + /// Specifies all public events. + /// + PublicEvents = 0x0800, + + /// + /// Specifies all non-public events. + /// + NonPublicEvents = 0x1000, + + /// + /// Specifies all interfaces implemented by the type. + /// + Interfaces = 0x2000, + + /// + /// Specifies all members. + /// + All = ~None +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs new file mode 100644 index 000000000..1cda5670f --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/DynamicallyAccessedMembersAttribute.cs @@ -0,0 +1,62 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Indicates that certain members on a specified are accessed dynamically, +/// for example through . +/// +/// +/// This allows tools to understand which members are being accessed during the execution +/// of a program. +/// +/// This attribute is valid on members whose type is or . +/// +/// When this attribute is applied to a location of type , the assumption is +/// that the string represents a fully qualified type name. +/// +/// If the attribute is applied to a method it's treated as a special case and it implies +/// the attribute should be applied to the "this" parameter of the method. As such the attribute +/// should only be used on instance methods of types assignable to System.Type (or string, but no methods +/// will use it there). +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Class | + Targets.Field | + Targets.GenericParameter | + Targets.Interface | + Targets.Method | + Targets.Parameter | + Targets.Property | + Targets.ReturnValue | + Targets.Struct, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class DynamicallyAccessedMembersAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified member types. + /// + /// The types of members dynamically accessed. + public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) => + MemberTypes = memberTypes; + + /// + /// Gets the which specifies the type + /// of members dynamically accessed. + /// + public DynamicallyAccessedMemberTypes MemberTypes { get; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs new file mode 100644 index 000000000..daa730179 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresDynamicCodeAttribute.cs @@ -0,0 +1,53 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Indicates that the specified method requires the ability to generate new code at runtime, +/// for example through . +/// +/// +/// This allows tools to understand which methods are unsafe to call when compiling ahead of time. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Method | + Targets.Constructor | + Targets.Class, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class RequiresDynamicCodeAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of dynamic code. + /// + public RequiresDynamicCodeAttribute(string message) => + Message = message; + + /// + /// Gets a message that contains information about the usage of dynamic code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires dynamic code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs new file mode 100644 index 000000000..f8cb3d519 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/RequiresUnreferencedCodeAttribute.cs @@ -0,0 +1,55 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics.CodeAnalysis; + +using Targets = AttributeTargets; + +/// +/// Indicates that the specified method requires dynamic access to code that is not referenced +/// statically, for example through . +/// +/// +/// This allows tools to understand which methods are unsafe to call when removing unreferenced +/// code from an application. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Method | + Targets.Constructor | + Targets.Class, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class RequiresUnreferencedCodeAttribute : + Attribute +{ + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of unreferenced code. + /// + public RequiresUnreferencedCodeAttribute(string message) => + Message = message; + + /// + /// Gets a message that contains information about the usage of unreferenced code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires unreferenced code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs new file mode 100644 index 000000000..df56e3bd4 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/Trimming/UnconditionalSuppressMessageAttribute.cs @@ -0,0 +1,98 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a +/// single code artifact. +/// +/// +/// is different than +/// in that it doesn't have a +/// . So it is always preserved in the compiled assembly. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: AttributeTargets.All, + Inherited = false, + AllowMultiple = true)] +#if PolyPublic +public +#endif +sealed class UnconditionalSuppressMessageAttribute : + Attribute +{ + /// + /// Initializes a new instance of the + /// class, specifying the category of the tool and the identifier for an analysis rule. + /// + /// The category for the attribute. + /// The identifier of the analysis rule the attribute applies to. + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } + + /// + /// Gets the category identifying the classification of the attribute. + /// + /// + /// The property describes the tool or tool analysis category + /// for which a message suppression attribute applies. + /// + public string Category { get; } + + /// + /// Gets the identifier of the analysis tool rule to be suppressed. + /// + /// + /// Concatenated together, the and + /// properties form a unique check identifier. + /// + public string CheckId { get; } + + /// + /// Gets or sets the scope of the code that is relevant for the attribute. + /// + /// + /// The Scope property is an optional argument that specifies the metadata scope for which + /// the attribute is relevant. + /// + public string? Scope { get; set; } + + /// + /// Gets or sets a fully qualified path that represents the target of the attribute. + /// + /// + /// The property is an optional argument identifying the analysis target + /// of the attribute. An example value is "System.IO.Stream.ctor():System.Void". + /// Because it is fully qualified, it can be long, particularly for targets such as parameters. + /// The analysis tool user interface should be capable of automatically formatting the parameter. + /// + public string? Target { get; set; } + + /// + /// Gets or sets an optional argument expanding on exclusion criteria. + /// + /// + /// The property is an optional argument that specifies additional + /// exclusion where the literal metadata target is not sufficiently precise. For example, + /// the cannot be applied within a method, + /// and it may be desirable to suppress a violation against a statement in the method that will + /// give a rule violation, but not against all statements in the method. + /// + public string? MessageId { get; set; } + + /// + /// Gets or sets the justification for suppressing the code analysis message. + /// + public string? Justification { get; set; } +} +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnmanagedCallersOnlyAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnmanagedCallersOnlyAttribute.cs new file mode 100644 index 000000000..f6b8f67ec --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnmanagedCallersOnlyAttribute.cs @@ -0,0 +1,50 @@ +// +#pragma warning disable + +#if !NET5_0_OR_GREATER + +#nullable enable + +namespace System.Runtime.InteropServices; + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +/// +/// Any method marked with can be directly called from +/// native code. The function token can be loaded to a local variable using the address-of operator +/// in C# and passed as a callback to a native method. +/// +/// +/// Methods marked with this attribute have the following restrictions: +/// * Method must be marked "static". +/// * Must not be called from managed code. +/// * Must only have blittable arguments. +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + AttributeTargets.Method, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class UnmanagedCallersOnlyAttribute : + Attribute +{ + /// + /// Optional. If omitted, the runtime will use the default platform calling convention. + /// + /// + /// Supplied types must be from the official "System.Runtime.CompilerServices" namespace and + /// be of the form "CallConvXXX". + /// + public Type[]? CallConvs; + + /// + /// Optional. If omitted, no named export is emitted during compilation. + /// + public string? EntryPoint; +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnreachableException.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnreachableException.cs new file mode 100644 index 000000000..8b86e7348 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnreachableException.cs @@ -0,0 +1,56 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +#nullable enable + +namespace System.Diagnostics; + +using System; +using System.Diagnostics.CodeAnalysis; + +/// +/// Exception thrown when the program executes an instruction that was thought to be unreachable. +/// +/// +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +#if PolyPublic +public +#endif +sealed class UnreachableException : Exception +{ + /// + /// Initializes a new instance of the class with the default error message. + /// + public UnreachableException() + : base("The program executed an instruction that was thought to be unreachable.") + { + } + + /// + /// Initializes a new instance of the + /// class with a specified error message. + /// + /// The error message that explains the reason for the exception. + public UnreachableException(string? message) + : base(message) + { + } + + /// + /// Initializes a new instance of the + /// class with a specified error message and a reference to the inner exception that is the cause of + /// this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception. + public UnreachableException(string? message, Exception? innerException) + : base(message, innerException) + { + } +} + +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnscopedRefAttribute.cs b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnscopedRefAttribute.cs new file mode 100644 index 000000000..f81d63d87 --- /dev/null +++ b/src/textOnlyPackages/src/polyfill/7.9.1/contentFiles/cs/netstandard2.0/Polyfill/UnscopedRefAttribute.cs @@ -0,0 +1,48 @@ +// +#pragma warning disable + +#if !NET7_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis; + +using System.Diagnostics; + +using Targets = AttributeTargets; + +/// +/// Used to indicate a byref escapes and is not scoped. +/// +/// +/// +/// There are several cases where the C# compiler treats a as implicitly +/// - where the compiler does not allow the to escape the method. +/// +/// +/// For example: +/// +/// for instance methods. +/// parameters that refer to types. +/// parameters. +/// +/// +/// +/// This attribute is used in those instances where the should be allowed to escape. +/// +/// +/// Applying this attribute, in any form, has impact on consumers of the applicable API. It is necessary for +/// API authors to understand the lifetime implications of applying this attribute and how it may impact their users. +/// +/// +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage( + validOn: Targets.Method | + Targets.Property | + Targets.Parameter, + Inherited = false)] +#if PolyPublic +public +#endif +sealed class UnscopedRefAttribute : + Attribute; +#endif \ No newline at end of file diff --git a/src/textOnlyPackages/src/polyfill/7.9.1/icon.png b/src/textOnlyPackages/src/polyfill/7.9.1/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..632a37e2767d2c4b3aa468137ebfd61cbd350a08 GIT binary patch literal 3215 zcmV;A3~=*_P)C$;u1io0 z6r3Ho*5 zU|=XIOU*X0jN1~I5A^7$~53u2V#oYKbt{*hn0Uw z%(izcF;unyG(BMy5}S=O6^K<5L`2!-fyc0Po|w6f7%W)dv zIGw-(2E8Epwb(+wwrv2;)S9#MO|3tS+{>|aaGP;%!?TbrhUJRcQ)O*0%= z(^XcbQIY^O-8ci$CBT3(1B>vEfru{AbkodI67RPO&^Zm0QCUvZ(eoP?suxNs_t?G? z?Nb11HlKu%Uq|%I_bapFBMBrQ~+JQ{rrZg&G$X;(0})da>G+w`?^`Y53s8v z9Tk2cIEr2U=M}rzXAPj~38NtP3Y9(QzYn?*VGGKx3he9yxfJN{j_tnC*{JcRcmAlu z;0RQ|4Kx4;lxZgqda@*QFZaGtq=1c<;`jDR2XH@DY>}8NH7#c<(+y%$Sb-!p|_M^GvS_ z9{{mV_skcpCz)I2p}(StncIeS%4CoS>}JK_vfdx=Er71KdUkl3L7nHzb*p#S%vT}u zUC&&pwpOd^?+YS|%|I$b&E`6c z{O3SF58SOMkv+MV1kjDnnRqN}yo#Og!Lp7Qv+Zx)mxVQe6+hEv4EK9o_yEN86uc?? zn)~(lWY2fM*j6UP7*}xF%j76~A?UsK(mRA&XL#aAbVIGQ{Y6oE)K+?t(LFB<1t9tj z8>ZeTk$c6KbH|X=JaJ=T*6OeS|LBgjKI> zuOAR|O(*cajVy=syy(>g=#bJqv&Du}=a@5LBwdqDUB;-{w!aTPwvqNrJuiAc29`eh zr_yf2sdGro{q|pU11*`V5Bk`k!$#VIp>zLD*H+vg0P;iI?-2eI0Ju8<a1)Eqa^bze1rzXX7h z#m=Bdc?iO_7=vF@v+)F%eN`P_2|yB=O-Sr`kf+`ErlT-;L0cP5T{ ze1}A4Jjj)}UmNs8NU`~gwQ5cX?I@m1O2#toR7f6&`pz4I{R`)WsHl!j}T* zM$8o-N;3B&RHg!-y6o;i(0er9xLj{K=gThp@(f=Kpc_eLmSHgp^l=Z|ok!=c*R-{% z$pc@m69@qSh?(6Y$=tbnYJ-2f>~0vMD>dD4kIt_j?6NOc35)=`kyK_GvG{0^vwUE;E< zc-Q0Njwf99<2Zp90D#<>`$UqtX^5T!eB`pbv-RetgIxCED1jG1Ht)2bDubG+kHYK0E~`>^qLXt0Nb#nNm{c1bl9$EghBwCZn_9$ zlEY?qBXXXY*(xoLafZMPK+Wc_fZpb?SqqhmB$0W_VY{9acmWX0|At-RBC^m?qau%x$h0_Wv&sZk0POC6 z2kn;!4nt?!W_pWmqetZFe;01?l_!( z5RacN=9(`YvR6|CP5`v`y9ID+0m&zb(IB%|*jawOf_R+q<3C0)Y_#pV118bik5=&X82*Ne67zJb`!$P_yv_ zgjtRl6TMCnxrZFF_`23q#ul>Y^w;>pL0I){{iR?_2 z+bc4pjK+v%)f`v){>eThZ~}lmTgarcvkW=JFLo-XS|Bt60FY#MDZ;r_vPXcyc;_OjKA{o-fF!c3 z5N!g=S<00{Qbocn zfbZByZ6U_xL0lUUN&%=jZXk-CQ&R5=TGii8C zzXf_(5Uc)f!YP1K+kfRwN#>q)Ihv{xP64P_Y&m^QEQj&mP87bwVWoz2&T-K(X`xHlyvPhvC!&;pzl-^czFp zqVL2orb}{-i)RVcCZVbUinssrOKDm4g15oc2H_HbNM8cjgtcRi=dsiX;S#{!H9#j= z)5Q#5)!$8M1h8kB*YLs*tJ*xKIE> z>2u&zLa~dMFEBXJM(S;aSqrgq^!ahBjvdPqQ3j&ElBBD}s>693q@-Q&eMz)>g+t>B{ zVDE7NWvR_rj;Fof(nti}q4$jG$L5{)0`)d?uIN4aWp4pUelgfR9#tD@k3Xk#nvS!V zFTyT5xBf^z9`+>Y<@Pi0y)90kk8zrA%78YO5nm_h0~oT1+1d3$J7>3=sM#kSv!zockz2mk z$HmfXx^XdZNkvX0Y6Im@B(vlCs*#Jo46-_}1GcysSA-|*z_4Z(YmSQwK+M(uLX2r( z;{{Pf?V<8BNwmFQ?Djri2TNkr8bp8Yd{hyhpv;$4X7Rp~>~}tZBytN;0=G+c;1M1q znceRwVM!B0B$YK0xrR#i+>h{*1>{eeQOaYut;alVo%ln + + + Polyfill + 7.9.1 + https://github.com/SimonCropp/Polyfill/graphs/contributors + true + false + MIT + https://licenses.nuget.org/MIT + https://github.com/SimonCropp/Polyfill + Source only packages that exposes newer .net and C# features to older runtimes. + + Polyfill + + \ No newline at end of file