repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.CodeGen.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Internal.TypeSystem.Ecma { partial class EcmaField { public override bool IsIntrinsic { get { return (GetFieldFlags(FieldFlags.AttributeMetadataCache | FieldFlags.Intrinsic) & FieldFlags.Intrinsic) != 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Internal.TypeSystem.Ecma { partial class EcmaField { public override bool IsIntrinsic { get { return (GetFieldFlags(FieldFlags.AttributeMetadataCache | FieldFlags.Intrinsic) & FieldFlags.Intrinsic) != 0; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // NOTE: This is a copy of // https://github.com/dotnet/coreclr/blame/07b3afc27304800f00975c8fd4836b319aaa8820/src/System.Private.CoreLib/shared/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs, // modified to be compilable against .NET Standard 2.0. It is missing optimizations present in the .NET Core implementation and should // only be used when a .NET Standard 2.0 implementation is required. Key differences: // - ThrowHelper call sites are replaced by normal exception throws. // - ThreadPool.{Unsafe}QueueUserWorkItem calls that accepted Action<object>/object/bool arguments are replaced by Task.Factory.StartNew usage. // - ExecutionContext.RunInternal are replaced by ExecutionContext.Run. // - Nullability annotations are removed. using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; namespace System.Threading.Tasks.Sources { /// <summary>Provides the core logic for implementing a manual-reset <see cref="IValueTaskSource"/> or <see cref="IValueTaskSource{TResult}"/>.</summary> /// <typeparam name="TResult"></typeparam> [StructLayout(LayoutKind.Auto)] public struct ManualResetValueTaskSourceCore<TResult> { /// <summary> /// The callback to invoke when the operation completes if <see cref="OnCompleted"/> was called before the operation completed, /// or <see cref="ManualResetValueTaskSourceCoreShared.s_sentinel"/> if the operation completed before a callback was supplied, /// or null if a callback hasn't yet been provided and the operation hasn't yet completed. /// </summary> private Action<object> _continuation; /// <summary>State to pass to <see cref="_continuation"/>.</summary> private object _continuationState; /// <summary><see cref="ExecutionContext"/> to flow to the callback, or null if no flowing is required.</summary> private ExecutionContext _executionContext; /// <summary> /// A "captured" <see cref="SynchronizationContext"/> or <see cref="TaskScheduler"/> with which to invoke the callback, /// or null if no special context is required. /// </summary> private object _capturedContext; /// <summary>Whether the current operation has completed.</summary> private bool _completed; /// <summary>The result with which the operation succeeded, or the default value if it hasn't yet completed or failed.</summary> private TResult _result; /// <summary>The exception with which the operation failed, or null if it hasn't yet completed or completed successfully.</summary> private ExceptionDispatchInfo _error; /// <summary>The current version of this value, used to help prevent misuse.</summary> private short _version; /// <summary>Gets or sets whether to force continuations to run asynchronously.</summary> /// <remarks>Continuations may run asynchronously if this is false, but they'll never run synchronously if this is true.</remarks> public bool RunContinuationsAsynchronously { get; set; } /// <summary>Resets to prepare for the next operation.</summary> public void Reset() { // Reset/update state for the next use/await of this instance. _version++; _completed = false; _result = default!; _error = null; _executionContext = null; _capturedContext = null; _continuation = null; _continuationState = null; } /// <summary>Completes with a successful result.</summary> /// <param name="result">The result.</param> public void SetResult(TResult result) { _result = result; SignalCompletion(); } /// <summary>Complets with an error.</summary> /// <param name="error"></param> public void SetException(Exception error) { _error = ExceptionDispatchInfo.Capture(error); SignalCompletion(); } /// <summary>Gets the operation version.</summary> public short Version => _version; /// <summary>Gets the status of the operation.</summary> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> public ValueTaskSourceStatus GetStatus(short token) { ValidateToken(token); return _continuation == null || !_completed ? ValueTaskSourceStatus.Pending : _error == null ? ValueTaskSourceStatus.Succeeded : _error.SourceException is OperationCanceledException ? ValueTaskSourceStatus.Canceled : ValueTaskSourceStatus.Faulted; } /// <summary>Gets the result of the operation.</summary> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> public TResult GetResult(short token) { ValidateToken(token); if (!_completed) { throw new InvalidOperationException(); } _error?.Throw(); return _result; } /// <summary>Schedules the continuation action for this operation.</summary> /// <param name="continuation">The continuation to invoke when the operation has completed.</param> /// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> /// <param name="flags">The flags describing the behavior of the continuation.</param> public void OnCompleted(Action<object> continuation!!, object state, short token, ValueTaskSourceOnCompletedFlags flags) { ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext sc = SynchronizationContext.Current; if (sc != null && sc.GetType() != typeof(SynchronizationContext)) { _capturedContext = sc; } else { TaskScheduler ts = TaskScheduler.Current; if (ts != TaskScheduler.Default) { _capturedContext = ts; } } } // We need to set the continuation state before we swap in the delegate, so that // if there's a race between this and SetResult/Exception and SetResult/Exception // sees the _continuation as non-null, it'll be able to invoke it with the state // stored here. However, this also means that if this is used incorrectly (e.g. // awaited twice concurrently), _continuationState might get erroneously overwritten. // To minimize the chances of that, we check preemptively whether _continuation // is already set to something other than the completion sentinel. object oldContinuation = _continuation; if (oldContinuation == null) { _continuationState = state; oldContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); } if (oldContinuation != null) { // Operation already completed, so we need to queue the supplied callback. if (!ReferenceEquals(oldContinuation, ManualResetValueTaskSourceCoreShared.s_sentinel)) { throw new InvalidOperationException(); } switch (_capturedContext) { case null: Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); break; case SynchronizationContext sc: sc.Post(s => { var tuple = (Tuple<Action<object>, object>)s; tuple.Item1(tuple.Item2); }, Tuple.Create(continuation, state)); break; case TaskScheduler ts: Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); break; } } } /// <summary>Ensures that the specified token matches the current version.</summary> /// <param name="token">The token supplied by <see cref="ValueTask"/>.</param> private void ValidateToken(short token) { if (token != _version) { throw new InvalidOperationException(); } } /// <summary>Signals that the operation has completed. Invoked after the result or error has been set.</summary> private void SignalCompletion() { if (_completed) { throw new InvalidOperationException(); } _completed = true; if (_continuation != null || Interlocked.CompareExchange(ref _continuation, ManualResetValueTaskSourceCoreShared.s_sentinel, null) != null) { if (_executionContext != null) { ExecutionContext.Run( _executionContext, s => ((ManualResetValueTaskSourceCore<TResult>)s).InvokeContinuation(), this); } else { InvokeContinuation(); } } } /// <summary> /// Invokes the continuation with the appropriate captured context / scheduler. /// This assumes that if <see cref="_executionContext"/> is not null we're already /// running within that <see cref="ExecutionContext"/>. /// </summary> private void InvokeContinuation() { Debug.Assert(_continuation != null); switch (_capturedContext) { case null: if (RunContinuationsAsynchronously) { Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { _continuation(_continuationState); } break; case SynchronizationContext sc: sc.Post(s => { var state = (Tuple<Action<object>, object>)s; state.Item1(state.Item2); }, Tuple.Create(_continuation, _continuationState)); break; case TaskScheduler ts: Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); break; } } } internal static class ManualResetValueTaskSourceCoreShared // separated out of generic to avoid unnecessary duplication { internal static readonly Action<object> s_sentinel = CompletionSentinel; private static void CompletionSentinel(object _) // named method to aid debugging { Debug.Fail("The sentinel delegate should never be invoked."); throw new InvalidOperationException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // NOTE: This is a copy of // https://github.com/dotnet/coreclr/blame/07b3afc27304800f00975c8fd4836b319aaa8820/src/System.Private.CoreLib/shared/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs, // modified to be compilable against .NET Standard 2.0. It is missing optimizations present in the .NET Core implementation and should // only be used when a .NET Standard 2.0 implementation is required. Key differences: // - ThrowHelper call sites are replaced by normal exception throws. // - ThreadPool.{Unsafe}QueueUserWorkItem calls that accepted Action<object>/object/bool arguments are replaced by Task.Factory.StartNew usage. // - ExecutionContext.RunInternal are replaced by ExecutionContext.Run. // - Nullability annotations are removed. using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; namespace System.Threading.Tasks.Sources { /// <summary>Provides the core logic for implementing a manual-reset <see cref="IValueTaskSource"/> or <see cref="IValueTaskSource{TResult}"/>.</summary> /// <typeparam name="TResult"></typeparam> [StructLayout(LayoutKind.Auto)] public struct ManualResetValueTaskSourceCore<TResult> { /// <summary> /// The callback to invoke when the operation completes if <see cref="OnCompleted"/> was called before the operation completed, /// or <see cref="ManualResetValueTaskSourceCoreShared.s_sentinel"/> if the operation completed before a callback was supplied, /// or null if a callback hasn't yet been provided and the operation hasn't yet completed. /// </summary> private Action<object> _continuation; /// <summary>State to pass to <see cref="_continuation"/>.</summary> private object _continuationState; /// <summary><see cref="ExecutionContext"/> to flow to the callback, or null if no flowing is required.</summary> private ExecutionContext _executionContext; /// <summary> /// A "captured" <see cref="SynchronizationContext"/> or <see cref="TaskScheduler"/> with which to invoke the callback, /// or null if no special context is required. /// </summary> private object _capturedContext; /// <summary>Whether the current operation has completed.</summary> private bool _completed; /// <summary>The result with which the operation succeeded, or the default value if it hasn't yet completed or failed.</summary> private TResult _result; /// <summary>The exception with which the operation failed, or null if it hasn't yet completed or completed successfully.</summary> private ExceptionDispatchInfo _error; /// <summary>The current version of this value, used to help prevent misuse.</summary> private short _version; /// <summary>Gets or sets whether to force continuations to run asynchronously.</summary> /// <remarks>Continuations may run asynchronously if this is false, but they'll never run synchronously if this is true.</remarks> public bool RunContinuationsAsynchronously { get; set; } /// <summary>Resets to prepare for the next operation.</summary> public void Reset() { // Reset/update state for the next use/await of this instance. _version++; _completed = false; _result = default!; _error = null; _executionContext = null; _capturedContext = null; _continuation = null; _continuationState = null; } /// <summary>Completes with a successful result.</summary> /// <param name="result">The result.</param> public void SetResult(TResult result) { _result = result; SignalCompletion(); } /// <summary>Complets with an error.</summary> /// <param name="error"></param> public void SetException(Exception error) { _error = ExceptionDispatchInfo.Capture(error); SignalCompletion(); } /// <summary>Gets the operation version.</summary> public short Version => _version; /// <summary>Gets the status of the operation.</summary> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> public ValueTaskSourceStatus GetStatus(short token) { ValidateToken(token); return _continuation == null || !_completed ? ValueTaskSourceStatus.Pending : _error == null ? ValueTaskSourceStatus.Succeeded : _error.SourceException is OperationCanceledException ? ValueTaskSourceStatus.Canceled : ValueTaskSourceStatus.Faulted; } /// <summary>Gets the result of the operation.</summary> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> public TResult GetResult(short token) { ValidateToken(token); if (!_completed) { throw new InvalidOperationException(); } _error?.Throw(); return _result; } /// <summary>Schedules the continuation action for this operation.</summary> /// <param name="continuation">The continuation to invoke when the operation has completed.</param> /// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param> /// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param> /// <param name="flags">The flags describing the behavior of the continuation.</param> public void OnCompleted(Action<object> continuation!!, object state, short token, ValueTaskSourceOnCompletedFlags flags) { ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) { _executionContext = ExecutionContext.Capture(); } if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { SynchronizationContext sc = SynchronizationContext.Current; if (sc != null && sc.GetType() != typeof(SynchronizationContext)) { _capturedContext = sc; } else { TaskScheduler ts = TaskScheduler.Current; if (ts != TaskScheduler.Default) { _capturedContext = ts; } } } // We need to set the continuation state before we swap in the delegate, so that // if there's a race between this and SetResult/Exception and SetResult/Exception // sees the _continuation as non-null, it'll be able to invoke it with the state // stored here. However, this also means that if this is used incorrectly (e.g. // awaited twice concurrently), _continuationState might get erroneously overwritten. // To minimize the chances of that, we check preemptively whether _continuation // is already set to something other than the completion sentinel. object oldContinuation = _continuation; if (oldContinuation == null) { _continuationState = state; oldContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null); } if (oldContinuation != null) { // Operation already completed, so we need to queue the supplied callback. if (!ReferenceEquals(oldContinuation, ManualResetValueTaskSourceCoreShared.s_sentinel)) { throw new InvalidOperationException(); } switch (_capturedContext) { case null: Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); break; case SynchronizationContext sc: sc.Post(s => { var tuple = (Tuple<Action<object>, object>)s; tuple.Item1(tuple.Item2); }, Tuple.Create(continuation, state)); break; case TaskScheduler ts: Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); break; } } } /// <summary>Ensures that the specified token matches the current version.</summary> /// <param name="token">The token supplied by <see cref="ValueTask"/>.</param> private void ValidateToken(short token) { if (token != _version) { throw new InvalidOperationException(); } } /// <summary>Signals that the operation has completed. Invoked after the result or error has been set.</summary> private void SignalCompletion() { if (_completed) { throw new InvalidOperationException(); } _completed = true; if (_continuation != null || Interlocked.CompareExchange(ref _continuation, ManualResetValueTaskSourceCoreShared.s_sentinel, null) != null) { if (_executionContext != null) { ExecutionContext.Run( _executionContext, s => ((ManualResetValueTaskSourceCore<TResult>)s).InvokeContinuation(), this); } else { InvokeContinuation(); } } } /// <summary> /// Invokes the continuation with the appropriate captured context / scheduler. /// This assumes that if <see cref="_executionContext"/> is not null we're already /// running within that <see cref="ExecutionContext"/>. /// </summary> private void InvokeContinuation() { Debug.Assert(_continuation != null); switch (_capturedContext) { case null: if (RunContinuationsAsynchronously) { Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { _continuation(_continuationState); } break; case SynchronizationContext sc: sc.Post(s => { var state = (Tuple<Action<object>, object>)s; state.Item1(state.Item2); }, Tuple.Create(_continuation, _continuationState)); break; case TaskScheduler ts: Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, ts); break; } } } internal static class ManualResetValueTaskSourceCoreShared // separated out of generic to avoid unnecessary duplication { internal static readonly Action<object> s_sentinel = CompletionSentinel; private static void CompletionSentinel(object _) // named method to aid debugging { Debug.Fail("The sentinel delegate should never be invoked."); throw new InvalidOperationException(); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/CLR-x86-JIT/V1-QFE/b147814/rembug.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly rembug {} .method public static unmanagedexp int32 modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) main() cil managed { .entrypoint .maxstack 3 .locals (int32* V_0, int32 V_1) ldloca.s V_1 stloc.0 ldloc.0 ldloc.0 ldind.i4 ldc.i4 0x80000000 rem stind.i4 ldc.i4 100 ret }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly rembug {} .method public static unmanagedexp int32 modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl) main() cil managed { .entrypoint .maxstack 3 .locals (int32* V_0, int32 V_1) ldloca.s V_1 stloc.0 ldloc.0 ldloc.0 ldind.i4 ldc.i4 0x80000000 rem stind.i4 ldc.i4 100 ret }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/baseservices/threading/generics/Monitor/EnterExit01.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="EnterExit01.cs" /> <Compile Include="MonitorHelper.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="EnterExit01.cs" /> <Compile Include="MonitorHelper.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Directed/perffix/primitivevt/mixed1_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>False</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="mixed1.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>None</DebugType> <Optimize>False</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Compile Include="mixed1.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Net.Requests/src/System/Net/WebExceptionPal.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http; namespace System.Net { public partial class WebException : InvalidOperationException { internal static WebExceptionStatus GetStatusFromException(HttpRequestException ex) { // For now, we use the .HResult of the exception to help us map to a suitable // WebExceptionStatus enum value. The .HResult is set into this exception by // the underlying .NET Core and .NET Native versions of the System.Net.Http stack. // In the future, the HttpRequestException will have its own .Status property that is // an enum type that is more compatible directly with the WebExceptionStatus enum. return GetStatusFromExceptionHelper(ex); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Http; namespace System.Net { public partial class WebException : InvalidOperationException { internal static WebExceptionStatus GetStatusFromException(HttpRequestException ex) { // For now, we use the .HResult of the exception to help us map to a suitable // WebExceptionStatus enum value. The .HResult is set into this exception by // the underlying .NET Core and .NET Native versions of the System.Net.Http stack. // In the future, the HttpRequestException will have its own .Status property that is // an enum type that is more compatible directly with the WebExceptionStatus enum. return GetStatusFromExceptionHelper(ex); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/Loader/classloader/generics/GenericMethods/method001d.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public class Foo { internal protected T Function<T>(T i) { return i; } } public class Test_method001d { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Foo f = new Foo(); Eval(f.Function<int>(1).Equals(1)); Eval(f.Function<string>("string").Equals("string")); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public class Foo { internal protected T Function<T>(T i) { return i; } } public class Test_method001d { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Foo f = new Foo(); Eval(f.Function<int>(1).Equals(1)); Eval(f.Function<string>("string").Equals("string")); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./eng/common/post-build/post-build-utils.ps1
# Most of the functions in this file require the variables `MaestroApiEndPoint`, # `MaestroApiVersion` and `MaestroApiAccessToken` to be globally available. $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 # `tools.ps1` checks $ci to perform some actions. Since the post-build # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true $disableConfigureToolsetImport = $true . $PSScriptRoot\..\tools.ps1 function Create-MaestroApiRequestHeaders([string]$ContentType = 'application/json') { Validate-MaestroVars $headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $headers.Add('Accept', $ContentType) $headers.Add('Authorization',"Bearer $MaestroApiAccessToken") return $headers } function Get-MaestroChannel([int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}?api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroBuild([int]$BuildId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/builds/${BuildId}?api-version=$MaestroApiVersion" $result = try { return Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroSubscriptions([string]$SourceRepository, [int]$ChannelId) { Validate-MaestroVars $SourceRepository = [System.Web.HttpUtility]::UrlEncode($SourceRepository) $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions?sourceRepository=$SourceRepository&channelId=$ChannelId&api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Assign-BuildToChannel([int]$BuildId, [int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}/builds/${BuildId}?api-version=$MaestroApiVersion" Invoke-WebRequest -Method Post -Uri $apiEndpoint -Headers $apiHeaders | Out-Null } function Trigger-Subscription([string]$SubscriptionId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions/$SubscriptionId/trigger?api-version=$MaestroApiVersion" Invoke-WebRequest -Uri $apiEndpoint -Headers $apiHeaders -Method Post | Out-Null } function Validate-MaestroVars { try { Get-Variable MaestroApiEndPoint | Out-Null Get-Variable MaestroApiVersion | Out-Null Get-Variable MaestroApiAccessToken | Out-Null if (!($MaestroApiEndPoint -Match '^http[s]?://maestro-(int|prod).westus2.cloudapp.azure.com$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiEndPoint is not a valid Maestro URL. '$MaestroApiEndPoint'" ExitWithExitCode 1 } if (!($MaestroApiVersion -Match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiVersion does not match a version string in the format yyyy-MM-DD. '$MaestroApiVersion'" ExitWithExitCode 1 } } catch { Write-PipelineTelemetryError -Category 'MaestroVars' -Message 'Error: Variables `MaestroApiEndPoint`, `MaestroApiVersion` and `MaestroApiAccessToken` are required while using this script.' Write-Host $_ ExitWithExitCode 1 } }
# Most of the functions in this file require the variables `MaestroApiEndPoint`, # `MaestroApiVersion` and `MaestroApiAccessToken` to be globally available. $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 # `tools.ps1` checks $ci to perform some actions. Since the post-build # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true $disableConfigureToolsetImport = $true . $PSScriptRoot\..\tools.ps1 function Create-MaestroApiRequestHeaders([string]$ContentType = 'application/json') { Validate-MaestroVars $headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' $headers.Add('Accept', $ContentType) $headers.Add('Authorization',"Bearer $MaestroApiAccessToken") return $headers } function Get-MaestroChannel([int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}?api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroBuild([int]$BuildId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/builds/${BuildId}?api-version=$MaestroApiVersion" $result = try { return Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Get-MaestroSubscriptions([string]$SourceRepository, [int]$ChannelId) { Validate-MaestroVars $SourceRepository = [System.Web.HttpUtility]::UrlEncode($SourceRepository) $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions?sourceRepository=$SourceRepository&channelId=$ChannelId&api-version=$MaestroApiVersion" $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } return $result } function Assign-BuildToChannel([int]$BuildId, [int]$ChannelId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}/builds/${BuildId}?api-version=$MaestroApiVersion" Invoke-WebRequest -Method Post -Uri $apiEndpoint -Headers $apiHeaders | Out-Null } function Trigger-Subscription([string]$SubscriptionId) { Validate-MaestroVars $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions/$SubscriptionId/trigger?api-version=$MaestroApiVersion" Invoke-WebRequest -Uri $apiEndpoint -Headers $apiHeaders -Method Post | Out-Null } function Validate-MaestroVars { try { Get-Variable MaestroApiEndPoint | Out-Null Get-Variable MaestroApiVersion | Out-Null Get-Variable MaestroApiAccessToken | Out-Null if (!($MaestroApiEndPoint -Match '^http[s]?://maestro-(int|prod).westus2.cloudapp.azure.com$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiEndPoint is not a valid Maestro URL. '$MaestroApiEndPoint'" ExitWithExitCode 1 } if (!($MaestroApiVersion -Match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$')) { Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiVersion does not match a version string in the format yyyy-MM-DD. '$MaestroApiVersion'" ExitWithExitCode 1 } } catch { Write-PipelineTelemetryError -Category 'MaestroVars' -Message 'Error: Variables `MaestroApiEndPoint`, `MaestroApiVersion` and `MaestroApiAccessToken` are required while using this script.' Write-Host $_ ExitWithExitCode 1 } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/SIMD/BoxUnbox.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Numerics; namespace VectorMathTests { class Program { static int Main(string[] args) { { var a = new System.Numerics.Vector<int>(1); object b = a; if (b is System.Numerics.Vector<int>) { var c = (System.Numerics.Vector<int>)b; if (a != c) { return 0; } } else { return 0; } } { var a = new System.Numerics.Vector4(1); object b = a; if (b is System.Numerics.Vector4) { var c = (System.Numerics.Vector4)b; if (a != c) { return 0; } } else { return 0; } } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Numerics; namespace VectorMathTests { class Program { static int Main(string[] args) { { var a = new System.Numerics.Vector<int>(1); object b = a; if (b is System.Numerics.Vector<int>) { var c = (System.Numerics.Vector<int>)b; if (a != c) { return 0; } } else { return 0; } } { var a = new System.Numerics.Vector4(1); object b = a; if (b is System.Numerics.Vector4) { var c = (System.Numerics.Vector4)b; if (a != c) { return 0; } } else { return 0; } } return 100; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/mono/mono/utils/checked-build.c
/** * \file * Expensive asserts used when mono is built with --with-checked-build=yes * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2015 Xamarin */ #include <config.h> #include <mono/utils/mono-compiler.h> #ifdef ENABLE_CHECKED_BUILD #include <mono/utils/checked-build.h> #include <mono/utils/mono-threads.h> #include <mono/utils/mono-threads-coop.h> #include <mono/utils/mono-tls.h> #include <mono/metadata/mempool.h> #include <mono/metadata/metadata-internals.h> #include <mono/metadata/image-internals.h> #include <mono/metadata/loaded-images-internals.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/reflection-internals.h> #include <glib.h> #ifdef HAVE_BACKTRACE_SYMBOLS #include <execinfo.h> #endif // Selective-enable support // Returns true for check modes which are allowed by both the current DISABLE_ macros and the MONO_CHECK_MODE env var. // Argument may be a bitmask; if so, result is true if at least one specified mode is enabled. mono_bool mono_check_mode_enabled (MonoCheckMode query) { static MonoCheckMode check_mode = MONO_CHECK_MODE_UNKNOWN; if (G_UNLIKELY (check_mode == MONO_CHECK_MODE_UNKNOWN)) { MonoCheckMode env_check_mode = MONO_CHECK_MODE_NONE; gchar *env_string = g_getenv ("MONO_CHECK_MODE"); if (env_string) { gchar **env_split = g_strsplit (env_string, ",", 0); for (gchar **env_component = env_split; *env_component; env_component++) { mono_bool G_GNUC_UNUSED check_all = g_str_equal (*env_component, "all"); #ifdef ENABLE_CHECKED_BUILD_GC if (check_all || g_str_equal (*env_component, "gc")) env_check_mode |= MONO_CHECK_MODE_GC; #endif #ifdef ENABLE_CHECKED_BUILD_METADATA if (check_all || g_str_equal (*env_component, "metadata")) env_check_mode |= MONO_CHECK_MODE_METADATA; #endif #ifdef ENABLE_CHECKED_BUILD_THREAD if (check_all || g_str_equal (*env_component, "thread")) env_check_mode |= MONO_CHECK_MODE_THREAD; #endif } g_strfreev (env_split); g_free (env_string); } check_mode = env_check_mode; } return check_mode & query; } static int mono_check_transition_limit (void) { static int transition_limit = -1; if (transition_limit < 0) { gchar *env_string = g_getenv ("MONO_CHECK_THREAD_TRANSITION_HISTORY"); if (env_string) { transition_limit = atoi (env_string); g_free (env_string); } else { transition_limit = 3; } } return transition_limit; } #define MAX_NATIVE_BT 6 #define MAX_NATIVE_BT_PROBE (MAX_NATIVE_BT + 5) #define MAX_TRANSITIONS (mono_check_transition_limit ()) typedef struct { const char *name; int from_state, next_state, suspend_count, suspend_count_delta, size; gpointer backtrace [MAX_NATIVE_BT_PROBE]; } ThreadTransition; typedef struct { guint32 in_gc_critical_region; // ring buffer of transitions, indexed by two guint16 indices: // push at buf_end, iterate from buf_start. valid range is // buf_start ... buf_end - 1 mod MAX_TRANSITIONS gint32 ringbuf; ThreadTransition transitions [MONO_ZERO_LEN_ARRAY]; } CheckState; static MonoNativeTlsKey thread_status; static mono_mutex_t backtrace_mutex; void checked_build_init (void) { // Init state for get_state, which can be called either by gc or thread mode if (mono_check_mode_enabled (MONO_CHECK_MODE_GC | MONO_CHECK_MODE_THREAD)) mono_native_tls_alloc (&thread_status, NULL); #if HAVE_BACKTRACE_SYMBOLS mono_os_mutex_init (&backtrace_mutex); #endif } static gboolean backtrace_mutex_trylock (void) { return mono_os_mutex_trylock (&backtrace_mutex) == 0; } static void backtrace_mutex_unlock (void) { mono_os_mutex_unlock (&backtrace_mutex); } static CheckState* get_state (void) { CheckState *state = (CheckState*)mono_native_tls_get_value (thread_status); if (!state) { state = (CheckState*) g_malloc0 (sizeof (CheckState) + sizeof(ThreadTransition) * MAX_TRANSITIONS); mono_native_tls_set_value (thread_status, state); } return state; } static void ringbuf_unpack (gint32 ringbuf, guint16 *buf_start, guint16 *buf_end) { *buf_start = (guint16) (ringbuf >> 16); *buf_end = (guint16) (ringbuf & 0x00FF); } static gint32 ringbuf_pack (guint16 buf_start, guint16 buf_end) { return ((((gint32)buf_start) << 16) | ((gint32)buf_end)); } static int ringbuf_size (guint32 ringbuf, int n) { guint16 buf_start, buf_end; ringbuf_unpack (ringbuf, &buf_start, &buf_end); if (buf_end > buf_start) return buf_end - buf_start; else return n - (buf_start - buf_end); } static guint16 ringbuf_push (gint32 *ringbuf, int n) { gint32 ringbuf_old, ringbuf_new; guint16 buf_start, buf_end; guint16 cur; retry: ringbuf_old = *ringbuf; ringbuf_unpack (ringbuf_old, &buf_start, &buf_end); cur = buf_end++; if (buf_end == n) buf_end = 0; if (buf_end == buf_start) { if (++buf_start == n) buf_start = 0; } ringbuf_new = ringbuf_pack (buf_start, buf_end); if (mono_atomic_cas_i32 (ringbuf, ringbuf_new, ringbuf_old) != ringbuf_old) goto retry; return cur; } #ifdef ENABLE_CHECKED_BUILD_THREAD #ifdef HAVE_BACKTRACE_SYMBOLS //XXX We should collect just the IPs and lazily symbolificate them. static int collect_backtrace (gpointer out_data[]) { #if defined (__GNUC__) && !defined (__clang__) /* GNU libc backtrace calls _Unwind_Backtrace in libgcc, which internally may take a lock. */ /* Suppose we're using hybrid suspend and T1 is in GC Unsafe and T2 is * GC Safe. T1 will be coop suspended, and T2 will be async suspended. * Suppose T1 is in RUNNING, and T2 just changed from RUNNING to * BLOCKING and it is in trace_state_change to record this fact. * * suspend initiator: switches T1 to ASYNC_SUSPEND_REQUESTED * suspend initiator: switches T2 to BLOCKING_SUSPEND_REQUESTED and sends a suspend signal * T1: calls mono_threads_transition_state_poll (), * T1: switches to SELF_SUSPENDED and starts trace_state_change () * T2: is still in checked_build_thread_transition for the RUNNING->BLOCKING transition and calls backtrace () * T2: suspend signal lands while T2 is in backtrace() holding a lock; T2 switches to BLOCKING_ASYNC_SUSPENDED () and waits for resume * T1: calls backtrace (), waits for the lock () * suspend initiator: waiting for T1 to suspend. * * At this point we're deadlocked. * * So what we'll do is try to take a lock before calling backtrace and * only collect a backtrace if there is no contention. */ int i; for (i = 0; i < 2; i++ ) { if (backtrace_mutex_trylock ()) { int sz = backtrace (out_data, MAX_NATIVE_BT_PROBE); backtrace_mutex_unlock (); return sz; } else { mono_thread_info_yield (); } } /* didn't get a backtrace, oh well. */ return 0; #else return backtrace (out_data, MAX_NATIVE_BT_PROBE); #endif } static char* translate_backtrace (gpointer native_trace[], int size) { if (size == 0) return g_strdup (""); char **names = backtrace_symbols (native_trace, size); GString* bt = g_string_sized_new (100); int i, j = -1; //Figure out the cut point of useless backtraces //We'll skip up to the caller of checked_build_thread_transition for (i = 0; i < size; ++i) { if (strstr (names [i], "checked_build_thread_transition")) { j = i + 1; break; } } if (j == -1) j = 0; for (i = j; i < size; ++i) { if (i - j <= MAX_NATIVE_BT) g_string_append_printf (bt, "\tat %s\n", names [i]); } g_free (names); return g_string_free (bt, FALSE); } #else static int collect_backtrace (gpointer out_data[]) { return 0; } static char* translate_backtrace (gpointer native_trace[], int size) { return g_strdup ("\tno backtrace available\n"); } #endif void checked_build_thread_transition (const char *transition, void *info, int from_state, int suspend_count, int next_state, int suspend_count_delta, gboolean capture_backtrace) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_THREAD)) return; /* We currently don't record external changes as those are hard to reason about. */ if (!mono_thread_info_is_current ((THREAD_INFO_TYPE*)info)) return; CheckState *state = get_state (); guint16 cur = ringbuf_push (&state->ringbuf, MAX_TRANSITIONS); ThreadTransition *t = &state->transitions[cur]; t->name = transition; t->from_state = from_state; t->next_state = next_state; t->suspend_count = suspend_count; t->suspend_count_delta = suspend_count_delta; if (capture_backtrace) t->size = collect_backtrace (t->backtrace); else t->size = 0; } void mono_fatal_with_history (const char * volatile msg, ...) { GString* err = g_string_sized_new (100); g_string_append_printf (err, "Assertion failure in thread %p due to: ", mono_native_thread_id_get ()); va_list args; va_start (args, msg); g_string_append_vprintf (err, msg, args); va_end (args); if (mono_check_mode_enabled (MONO_CHECK_MODE_THREAD)) { CheckState *state = get_state (); guint16 cur, end; int len = ringbuf_size (state->ringbuf, MAX_TRANSITIONS); g_string_append_printf (err, "\nLast %d state transitions: (most recent first)\n", len); ringbuf_unpack (state->ringbuf, &cur, &end); while (cur != end) { ThreadTransition *t = &state->transitions[cur]; char *bt = translate_backtrace (t->backtrace, t->size); g_string_append_printf (err, "[%s] %s -> %s (%d) %s%d at:\n%s", t->name, mono_thread_state_name (t->from_state), mono_thread_state_name (t->next_state), t->suspend_count, t->suspend_count_delta > 0 ? "+" : "", //I'd like to see this sort of values: -1, 0, +1 t->suspend_count_delta, bt); g_free (bt); if (++cur == MAX_TRANSITIONS) cur = 0; } } g_error (err->str); g_string_free (err, TRUE); } #endif /* defined(ENABLE_CHECKED_BUILD_THREAD) */ #ifdef ENABLE_CHECKED_BUILD_GC void assert_gc_safe_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Safe mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_BLOCKING: case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Safe mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void assert_gc_unsafe_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Unsafe mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Unsafe mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void assert_gc_neutral_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Neutral mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING: case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Neutral mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void * critical_gc_region_begin(void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return NULL; CheckState *state = get_state (); state->in_gc_critical_region++; return state; } void critical_gc_region_end(void* token) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); g_assert (state == token); state->in_gc_critical_region--; } void assert_not_in_gc_critical_region(void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); if (state->in_gc_critical_region > 0) { mono_fatal_with_history("Expected GC Unsafe mode, but was in %s state", mono_thread_state_name (mono_thread_info_current_state (mono_thread_info_current ()))); } } void assert_in_gc_critical_region (void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); if (state->in_gc_critical_region == 0) mono_fatal_with_history("Expected GC critical region"); } #endif /* defined(ENABLE_CHECKED_BUILD_GC) */ #ifdef ENABLE_CHECKED_BUILD_METADATA // check_metadata_store et al: The goal of these functions is to verify that if there is a pointer from one mempool into // another, that the pointed-to memory is protected by the reference count mechanism for MonoImages. // // Note: The code below catches only some kinds of failures. Failures outside its scope notably incode: // * Code below absolutely assumes that no mempool is ever held as "mempool" member by more than one Image or ImageSet at once // * Code below assumes reference counts never underflow (ie: if we have a pointer to something, it won't be deallocated while we're looking at it) // Locking strategy is a little slapdash overall. // Reference audit support #define check_mempool_assert_message(...) \ g_assertion_message("Mempool reference violation: " __VA_ARGS__) typedef struct { MonoImage *image; MonoImageSet *image_set; } MonoMemPoolOwner; static MonoMemPoolOwner mono_mempool_no_owner = {NULL,NULL}; static gboolean check_mempool_owner_eq (MonoMemPoolOwner a, MonoMemPoolOwner b) { return a.image == b.image && a.image_set == b.image_set; } // Say image X "references" image Y if X either contains Y in its modules field, or X’s "references" field contains an // assembly whose image is Y. // Say image X transitively references image Y if there is any chain of images-referencing-images which leads from X to Y. // Once the mempools for two pointers have been looked up, there are four possibilities: // Case 1. Image FROM points to Image TO: Legal if FROM transitively references TO // We'll do a simple BFS graph search on images. For each image we visit: static void check_image_search (GHashTable *visited, GPtrArray *next, MonoImage *candidate, MonoImage *goal, gboolean *success) { // Image hasn't even been loaded-- ignore it if (!candidate) return; // Image has already been visited-- ignore it if (g_hash_table_lookup_extended (visited, candidate, NULL, NULL)) return; // Image is the target-- mark success if (candidate == goal) { *success = TRUE; return; } // Unvisited image, queue it to have its children visited g_hash_table_insert (visited, candidate, NULL); g_ptr_array_add (next, candidate); return; } static gboolean check_image_may_reference_image(MonoImage *from, MonoImage *to) { if (to == from) // Shortcut return TRUE; // Corlib is never unloaded, and all images implicitly reference it. // Some images avoid explicitly referencing it as an optimization, so special-case it here. if (to == mono_defaults.corlib) return TRUE; // Non-dynamic images may NEVER reference dynamic images if (to->dynamic && !from->dynamic) return FALSE; // FIXME: We currently give a dynamic images a pass on the reference rules. // Dynamic images may ALWAYS reference non-dynamic images. // We allow this because the dynamic image code is known "messy", and in theory it is already // protected because dynamic images can only reference classes their assembly has retained. // However, long term, we should make this rigorous. if (from->dynamic && !to->dynamic) return TRUE; gboolean success = FALSE; // Images to inspect on this pass, images to inspect on the next pass GPtrArray *current = g_ptr_array_sized_new (1), *next = g_ptr_array_new (); // Because in practice the image graph contains cycles, we must track which images we've visited GHashTable *visited = g_hash_table_new (NULL, NULL); #define CHECK_IMAGE_VISIT(i) check_image_search (visited, next, (i), to, &success) CHECK_IMAGE_VISIT (from); // Initially "next" contains only from node // For each pass exhaust the "to check" queue while filling up the "check next" queue while (!success && next->len > 0) // Halt on success or when out of nodes to process { // Swap "current" and "next" and clear next GPtrArray *temp = current; current = next; next = temp; g_ptr_array_set_size (next, 0); int current_idx; for(current_idx = 0; current_idx < current->len; current_idx++) { MonoImage *checking = (MonoImage*)g_ptr_array_index (current, current_idx); mono_image_lock (checking); // For each queued image visit all directly referenced images int inner_idx; // 'files' and 'modules' semantically contain the same items but because of lazy loading we must check both for (inner_idx = 0; !success && inner_idx < checking->file_count; inner_idx++) { CHECK_IMAGE_VISIT (checking->files[inner_idx]); } for (inner_idx = 0; !success && inner_idx < checking->module_count; inner_idx++) { CHECK_IMAGE_VISIT (checking->modules[inner_idx]); } for (inner_idx = 0; !success && inner_idx < checking->nreferences; inner_idx++) { // Assembly references are lazy-loaded and thus allowed to be NULL. // If they are NULL, we don't care about them for this search, because their images haven't impacted ref_count yet. if (checking->references[inner_idx]) { CHECK_IMAGE_VISIT (checking->references[inner_idx]->image); } } mono_image_unlock (checking); } } g_ptr_array_free (current, TRUE); g_ptr_array_free (next, TRUE); g_hash_table_destroy (visited); return success; } // Case 2. ImageSet FROM points to Image TO: One of FROM's "images" either is, or transitively references, TO. static gboolean check_image_set_may_reference_image (MonoImageSet *from, MonoImage *to) { // See above-- All images implicitly reference corlib if (to == mono_defaults.corlib) return TRUE; int idx; gboolean success = FALSE; mono_image_set_lock (from); for (idx = 0; !success && idx < from->nimages; idx++) { if (check_image_may_reference_image (from->images[idx], to)) success = TRUE; } mono_image_set_unlock (from); return success; // No satisfying image found in from->images } // Case 3. ImageSet FROM points to ImageSet TO: The images in TO are a strict subset of FROM (no transitive relationship is important here) static gboolean check_image_set_may_reference_image_set (MonoImageSet *from, MonoImageSet *to) { if (to == from) return TRUE; gboolean valid = TRUE; // Until proven otherwise mono_image_set_lock (from); mono_image_set_lock (to); int to_idx, from_idx; for (to_idx = 0; valid && to_idx < to->nimages; to_idx++) { gboolean seen = FALSE; // If TO set includes corlib, the FROM set may // implicitly reference corlib, even if it's not // present in the set explicitly. if (to->images[to_idx] == mono_defaults.corlib) seen = TRUE; // For each item in to->images, scan over from->images seeking a path to it. for (from_idx = 0; !seen && from_idx < from->nimages; from_idx++) { if (check_image_may_reference_image (from->images[from_idx], to->images[to_idx])) seen = TRUE; } // If the to->images item is not found in from->images, the subset check has failed if (!seen) valid = FALSE; } mono_image_set_unlock (from); mono_image_set_unlock (to); return valid; // All items in "to" were found in "from" } // Case 4. Image FROM points to ImageSet TO: FROM transitively references *ALL* of the “images” listed in TO static gboolean check_image_may_reference_image_set (MonoImage *from, MonoImageSet *to) { if (to->nimages == 0) // Malformed image_set return FALSE; gboolean valid = TRUE; mono_image_set_lock (to); int idx; for (idx = 0; valid && idx < to->nimages; idx++) { if (!check_image_may_reference_image (from, to->images[idx])) valid = FALSE; } mono_image_set_unlock (to); return valid; // All images in to->images checked out } // Small helper-- get a descriptive string for a MonoMemPoolOwner // Callers are obligated to free buffer with g_free after use static const char * check_mempool_owner_name (MonoMemPoolOwner owner) { GString *result = g_string_new (NULL); if (owner.image) { if (owner.image->dynamic) g_string_append (result, "(Dynamic)"); g_string_append (result, owner.image->name); } else if (owner.image_set) { char *temp = mono_image_set_description (owner.image_set); g_string_append (result, "(Image set)"); g_string_append (result, temp); g_free (temp); } else { g_string_append (result, "(Non-image memory)"); } return g_string_free (result, FALSE); } // Helper -- surf various image-locating functions looking for the owner of this pointer static MonoMemPoolOwner mono_find_mempool_owner (void *ptr) { MonoMemPoolOwner owner = mono_mempool_no_owner; owner.image = mono_find_image_owner (ptr); if (!check_mempool_owner_eq (owner, mono_mempool_no_owner)) return owner; owner.image_set = mono_find_image_set_owner (ptr); if (!check_mempool_owner_eq (owner, mono_mempool_no_owner)) return owner; owner.image = mono_find_dynamic_image_owner (ptr); return owner; } // Actually perform reference audit static void check_mempool_may_reference_mempool (void *from_ptr, void *to_ptr, gboolean require_local) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_METADATA)) return; // Null pointers are OK if (!to_ptr) return; MonoMemPoolOwner from = mono_find_mempool_owner (from_ptr), to = mono_find_mempool_owner (to_ptr); if (require_local) { if (!check_mempool_owner_eq (from,to)) check_mempool_assert_message ("Pointer in image %s should have been internal, but instead pointed to image %s", check_mempool_owner_name (from), check_mempool_owner_name (to)); } // Writing into unknown mempool else if (check_mempool_owner_eq (from, mono_mempool_no_owner)) { check_mempool_assert_message ("Non-image memory attempting to write pointer to image %s", check_mempool_owner_name (to)); } // Reading from unknown mempool else if (check_mempool_owner_eq (to, mono_mempool_no_owner)) { check_mempool_assert_message ("Attempting to write pointer from image %s to non-image memory", check_mempool_owner_name (from)); } // Split out the four cases described above: else if (from.image && to.image) { if (!check_image_may_reference_image (from.image, to.image)) check_mempool_assert_message ("Image %s tried to point to image %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image && to.image_set) { if (!check_image_may_reference_image_set (from.image, to.image_set)) check_mempool_assert_message ("Image %s tried to point to image set %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image_set && to.image_set) { if (!check_image_set_may_reference_image_set (from.image_set, to.image_set)) check_mempool_assert_message ("Image set %s tried to point to image set %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image_set && to.image) { if (!check_image_set_may_reference_image (from.image_set, to.image)) check_mempool_assert_message ("Image set %s tried to point to image %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else { check_mempool_assert_message ("Internal logic error: Unreachable code"); } } void check_metadata_store (void *from, void *to) { check_mempool_may_reference_mempool (from, to, FALSE); } void check_metadata_store_local (void *from, void *to) { check_mempool_may_reference_mempool (from, to, TRUE); } #endif /* defined(ENABLE_CHECKED_BUILD_METADATA) */ #else /* ENABLE_CHECKED_BUILD */ MONO_EMPTY_SOURCE_FILE (checked_build); #endif /* ENABLE_CHECKED_BUILD */
/** * \file * Expensive asserts used when mono is built with --with-checked-build=yes * * Author: * Rodrigo Kumpera ([email protected]) * * (C) 2015 Xamarin */ #include <config.h> #include <mono/utils/mono-compiler.h> #ifdef ENABLE_CHECKED_BUILD #include <mono/utils/checked-build.h> #include <mono/utils/mono-threads.h> #include <mono/utils/mono-threads-coop.h> #include <mono/utils/mono-tls.h> #include <mono/metadata/mempool.h> #include <mono/metadata/metadata-internals.h> #include <mono/metadata/image-internals.h> #include <mono/metadata/loaded-images-internals.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/reflection-internals.h> #include <glib.h> #ifdef HAVE_BACKTRACE_SYMBOLS #include <execinfo.h> #endif // Selective-enable support // Returns true for check modes which are allowed by both the current DISABLE_ macros and the MONO_CHECK_MODE env var. // Argument may be a bitmask; if so, result is true if at least one specified mode is enabled. mono_bool mono_check_mode_enabled (MonoCheckMode query) { static MonoCheckMode check_mode = MONO_CHECK_MODE_UNKNOWN; if (G_UNLIKELY (check_mode == MONO_CHECK_MODE_UNKNOWN)) { MonoCheckMode env_check_mode = MONO_CHECK_MODE_NONE; gchar *env_string = g_getenv ("MONO_CHECK_MODE"); if (env_string) { gchar **env_split = g_strsplit (env_string, ",", 0); for (gchar **env_component = env_split; *env_component; env_component++) { mono_bool G_GNUC_UNUSED check_all = g_str_equal (*env_component, "all"); #ifdef ENABLE_CHECKED_BUILD_GC if (check_all || g_str_equal (*env_component, "gc")) env_check_mode |= MONO_CHECK_MODE_GC; #endif #ifdef ENABLE_CHECKED_BUILD_METADATA if (check_all || g_str_equal (*env_component, "metadata")) env_check_mode |= MONO_CHECK_MODE_METADATA; #endif #ifdef ENABLE_CHECKED_BUILD_THREAD if (check_all || g_str_equal (*env_component, "thread")) env_check_mode |= MONO_CHECK_MODE_THREAD; #endif } g_strfreev (env_split); g_free (env_string); } check_mode = env_check_mode; } return check_mode & query; } static int mono_check_transition_limit (void) { static int transition_limit = -1; if (transition_limit < 0) { gchar *env_string = g_getenv ("MONO_CHECK_THREAD_TRANSITION_HISTORY"); if (env_string) { transition_limit = atoi (env_string); g_free (env_string); } else { transition_limit = 3; } } return transition_limit; } #define MAX_NATIVE_BT 6 #define MAX_NATIVE_BT_PROBE (MAX_NATIVE_BT + 5) #define MAX_TRANSITIONS (mono_check_transition_limit ()) typedef struct { const char *name; int from_state, next_state, suspend_count, suspend_count_delta, size; gpointer backtrace [MAX_NATIVE_BT_PROBE]; } ThreadTransition; typedef struct { guint32 in_gc_critical_region; // ring buffer of transitions, indexed by two guint16 indices: // push at buf_end, iterate from buf_start. valid range is // buf_start ... buf_end - 1 mod MAX_TRANSITIONS gint32 ringbuf; ThreadTransition transitions [MONO_ZERO_LEN_ARRAY]; } CheckState; static MonoNativeTlsKey thread_status; static mono_mutex_t backtrace_mutex; void checked_build_init (void) { // Init state for get_state, which can be called either by gc or thread mode if (mono_check_mode_enabled (MONO_CHECK_MODE_GC | MONO_CHECK_MODE_THREAD)) mono_native_tls_alloc (&thread_status, NULL); #if HAVE_BACKTRACE_SYMBOLS mono_os_mutex_init (&backtrace_mutex); #endif } static gboolean backtrace_mutex_trylock (void) { return mono_os_mutex_trylock (&backtrace_mutex) == 0; } static void backtrace_mutex_unlock (void) { mono_os_mutex_unlock (&backtrace_mutex); } static CheckState* get_state (void) { CheckState *state = (CheckState*)mono_native_tls_get_value (thread_status); if (!state) { state = (CheckState*) g_malloc0 (sizeof (CheckState) + sizeof(ThreadTransition) * MAX_TRANSITIONS); mono_native_tls_set_value (thread_status, state); } return state; } static void ringbuf_unpack (gint32 ringbuf, guint16 *buf_start, guint16 *buf_end) { *buf_start = (guint16) (ringbuf >> 16); *buf_end = (guint16) (ringbuf & 0x00FF); } static gint32 ringbuf_pack (guint16 buf_start, guint16 buf_end) { return ((((gint32)buf_start) << 16) | ((gint32)buf_end)); } static int ringbuf_size (guint32 ringbuf, int n) { guint16 buf_start, buf_end; ringbuf_unpack (ringbuf, &buf_start, &buf_end); if (buf_end > buf_start) return buf_end - buf_start; else return n - (buf_start - buf_end); } static guint16 ringbuf_push (gint32 *ringbuf, int n) { gint32 ringbuf_old, ringbuf_new; guint16 buf_start, buf_end; guint16 cur; retry: ringbuf_old = *ringbuf; ringbuf_unpack (ringbuf_old, &buf_start, &buf_end); cur = buf_end++; if (buf_end == n) buf_end = 0; if (buf_end == buf_start) { if (++buf_start == n) buf_start = 0; } ringbuf_new = ringbuf_pack (buf_start, buf_end); if (mono_atomic_cas_i32 (ringbuf, ringbuf_new, ringbuf_old) != ringbuf_old) goto retry; return cur; } #ifdef ENABLE_CHECKED_BUILD_THREAD #ifdef HAVE_BACKTRACE_SYMBOLS //XXX We should collect just the IPs and lazily symbolificate them. static int collect_backtrace (gpointer out_data[]) { #if defined (__GNUC__) && !defined (__clang__) /* GNU libc backtrace calls _Unwind_Backtrace in libgcc, which internally may take a lock. */ /* Suppose we're using hybrid suspend and T1 is in GC Unsafe and T2 is * GC Safe. T1 will be coop suspended, and T2 will be async suspended. * Suppose T1 is in RUNNING, and T2 just changed from RUNNING to * BLOCKING and it is in trace_state_change to record this fact. * * suspend initiator: switches T1 to ASYNC_SUSPEND_REQUESTED * suspend initiator: switches T2 to BLOCKING_SUSPEND_REQUESTED and sends a suspend signal * T1: calls mono_threads_transition_state_poll (), * T1: switches to SELF_SUSPENDED and starts trace_state_change () * T2: is still in checked_build_thread_transition for the RUNNING->BLOCKING transition and calls backtrace () * T2: suspend signal lands while T2 is in backtrace() holding a lock; T2 switches to BLOCKING_ASYNC_SUSPENDED () and waits for resume * T1: calls backtrace (), waits for the lock () * suspend initiator: waiting for T1 to suspend. * * At this point we're deadlocked. * * So what we'll do is try to take a lock before calling backtrace and * only collect a backtrace if there is no contention. */ int i; for (i = 0; i < 2; i++ ) { if (backtrace_mutex_trylock ()) { int sz = backtrace (out_data, MAX_NATIVE_BT_PROBE); backtrace_mutex_unlock (); return sz; } else { mono_thread_info_yield (); } } /* didn't get a backtrace, oh well. */ return 0; #else return backtrace (out_data, MAX_NATIVE_BT_PROBE); #endif } static char* translate_backtrace (gpointer native_trace[], int size) { if (size == 0) return g_strdup (""); char **names = backtrace_symbols (native_trace, size); GString* bt = g_string_sized_new (100); int i, j = -1; //Figure out the cut point of useless backtraces //We'll skip up to the caller of checked_build_thread_transition for (i = 0; i < size; ++i) { if (strstr (names [i], "checked_build_thread_transition")) { j = i + 1; break; } } if (j == -1) j = 0; for (i = j; i < size; ++i) { if (i - j <= MAX_NATIVE_BT) g_string_append_printf (bt, "\tat %s\n", names [i]); } g_free (names); return g_string_free (bt, FALSE); } #else static int collect_backtrace (gpointer out_data[]) { return 0; } static char* translate_backtrace (gpointer native_trace[], int size) { return g_strdup ("\tno backtrace available\n"); } #endif void checked_build_thread_transition (const char *transition, void *info, int from_state, int suspend_count, int next_state, int suspend_count_delta, gboolean capture_backtrace) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_THREAD)) return; /* We currently don't record external changes as those are hard to reason about. */ if (!mono_thread_info_is_current ((THREAD_INFO_TYPE*)info)) return; CheckState *state = get_state (); guint16 cur = ringbuf_push (&state->ringbuf, MAX_TRANSITIONS); ThreadTransition *t = &state->transitions[cur]; t->name = transition; t->from_state = from_state; t->next_state = next_state; t->suspend_count = suspend_count; t->suspend_count_delta = suspend_count_delta; if (capture_backtrace) t->size = collect_backtrace (t->backtrace); else t->size = 0; } void mono_fatal_with_history (const char * volatile msg, ...) { GString* err = g_string_sized_new (100); g_string_append_printf (err, "Assertion failure in thread %p due to: ", mono_native_thread_id_get ()); va_list args; va_start (args, msg); g_string_append_vprintf (err, msg, args); va_end (args); if (mono_check_mode_enabled (MONO_CHECK_MODE_THREAD)) { CheckState *state = get_state (); guint16 cur, end; int len = ringbuf_size (state->ringbuf, MAX_TRANSITIONS); g_string_append_printf (err, "\nLast %d state transitions: (most recent first)\n", len); ringbuf_unpack (state->ringbuf, &cur, &end); while (cur != end) { ThreadTransition *t = &state->transitions[cur]; char *bt = translate_backtrace (t->backtrace, t->size); g_string_append_printf (err, "[%s] %s -> %s (%d) %s%d at:\n%s", t->name, mono_thread_state_name (t->from_state), mono_thread_state_name (t->next_state), t->suspend_count, t->suspend_count_delta > 0 ? "+" : "", //I'd like to see this sort of values: -1, 0, +1 t->suspend_count_delta, bt); g_free (bt); if (++cur == MAX_TRANSITIONS) cur = 0; } } g_error (err->str); g_string_free (err, TRUE); } #endif /* defined(ENABLE_CHECKED_BUILD_THREAD) */ #ifdef ENABLE_CHECKED_BUILD_GC void assert_gc_safe_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Safe mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_BLOCKING: case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Safe mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void assert_gc_unsafe_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Unsafe mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Unsafe mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void assert_gc_neutral_mode (const char *file, int lineno) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; MonoThreadInfo *cur = mono_thread_info_current (); if (!cur) mono_fatal_with_history ("%s:%d: Expected GC Neutral mode but thread is not attached", file, lineno); int state = mono_thread_info_current_state (cur); switch (state) { case STATE_RUNNING: case STATE_ASYNC_SUSPEND_REQUESTED: case STATE_BLOCKING: case STATE_BLOCKING_SELF_SUSPENDED: case STATE_BLOCKING_SUSPEND_REQUESTED: break; default: mono_fatal_with_history ("%s:%d: Expected GC Neutral mode but was in %s state", file, lineno, mono_thread_state_name (state)); } } void * critical_gc_region_begin(void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return NULL; CheckState *state = get_state (); state->in_gc_critical_region++; return state; } void critical_gc_region_end(void* token) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); g_assert (state == token); state->in_gc_critical_region--; } void assert_not_in_gc_critical_region(void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); if (state->in_gc_critical_region > 0) { mono_fatal_with_history("Expected GC Unsafe mode, but was in %s state", mono_thread_state_name (mono_thread_info_current_state (mono_thread_info_current ()))); } } void assert_in_gc_critical_region (void) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_GC)) return; CheckState *state = get_state(); if (state->in_gc_critical_region == 0) mono_fatal_with_history("Expected GC critical region"); } #endif /* defined(ENABLE_CHECKED_BUILD_GC) */ #ifdef ENABLE_CHECKED_BUILD_METADATA // check_metadata_store et al: The goal of these functions is to verify that if there is a pointer from one mempool into // another, that the pointed-to memory is protected by the reference count mechanism for MonoImages. // // Note: The code below catches only some kinds of failures. Failures outside its scope notably incode: // * Code below absolutely assumes that no mempool is ever held as "mempool" member by more than one Image or ImageSet at once // * Code below assumes reference counts never underflow (ie: if we have a pointer to something, it won't be deallocated while we're looking at it) // Locking strategy is a little slapdash overall. // Reference audit support #define check_mempool_assert_message(...) \ g_assertion_message("Mempool reference violation: " __VA_ARGS__) typedef struct { MonoImage *image; MonoImageSet *image_set; } MonoMemPoolOwner; static MonoMemPoolOwner mono_mempool_no_owner = {NULL,NULL}; static gboolean check_mempool_owner_eq (MonoMemPoolOwner a, MonoMemPoolOwner b) { return a.image == b.image && a.image_set == b.image_set; } // Say image X "references" image Y if X either contains Y in its modules field, or X’s "references" field contains an // assembly whose image is Y. // Say image X transitively references image Y if there is any chain of images-referencing-images which leads from X to Y. // Once the mempools for two pointers have been looked up, there are four possibilities: // Case 1. Image FROM points to Image TO: Legal if FROM transitively references TO // We'll do a simple BFS graph search on images. For each image we visit: static void check_image_search (GHashTable *visited, GPtrArray *next, MonoImage *candidate, MonoImage *goal, gboolean *success) { // Image hasn't even been loaded-- ignore it if (!candidate) return; // Image has already been visited-- ignore it if (g_hash_table_lookup_extended (visited, candidate, NULL, NULL)) return; // Image is the target-- mark success if (candidate == goal) { *success = TRUE; return; } // Unvisited image, queue it to have its children visited g_hash_table_insert (visited, candidate, NULL); g_ptr_array_add (next, candidate); return; } static gboolean check_image_may_reference_image(MonoImage *from, MonoImage *to) { if (to == from) // Shortcut return TRUE; // Corlib is never unloaded, and all images implicitly reference it. // Some images avoid explicitly referencing it as an optimization, so special-case it here. if (to == mono_defaults.corlib) return TRUE; // Non-dynamic images may NEVER reference dynamic images if (to->dynamic && !from->dynamic) return FALSE; // FIXME: We currently give a dynamic images a pass on the reference rules. // Dynamic images may ALWAYS reference non-dynamic images. // We allow this because the dynamic image code is known "messy", and in theory it is already // protected because dynamic images can only reference classes their assembly has retained. // However, long term, we should make this rigorous. if (from->dynamic && !to->dynamic) return TRUE; gboolean success = FALSE; // Images to inspect on this pass, images to inspect on the next pass GPtrArray *current = g_ptr_array_sized_new (1), *next = g_ptr_array_new (); // Because in practice the image graph contains cycles, we must track which images we've visited GHashTable *visited = g_hash_table_new (NULL, NULL); #define CHECK_IMAGE_VISIT(i) check_image_search (visited, next, (i), to, &success) CHECK_IMAGE_VISIT (from); // Initially "next" contains only from node // For each pass exhaust the "to check" queue while filling up the "check next" queue while (!success && next->len > 0) // Halt on success or when out of nodes to process { // Swap "current" and "next" and clear next GPtrArray *temp = current; current = next; next = temp; g_ptr_array_set_size (next, 0); int current_idx; for(current_idx = 0; current_idx < current->len; current_idx++) { MonoImage *checking = (MonoImage*)g_ptr_array_index (current, current_idx); mono_image_lock (checking); // For each queued image visit all directly referenced images int inner_idx; // 'files' and 'modules' semantically contain the same items but because of lazy loading we must check both for (inner_idx = 0; !success && inner_idx < checking->file_count; inner_idx++) { CHECK_IMAGE_VISIT (checking->files[inner_idx]); } for (inner_idx = 0; !success && inner_idx < checking->module_count; inner_idx++) { CHECK_IMAGE_VISIT (checking->modules[inner_idx]); } for (inner_idx = 0; !success && inner_idx < checking->nreferences; inner_idx++) { // Assembly references are lazy-loaded and thus allowed to be NULL. // If they are NULL, we don't care about them for this search, because their images haven't impacted ref_count yet. if (checking->references[inner_idx]) { CHECK_IMAGE_VISIT (checking->references[inner_idx]->image); } } mono_image_unlock (checking); } } g_ptr_array_free (current, TRUE); g_ptr_array_free (next, TRUE); g_hash_table_destroy (visited); return success; } // Case 2. ImageSet FROM points to Image TO: One of FROM's "images" either is, or transitively references, TO. static gboolean check_image_set_may_reference_image (MonoImageSet *from, MonoImage *to) { // See above-- All images implicitly reference corlib if (to == mono_defaults.corlib) return TRUE; int idx; gboolean success = FALSE; mono_image_set_lock (from); for (idx = 0; !success && idx < from->nimages; idx++) { if (check_image_may_reference_image (from->images[idx], to)) success = TRUE; } mono_image_set_unlock (from); return success; // No satisfying image found in from->images } // Case 3. ImageSet FROM points to ImageSet TO: The images in TO are a strict subset of FROM (no transitive relationship is important here) static gboolean check_image_set_may_reference_image_set (MonoImageSet *from, MonoImageSet *to) { if (to == from) return TRUE; gboolean valid = TRUE; // Until proven otherwise mono_image_set_lock (from); mono_image_set_lock (to); int to_idx, from_idx; for (to_idx = 0; valid && to_idx < to->nimages; to_idx++) { gboolean seen = FALSE; // If TO set includes corlib, the FROM set may // implicitly reference corlib, even if it's not // present in the set explicitly. if (to->images[to_idx] == mono_defaults.corlib) seen = TRUE; // For each item in to->images, scan over from->images seeking a path to it. for (from_idx = 0; !seen && from_idx < from->nimages; from_idx++) { if (check_image_may_reference_image (from->images[from_idx], to->images[to_idx])) seen = TRUE; } // If the to->images item is not found in from->images, the subset check has failed if (!seen) valid = FALSE; } mono_image_set_unlock (from); mono_image_set_unlock (to); return valid; // All items in "to" were found in "from" } // Case 4. Image FROM points to ImageSet TO: FROM transitively references *ALL* of the “images” listed in TO static gboolean check_image_may_reference_image_set (MonoImage *from, MonoImageSet *to) { if (to->nimages == 0) // Malformed image_set return FALSE; gboolean valid = TRUE; mono_image_set_lock (to); int idx; for (idx = 0; valid && idx < to->nimages; idx++) { if (!check_image_may_reference_image (from, to->images[idx])) valid = FALSE; } mono_image_set_unlock (to); return valid; // All images in to->images checked out } // Small helper-- get a descriptive string for a MonoMemPoolOwner // Callers are obligated to free buffer with g_free after use static const char * check_mempool_owner_name (MonoMemPoolOwner owner) { GString *result = g_string_new (NULL); if (owner.image) { if (owner.image->dynamic) g_string_append (result, "(Dynamic)"); g_string_append (result, owner.image->name); } else if (owner.image_set) { char *temp = mono_image_set_description (owner.image_set); g_string_append (result, "(Image set)"); g_string_append (result, temp); g_free (temp); } else { g_string_append (result, "(Non-image memory)"); } return g_string_free (result, FALSE); } // Helper -- surf various image-locating functions looking for the owner of this pointer static MonoMemPoolOwner mono_find_mempool_owner (void *ptr) { MonoMemPoolOwner owner = mono_mempool_no_owner; owner.image = mono_find_image_owner (ptr); if (!check_mempool_owner_eq (owner, mono_mempool_no_owner)) return owner; owner.image_set = mono_find_image_set_owner (ptr); if (!check_mempool_owner_eq (owner, mono_mempool_no_owner)) return owner; owner.image = mono_find_dynamic_image_owner (ptr); return owner; } // Actually perform reference audit static void check_mempool_may_reference_mempool (void *from_ptr, void *to_ptr, gboolean require_local) { if (!mono_check_mode_enabled (MONO_CHECK_MODE_METADATA)) return; // Null pointers are OK if (!to_ptr) return; MonoMemPoolOwner from = mono_find_mempool_owner (from_ptr), to = mono_find_mempool_owner (to_ptr); if (require_local) { if (!check_mempool_owner_eq (from,to)) check_mempool_assert_message ("Pointer in image %s should have been internal, but instead pointed to image %s", check_mempool_owner_name (from), check_mempool_owner_name (to)); } // Writing into unknown mempool else if (check_mempool_owner_eq (from, mono_mempool_no_owner)) { check_mempool_assert_message ("Non-image memory attempting to write pointer to image %s", check_mempool_owner_name (to)); } // Reading from unknown mempool else if (check_mempool_owner_eq (to, mono_mempool_no_owner)) { check_mempool_assert_message ("Attempting to write pointer from image %s to non-image memory", check_mempool_owner_name (from)); } // Split out the four cases described above: else if (from.image && to.image) { if (!check_image_may_reference_image (from.image, to.image)) check_mempool_assert_message ("Image %s tried to point to image %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image && to.image_set) { if (!check_image_may_reference_image_set (from.image, to.image_set)) check_mempool_assert_message ("Image %s tried to point to image set %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image_set && to.image_set) { if (!check_image_set_may_reference_image_set (from.image_set, to.image_set)) check_mempool_assert_message ("Image set %s tried to point to image set %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else if (from.image_set && to.image) { if (!check_image_set_may_reference_image (from.image_set, to.image)) check_mempool_assert_message ("Image set %s tried to point to image %s, but does not retain a reference", check_mempool_owner_name (from), check_mempool_owner_name (to)); } else { check_mempool_assert_message ("Internal logic error: Unreachable code"); } } void check_metadata_store (void *from, void *to) { check_mempool_may_reference_mempool (from, to, FALSE); } void check_metadata_store_local (void *from, void *to) { check_mempool_may_reference_mempool (from, to, TRUE); } #endif /* defined(ENABLE_CHECKED_BUILD_METADATA) */ #else /* ENABLE_CHECKED_BUILD */ MONO_EMPTY_SOURCE_FILE (checked_build); #endif /* ENABLE_CHECKED_BUILD */
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CanonicalizationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class CanonicalizationTests { private TestTypeSystemContext _context; private ModuleDesc _testModule; private MetadataType _referenceType; private MetadataType _otherReferenceType; private MetadataType _structType; private MetadataType _otherStructType; private MetadataType _genericReferenceType; private MetadataType _genericStructType; private MetadataType _genericReferenceTypeWithThreeParams; private MetadataType _genericStructTypeWithThreeParams; public CanonicalizationTests() { _context = new TestTypeSystemContext(TargetArchitecture.Unknown); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; _referenceType = _testModule.GetType("Canonicalization", "ReferenceType"); _otherReferenceType = _testModule.GetType("Canonicalization", "OtherReferenceType"); _structType = _testModule.GetType("Canonicalization", "StructType"); _otherStructType = _testModule.GetType("Canonicalization", "OtherStructType"); _genericReferenceType = _testModule.GetType("Canonicalization", "GenericReferenceType`1"); _genericStructType = _testModule.GetType("Canonicalization", "GenericStructType`1"); _genericReferenceTypeWithThreeParams = _testModule.GetType("Canonicalization", "GenericReferenceTypeWithThreeParams`3"); _genericStructTypeWithThreeParams = _testModule.GetType("Canonicalization", "GenericStructTypeWithThreeParams`3"); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestGenericTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Canonical forms of reference type over two different reference types are equivalent var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var referenceOverOtherReference = _genericReferenceType.MakeInstantiatedType(_otherReferenceType); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Universal)); var referenceOverReferenceOverReference = _genericReferenceType.MakeInstantiatedType(referenceOverReference); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverReferenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverReferenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); var threeParamReferenceOverS1R1S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _referenceType, _structType); var threeParamReferenceOverS1R2S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _structType); var threeParamReferenceOverS1R2S2 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _otherStructType); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Specific), threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Universal), threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Universal)); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Universal), threeParamReferenceOverS1R2S2.ConvertToCanonForm(CanonicalFormKind.Universal)); // Universal canonical forms of reference type over reference and value types are equivalent var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); var referenceOverOtherStruct = _genericReferenceType.MakeInstantiatedType(_otherStructType); Assert.Same( referenceOverStruct.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverOtherStruct.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canon forms of reference type instantiated over a generic valuetype over any reference type var genericStructOverReference = _genericStructType.MakeInstantiatedType(_referenceType); var genericStructOverOtherReference = _genericStructType.MakeInstantiatedType(_otherReferenceType); var referenceOverGenericStructOverReference = _genericReferenceType.MakeInstantiatedType(genericStructOverReference); var referenceOverGenericStructOverOtherReference = _genericReferenceType.MakeInstantiatedType(genericStructOverOtherReference); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverGenericStructOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverGenericStructOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Universal)); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canon of a type instantiated over a signature variable is the same type when just canonicalizing as specific, // but the universal canon form when performing universal canonicalization. var genericStructOverSignatureVariable = _genericStructType.MakeInstantiatedType(_context.GetSignatureVariable(0, false)); Assert.Same( genericStructOverSignatureVariable, genericStructOverSignatureVariable.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( genericStructOverSignatureVariable, genericStructOverSignatureVariable.ConvertToCanonForm(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestGenericTypesNegative(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Two different types instantiated over the same type are not canonically equivalent var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var structOverReference = _genericStructType.MakeInstantiatedType(_referenceType); Assert.NotSame( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), structOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), structOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); // Specific canonical forms of reference type over reference and value types are not equivalent var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); var referenceOverOtherStruct = _genericReferenceType.MakeInstantiatedType(_otherStructType); Assert.NotSame( referenceOverStruct.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverOtherStruct.ConvertToCanonForm(CanonicalFormKind.Specific)); var threeParamReferenceOverS1R2S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _structType); var threeParamReferenceOverS1R2S2 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _otherStructType); Assert.NotSame( threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Specific), threeParamReferenceOverS1R2S2.ConvertToCanonForm(CanonicalFormKind.Specific)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestArrayTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Generic type instantiated over an array has the same canonical form as generic type over any other reference type var genericStructOverArrayOfInt = _genericStructType.MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32).MakeArrayType()); var genericStructOverReferenceType = _genericStructType.MakeInstantiatedType(_referenceType); Assert.Same( genericStructOverArrayOfInt.ConvertToCanonForm(CanonicalFormKind.Specific), genericStructOverReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( genericStructOverArrayOfInt.ConvertToCanonForm(CanonicalFormKind.Universal), genericStructOverReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical form of SzArray and Multidim array are not the same var arrayOfReferenceType = _referenceType.MakeArrayType(); var mdArrayOfReferenceType = _referenceType.MakeArrayType(1); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), mdArrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), mdArrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical forms of arrays over different reference types are same var arrayOfOtherReferenceType = _otherReferenceType.MakeArrayType(); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), arrayOfOtherReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), arrayOfOtherReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical forms of arrays of value types are only same for universal canon form var arrayOfStruct = _structType.MakeArrayType(); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), arrayOfStruct.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), arrayOfStruct.ConvertToCanonForm(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestMethodsOnGenericTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var referenceOverOtherReference = _genericReferenceType.MakeInstantiatedType(_otherReferenceType); Assert.NotSame( referenceOverReference.GetMethod("Method", null), referenceOverOtherReference.GetMethod("Method", null)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); Assert.NotSame( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverStruct.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverStruct.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_otherReferenceType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_otherReferenceType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverStruct.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverStruct.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType), referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestArrayMethods(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var arrayOfReferenceType = _referenceType.MakeArrayType(1); var arrayOfOtherReferenceType = _otherReferenceType.MakeArrayType(1); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific), arrayOfOtherReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal), arrayOfOtherReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); var arrayOfStruct = _structType.MakeArrayType(1); Assert.NotSame( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific), arrayOfStruct.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal), arrayOfStruct.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestUpgradeToUniversalCanon(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var gstOverUniversalCanon = _genericStructType.MakeInstantiatedType(_context.UniversalCanonType); var grtOverRtRtStOverUniversal = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _referenceType, _referenceType, gstOverUniversalCanon); var grtOverRtRtStOverUniversalCanon = grtOverRtRtStOverUniversal.ConvertToCanonForm(CanonicalFormKind.Specific); // Specific form gets upgraded to universal in the presence of universal canon. // GenericReferenceTypeWithThreeParams<ReferenceType, ReferenceType, GenericStructType<__UniversalCanon>> is // GenericReferenceTypeWithThreeParams<T__UniversalCanon, U__UniversalCanon, V__UniversalCanon> Assert.Same(_context.UniversalCanonType, grtOverRtRtStOverUniversalCanon.Instantiation[0]); Assert.Same(_context.UniversalCanonType, grtOverRtRtStOverUniversalCanon.Instantiation[2]); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestDowngradeFromUniversalCanon(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var grtOverUniversalCanon = _genericReferenceType.MakeInstantiatedType(_context.UniversalCanonType); var gstOverGrtOverUniversalCanon = _genericStructType.MakeInstantiatedType(grtOverUniversalCanon); var gstOverCanon = _genericStructType.MakeInstantiatedType(_context.CanonType); Assert.Same(gstOverCanon, gstOverGrtOverUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); var gstOverGstOverGrtOverUniversalCanon = _genericStructType.MakeInstantiatedType(gstOverGrtOverUniversalCanon); var gstOverGstOverCanon = _genericStructType.MakeInstantiatedType(gstOverCanon); Assert.Same(gstOverGstOverCanon, gstOverGstOverGrtOverUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); } [Fact] public void TestCanonicalizationOfRuntimeDeterminedUniversalGeneric() { var gstOverUniversalCanon = _genericStructType.MakeInstantiatedType(_context.UniversalCanonType); var rdtUniversalCanon = (RuntimeDeterminedType)gstOverUniversalCanon.ConvertToSharedRuntimeDeterminedForm().Instantiation[0]; Assert.Same(_context.UniversalCanonType, rdtUniversalCanon.CanonicalType); var gstOverRdtUniversalCanon = _genericStructType.MakeInstantiatedType(rdtUniversalCanon); Assert.Same(gstOverUniversalCanon, gstOverRdtUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class CanonicalizationTests { private TestTypeSystemContext _context; private ModuleDesc _testModule; private MetadataType _referenceType; private MetadataType _otherReferenceType; private MetadataType _structType; private MetadataType _otherStructType; private MetadataType _genericReferenceType; private MetadataType _genericStructType; private MetadataType _genericReferenceTypeWithThreeParams; private MetadataType _genericStructTypeWithThreeParams; public CanonicalizationTests() { _context = new TestTypeSystemContext(TargetArchitecture.Unknown); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; _referenceType = _testModule.GetType("Canonicalization", "ReferenceType"); _otherReferenceType = _testModule.GetType("Canonicalization", "OtherReferenceType"); _structType = _testModule.GetType("Canonicalization", "StructType"); _otherStructType = _testModule.GetType("Canonicalization", "OtherStructType"); _genericReferenceType = _testModule.GetType("Canonicalization", "GenericReferenceType`1"); _genericStructType = _testModule.GetType("Canonicalization", "GenericStructType`1"); _genericReferenceTypeWithThreeParams = _testModule.GetType("Canonicalization", "GenericReferenceTypeWithThreeParams`3"); _genericStructTypeWithThreeParams = _testModule.GetType("Canonicalization", "GenericStructTypeWithThreeParams`3"); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestGenericTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Canonical forms of reference type over two different reference types are equivalent var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var referenceOverOtherReference = _genericReferenceType.MakeInstantiatedType(_otherReferenceType); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Universal)); var referenceOverReferenceOverReference = _genericReferenceType.MakeInstantiatedType(referenceOverReference); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverReferenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverReferenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); var threeParamReferenceOverS1R1S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _referenceType, _structType); var threeParamReferenceOverS1R2S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _structType); var threeParamReferenceOverS1R2S2 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _otherStructType); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Specific), threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Universal), threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Universal)); Assert.Same( threeParamReferenceOverS1R1S1.ConvertToCanonForm(CanonicalFormKind.Universal), threeParamReferenceOverS1R2S2.ConvertToCanonForm(CanonicalFormKind.Universal)); // Universal canonical forms of reference type over reference and value types are equivalent var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); var referenceOverOtherStruct = _genericReferenceType.MakeInstantiatedType(_otherStructType); Assert.Same( referenceOverStruct.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverOtherStruct.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canon forms of reference type instantiated over a generic valuetype over any reference type var genericStructOverReference = _genericStructType.MakeInstantiatedType(_referenceType); var genericStructOverOtherReference = _genericStructType.MakeInstantiatedType(_otherReferenceType); var referenceOverGenericStructOverReference = _genericReferenceType.MakeInstantiatedType(genericStructOverReference); var referenceOverGenericStructOverOtherReference = _genericReferenceType.MakeInstantiatedType(genericStructOverOtherReference); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverGenericStructOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverGenericStructOverOtherReference.ConvertToCanonForm(CanonicalFormKind.Universal)); Assert.Same( referenceOverGenericStructOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canon of a type instantiated over a signature variable is the same type when just canonicalizing as specific, // but the universal canon form when performing universal canonicalization. var genericStructOverSignatureVariable = _genericStructType.MakeInstantiatedType(_context.GetSignatureVariable(0, false)); Assert.Same( genericStructOverSignatureVariable, genericStructOverSignatureVariable.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( genericStructOverSignatureVariable, genericStructOverSignatureVariable.ConvertToCanonForm(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestGenericTypesNegative(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Two different types instantiated over the same type are not canonically equivalent var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var structOverReference = _genericStructType.MakeInstantiatedType(_referenceType); Assert.NotSame( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Specific), structOverReference.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( referenceOverReference.ConvertToCanonForm(CanonicalFormKind.Universal), structOverReference.ConvertToCanonForm(CanonicalFormKind.Universal)); // Specific canonical forms of reference type over reference and value types are not equivalent var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); var referenceOverOtherStruct = _genericReferenceType.MakeInstantiatedType(_otherStructType); Assert.NotSame( referenceOverStruct.ConvertToCanonForm(CanonicalFormKind.Specific), referenceOverOtherStruct.ConvertToCanonForm(CanonicalFormKind.Specific)); var threeParamReferenceOverS1R2S1 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _structType); var threeParamReferenceOverS1R2S2 = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _structType, _otherReferenceType, _otherStructType); Assert.NotSame( threeParamReferenceOverS1R2S1.ConvertToCanonForm(CanonicalFormKind.Specific), threeParamReferenceOverS1R2S2.ConvertToCanonForm(CanonicalFormKind.Specific)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestArrayTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; // Generic type instantiated over an array has the same canonical form as generic type over any other reference type var genericStructOverArrayOfInt = _genericStructType.MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32).MakeArrayType()); var genericStructOverReferenceType = _genericStructType.MakeInstantiatedType(_referenceType); Assert.Same( genericStructOverArrayOfInt.ConvertToCanonForm(CanonicalFormKind.Specific), genericStructOverReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( genericStructOverArrayOfInt.ConvertToCanonForm(CanonicalFormKind.Universal), genericStructOverReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical form of SzArray and Multidim array are not the same var arrayOfReferenceType = _referenceType.MakeArrayType(); var mdArrayOfReferenceType = _referenceType.MakeArrayType(1); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), mdArrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), mdArrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical forms of arrays over different reference types are same var arrayOfOtherReferenceType = _otherReferenceType.MakeArrayType(); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), arrayOfOtherReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), arrayOfOtherReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal)); // Canonical forms of arrays of value types are only same for universal canon form var arrayOfStruct = _structType.MakeArrayType(); Assert.NotSame( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Specific), arrayOfStruct.ConvertToCanonForm(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.ConvertToCanonForm(CanonicalFormKind.Universal), arrayOfStruct.ConvertToCanonForm(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestMethodsOnGenericTypes(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var referenceOverReference = _genericReferenceType.MakeInstantiatedType(_referenceType); var referenceOverOtherReference = _genericReferenceType.MakeInstantiatedType(_otherReferenceType); Assert.NotSame( referenceOverReference.GetMethod("Method", null), referenceOverOtherReference.GetMethod("Method", null)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); var referenceOverStruct = _genericReferenceType.MakeInstantiatedType(_structType); Assert.NotSame( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverStruct.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverStruct.GetMethod("Method", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_otherReferenceType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_otherReferenceType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverStruct.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Specific), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( referenceOverStruct.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_referenceType).GetCanonMethodTarget(CanonicalFormKind.Universal), referenceOverOtherReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Universal)); Assert.NotSame( referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType), referenceOverReference.GetMethod("GenericMethod", null).MakeInstantiatedMethod(_structType).GetCanonMethodTarget(CanonicalFormKind.Specific)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestArrayMethods(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var arrayOfReferenceType = _referenceType.MakeArrayType(1); var arrayOfOtherReferenceType = _otherReferenceType.MakeArrayType(1); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific), arrayOfOtherReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal), arrayOfOtherReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); var arrayOfStruct = _structType.MakeArrayType(1); Assert.NotSame( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific), arrayOfStruct.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Specific)); Assert.Same( arrayOfReferenceType.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal), arrayOfStruct.GetMethod("Set", null).GetCanonMethodTarget(CanonicalFormKind.Universal)); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestUpgradeToUniversalCanon(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var gstOverUniversalCanon = _genericStructType.MakeInstantiatedType(_context.UniversalCanonType); var grtOverRtRtStOverUniversal = _genericReferenceTypeWithThreeParams.MakeInstantiatedType( _referenceType, _referenceType, gstOverUniversalCanon); var grtOverRtRtStOverUniversalCanon = grtOverRtRtStOverUniversal.ConvertToCanonForm(CanonicalFormKind.Specific); // Specific form gets upgraded to universal in the presence of universal canon. // GenericReferenceTypeWithThreeParams<ReferenceType, ReferenceType, GenericStructType<__UniversalCanon>> is // GenericReferenceTypeWithThreeParams<T__UniversalCanon, U__UniversalCanon, V__UniversalCanon> Assert.Same(_context.UniversalCanonType, grtOverRtRtStOverUniversalCanon.Instantiation[0]); Assert.Same(_context.UniversalCanonType, grtOverRtRtStOverUniversalCanon.Instantiation[2]); } [Theory] [InlineData(CanonicalizationMode.Standard)] [InlineData(CanonicalizationMode.RuntimeDetermined)] public void TestDowngradeFromUniversalCanon(CanonicalizationMode algorithmType) { _context.CanonMode = algorithmType; var grtOverUniversalCanon = _genericReferenceType.MakeInstantiatedType(_context.UniversalCanonType); var gstOverGrtOverUniversalCanon = _genericStructType.MakeInstantiatedType(grtOverUniversalCanon); var gstOverCanon = _genericStructType.MakeInstantiatedType(_context.CanonType); Assert.Same(gstOverCanon, gstOverGrtOverUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); var gstOverGstOverGrtOverUniversalCanon = _genericStructType.MakeInstantiatedType(gstOverGrtOverUniversalCanon); var gstOverGstOverCanon = _genericStructType.MakeInstantiatedType(gstOverCanon); Assert.Same(gstOverGstOverCanon, gstOverGstOverGrtOverUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); } [Fact] public void TestCanonicalizationOfRuntimeDeterminedUniversalGeneric() { var gstOverUniversalCanon = _genericStructType.MakeInstantiatedType(_context.UniversalCanonType); var rdtUniversalCanon = (RuntimeDeterminedType)gstOverUniversalCanon.ConvertToSharedRuntimeDeterminedForm().Instantiation[0]; Assert.Same(_context.UniversalCanonType, rdtUniversalCanon.CanonicalType); var gstOverRdtUniversalCanon = _genericStructType.MakeInstantiatedType(rdtUniversalCanon); Assert.Same(gstOverUniversalCanon, gstOverRdtUniversalCanon.ConvertToCanonForm(CanonicalFormKind.Specific)); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/SingleMethodCompilationModuleGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Internal.TypeSystem; namespace ILCompiler { /// <summary> /// A compilation group that only contains a single method. Useful for development purposes when investigating /// code generation issues. /// </summary> public class SingleMethodCompilationModuleGroup : CompilationModuleGroup { private MethodDesc _method; public SingleMethodCompilationModuleGroup(MethodDesc method) { _method = method; } public override bool IsSingleFileCompilation { get { return false; } } public override bool ContainsMethodBody(MethodDesc method, bool unboxingStub) { return method == _method; } public sealed override bool ContainsMethodDictionary(MethodDesc method) { Debug.Assert(method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method); return true; } public override bool ContainsType(TypeDesc type) { return true; } public override bool ContainsTypeDictionary(TypeDesc type) { return true; } public override bool ImportsMethod(MethodDesc method, bool unboxingStub) { return false; } public override bool ShouldProduceFullVTable(TypeDesc type) { return false; } public override bool ShouldPromoteToFullType(TypeDesc type) { return false; } public override bool PresenceOfEETypeImpliesAllMethodsOnType(TypeDesc type) { return false; } public override bool ShouldReferenceThroughImportTable(TypeDesc type) { return false; } public override bool CanHaveReferenceThroughImportTable { get { return false; } } public override bool AllowInstanceMethodOptimization(MethodDesc method) { return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Internal.TypeSystem; namespace ILCompiler { /// <summary> /// A compilation group that only contains a single method. Useful for development purposes when investigating /// code generation issues. /// </summary> public class SingleMethodCompilationModuleGroup : CompilationModuleGroup { private MethodDesc _method; public SingleMethodCompilationModuleGroup(MethodDesc method) { _method = method; } public override bool IsSingleFileCompilation { get { return false; } } public override bool ContainsMethodBody(MethodDesc method, bool unboxingStub) { return method == _method; } public sealed override bool ContainsMethodDictionary(MethodDesc method) { Debug.Assert(method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method); return true; } public override bool ContainsType(TypeDesc type) { return true; } public override bool ContainsTypeDictionary(TypeDesc type) { return true; } public override bool ImportsMethod(MethodDesc method, bool unboxingStub) { return false; } public override bool ShouldProduceFullVTable(TypeDesc type) { return false; } public override bool ShouldPromoteToFullType(TypeDesc type) { return false; } public override bool PresenceOfEETypeImpliesAllMethodsOnType(TypeDesc type) { return false; } public override bool ShouldReferenceThroughImportTable(TypeDesc type) { return false; } public override bool CanHaveReferenceThroughImportTable { get { return false; } } public override bool AllowInstanceMethodOptimization(MethodDesc method) { return false; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyContentType.cs
// 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 { public enum AssemblyContentType { Default = 0, WindowsRuntime = 1, } }
// 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 { public enum AssemblyContentType { Default = 0, WindowsRuntime = 1, } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates { public sealed class X500DistinguishedName : AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) : base(new Oid(null, null), encodedDistinguishedName) { } /// <summary> /// Initializes a new instance of the <see cref="X500DistinguishedName"/> /// class using information from the provided data. /// </summary> /// <param name="encodedDistinguishedName"> /// The encoded distinguished name. /// </param> /// <seealso cref="Encode"/> public X500DistinguishedName(ReadOnlySpan<byte> encodedDistinguishedName) : base(new Oid(null, null), encodedDistinguishedName) { } public X500DistinguishedName(AsnEncodedData encodedDistinguishedName) : base(encodedDistinguishedName) { } public X500DistinguishedName(X500DistinguishedName distinguishedName) : base(distinguishedName) { _lazyDistinguishedName = distinguishedName.Name; } public X500DistinguishedName(string distinguishedName) : this(distinguishedName, X500DistinguishedNameFlags.Reversed) { } public X500DistinguishedName(string distinguishedName, X500DistinguishedNameFlags flag) : base(new Oid(null, null), Encode(distinguishedName, flag)) { _lazyDistinguishedName = distinguishedName; } public string Name { get { string? name = _lazyDistinguishedName; if (name == null) { name = _lazyDistinguishedName = Decode(X500DistinguishedNameFlags.Reversed); } return name; } } public string Decode(X500DistinguishedNameFlags flag) { ThrowIfInvalid(flag); return X509Pal.Instance.X500DistinguishedNameDecode(RawData, flag); } public override string Format(bool multiLine) { return X509Pal.Instance.X500DistinguishedNameFormat(RawData, multiLine); } private static byte[] Encode(string distinguishedName!!, X500DistinguishedNameFlags flags) { ThrowIfInvalid(flags); return X509Pal.Instance.X500DistinguishedNameEncode(distinguishedName, flags); } private static void ThrowIfInvalid(X500DistinguishedNameFlags flags) { // All values or'ed together. Change this if you add values to the enumeration. uint allFlags = 0x71F1; uint dwFlags = (uint)flags; if ((dwFlags & ~allFlags) != 0) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, "flag")); } private volatile string? _lazyDistinguishedName; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates { public sealed class X500DistinguishedName : AsnEncodedData { public X500DistinguishedName(byte[] encodedDistinguishedName) : base(new Oid(null, null), encodedDistinguishedName) { } /// <summary> /// Initializes a new instance of the <see cref="X500DistinguishedName"/> /// class using information from the provided data. /// </summary> /// <param name="encodedDistinguishedName"> /// The encoded distinguished name. /// </param> /// <seealso cref="Encode"/> public X500DistinguishedName(ReadOnlySpan<byte> encodedDistinguishedName) : base(new Oid(null, null), encodedDistinguishedName) { } public X500DistinguishedName(AsnEncodedData encodedDistinguishedName) : base(encodedDistinguishedName) { } public X500DistinguishedName(X500DistinguishedName distinguishedName) : base(distinguishedName) { _lazyDistinguishedName = distinguishedName.Name; } public X500DistinguishedName(string distinguishedName) : this(distinguishedName, X500DistinguishedNameFlags.Reversed) { } public X500DistinguishedName(string distinguishedName, X500DistinguishedNameFlags flag) : base(new Oid(null, null), Encode(distinguishedName, flag)) { _lazyDistinguishedName = distinguishedName; } public string Name { get { string? name = _lazyDistinguishedName; if (name == null) { name = _lazyDistinguishedName = Decode(X500DistinguishedNameFlags.Reversed); } return name; } } public string Decode(X500DistinguishedNameFlags flag) { ThrowIfInvalid(flag); return X509Pal.Instance.X500DistinguishedNameDecode(RawData, flag); } public override string Format(bool multiLine) { return X509Pal.Instance.X500DistinguishedNameFormat(RawData, multiLine); } private static byte[] Encode(string distinguishedName!!, X500DistinguishedNameFlags flags) { ThrowIfInvalid(flags); return X509Pal.Instance.X500DistinguishedNameEncode(distinguishedName, flags); } private static void ThrowIfInvalid(X500DistinguishedNameFlags flags) { // All values or'ed together. Change this if you add values to the enumeration. uint allFlags = 0x71F1; uint dwFlags = (uint)flags; if ((dwFlags & ~allFlags) != 0) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, "flag")); } private volatile string? _lazyDistinguishedName; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Runtime.Serialization.Formatters/tests/SerializationTypes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; [Serializable] public struct TypeWithoutNamespace { } namespace System.Runtime.Serialization.Formatters.Tests { [Serializable] public sealed class SealedObjectWithIntStringFields { public int Member1; public string Member2; public string Member3; public override bool Equals(object obj) { var o = obj as SealedObjectWithIntStringFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(Member3, o.Member3); } public override int GetHashCode() => 1; } [Serializable] public class ObjectWithIntStringUShortUIntULongAndCustomObjectFields { public int Member1; public string Member2; public string _member3; public SealedObjectWithIntStringFields Member4; public SealedObjectWithIntStringFields Member4shared; public SealedObjectWithIntStringFields Member5; public string Member6; public string str1; public string str2; public string str3; public string str4; public ushort u16; public uint u32; public ulong u64; public override bool Equals(object obj) { var o = obj as ObjectWithIntStringUShortUIntULongAndCustomObjectFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(_member3, o._member3) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4, o.Member4) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4shared, o.Member4shared) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member5, o.Member5) && EqualityComparer<string>.Default.Equals(Member6, o.Member6) && EqualityComparer<string>.Default.Equals(str1, o.str1) && EqualityComparer<string>.Default.Equals(str2, o.str2) && EqualityComparer<string>.Default.Equals(str3, o.str3) && EqualityComparer<string>.Default.Equals(str4, o.str4) && EqualityComparer<ushort>.Default.Equals(u16, o.u16) && EqualityComparer<uint>.Default.Equals(u16, o.u16) && EqualityComparer<ulong>.Default.Equals(u64, o.u64) && // make sure shared members are the same object ReferenceEquals(Member4, Member4shared) && ReferenceEquals(o.Member4, o.Member4shared); } public override int GetHashCode() => 1; } [Serializable] public class Point : IComparable<Point>, IEquatable<Point> { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public int CompareTo(object obj) { return CompareTo(obj as Point); } public int CompareTo(Point other) { return other == null ? 1 : 0; } public override bool Equals(object obj) => Equals(obj as Point); public bool Equals(Point other) { return other != null && X == other.X && Y == other.Y; } public override int GetHashCode() => 1; } [Serializable] public class Tree<T> { public Tree(T value, Tree<T> left, Tree<T> right) { Value = value; Left = left; Right = right; } public T Value { get; } public Tree<T> Left { get; } public Tree<T> Right { get; } public override bool Equals(object obj) { Tree<T> o = obj as Tree<T>; if (o == null) return false; return EqualityComparer<T>.Default.Equals(Value, o.Value) && EqualityComparer<Tree<T>>.Default.Equals(Left, o.Left) && EqualityComparer<Tree<T>>.Default.Equals(Right, o.Right) && // make sure the branches aren't actually the exact same object (Left == null || !ReferenceEquals(Left, o.Left)) && (Right == null || !ReferenceEquals(Right, o.Right)); } public override int GetHashCode() => 1; } [Serializable] public class Graph<T> { public T Value; public Graph<T>[] Links; public override bool Equals(object obj) { Graph<T> o = obj as Graph<T>; if (o == null) return false; var toExplore = new Stack<KeyValuePair<Graph<T>, Graph<T>>>(); toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(this, o)); var seen1 = new HashSet<Graph<T>>(ReferenceEqualityComparer.Instance); while (toExplore.Count > 0) { var cur = toExplore.Pop(); if (!seen1.Add(cur.Key)) { continue; } if (!EqualityComparer<T>.Default.Equals(cur.Key.Value, cur.Value.Value)) { return false; } if (Links == null || o.Links == null) { if (Links != o.Links) return false; continue; } if (Links.Length != o.Links.Length) { return false; } for (int i = 0; i < Links.Length; i++) { toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(Links[i], o.Links[i])); } } return true; } public override int GetHashCode() => 1; } [Serializable] public sealed class ObjectWithArrays { public int[] IntArray; public string[] StringArray; public Tree<int>[] TreeArray; public byte[] ByteArray; public int[][] JaggedArray; public int[,] MultiDimensionalArray; public override bool Equals(object obj) { ObjectWithArrays o = obj as ObjectWithArrays; if (o == null) return false; return EqualityHelpers.ArraysAreEqual(IntArray, o.IntArray) && EqualityHelpers.ArraysAreEqual(StringArray, o.StringArray) && EqualityHelpers.ArraysAreEqual(TreeArray, o.TreeArray) && EqualityHelpers.ArraysAreEqual(ByteArray, o.ByteArray) && EqualityHelpers.ArraysAreEqual(JaggedArray, o.JaggedArray) && EqualityHelpers.ArraysAreEqual(MultiDimensionalArray, o.MultiDimensionalArray); } public override int GetHashCode() => 1; } [Serializable] public enum Colors { Red, Orange, Yellow, Green, Blue, Purple } [Serializable] public enum ByteEnum : byte { } [Serializable] public enum SByteEnum : sbyte { } [Serializable] public enum Int16Enum : short { } [Serializable] public enum UInt16Enum : ushort { } [Serializable] public enum Int32Enum : int { } [Serializable] public enum UInt32Enum : uint { } [Serializable] public enum Int64Enum : long { } [Serializable] public enum UInt64Enum : ulong { } public struct NonSerializableStruct { public int Value; } public class NonSerializableClass { public int Value; } [Serializable] public class SerializableClassDerivedFromNonSerializableClass : NonSerializableClass { public int AnotherValue; } [Serializable] public class SerializableClassWithBadField { public NonSerializableClass Value; } [Serializable] public struct EmptyStruct { } [Serializable] public struct StructWithIntField { public int X; } [Serializable] public struct StructWithStringFields { public string String1; public string String2; } [Serializable] public struct StructContainingOtherStructs { public StructWithStringFields Nested1; public StructWithStringFields Nested2; } [Serializable] public struct StructContainingArraysOfOtherStructs { public StructContainingOtherStructs[] Nested; public override bool Equals(object obj) { if (!(obj is StructContainingArraysOfOtherStructs)) return false; return EqualityHelpers.ArraysAreEqual(Nested, ((StructContainingArraysOfOtherStructs)obj).Nested); } public override int GetHashCode() => 1; } [Serializable] public class BasicISerializableObject : ISerializable { private NonSerializablePair<int, string> _data; public BasicISerializableObject(int value1, string value2) { _data = new NonSerializablePair<int, string> { Value1 = value1, Value2 = value2 }; } public BasicISerializableObject(SerializationInfo info, StreamingContext context) { _data = new NonSerializablePair<int, string> { Value1 = info.GetInt32("Value1"), Value2 = info.GetString("Value2") }; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Value1", _data.Value1); info.AddValue("Value2", _data.Value2); } public override bool Equals(object obj) { var o = obj as BasicISerializableObject; if (o == null) return false; if (_data == null || o._data == null) return _data == o._data; return _data.Value1 == o._data.Value1 && _data.Value2 == o._data.Value2; } public override int GetHashCode() => 1; } [Serializable] public sealed class DerivedISerializableWithNonPublicDeserializationCtor : BasicISerializableObject { public DerivedISerializableWithNonPublicDeserializationCtor(int value1, string value2) : base(value1, value2) { } private DerivedISerializableWithNonPublicDeserializationCtor(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class IncrementCountsDuringRoundtrip { public int IncrementedDuringOnSerializingMethod; public int IncrementedDuringOnSerializedMethod; [NonSerialized] public int IncrementedDuringOnDeserializingMethod; public int IncrementedDuringOnDeserializedMethod; public IncrementCountsDuringRoundtrip(string ignored) { } // non-default ctor so that we can observe changes from OnDeserializing [OnSerializing] private void OnSerializingMethod(StreamingContext context) => IncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => IncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => IncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => IncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class DerivedIncrementCountsDuringRoundtrip : IncrementCountsDuringRoundtrip { internal int DerivedIncrementedDuringOnSerializingMethod; internal int DerivedIncrementedDuringOnSerializedMethod; [NonSerialized] internal int DerivedIncrementedDuringOnDeserializingMethod; internal int DerivedIncrementedDuringOnDeserializedMethod; public DerivedIncrementCountsDuringRoundtrip(string ignored) : base(ignored) { } [OnSerializing] private void OnSerializingMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class ObjRefReturnsObj : IObjectReference { public object Real; public object GetRealObject(StreamingContext context) => Real; } internal sealed class NonSerializablePair<T1, T2> { public T1 Value1; public T2 Value2; } internal sealed class NonSerializablePairSurrogate : ISerializationSurrogate { public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { var pair = (NonSerializablePair<int, string>)obj; info.AddValue("Value1", pair.Value1); info.AddValue("Value2", pair.Value2); } public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { var pair = (NonSerializablePair<int, string>)obj; pair.Value1 = info.GetInt32("Value1"); pair.Value2 = info.GetString("Value2"); return pair; } } [Serializable] public class Version1ClassWithoutField { } [Serializable] public class Version2ClassWithoutOptionalField { public object Value; } [Serializable] public class Version2ClassWithOptionalField { [OptionalField(VersionAdded = 2)] public object Value; } [Serializable] public class ObjectWithStateAndMethod { public int State; public int GetState() => State; } [Serializable] public sealed class PointEqualityComparer : IEqualityComparer<Point> { public bool Equals(Point x, Point y) => (x.X == y.X) && (x.Y == y.Y); public int GetHashCode(Point obj) => RuntimeHelpers.GetHashCode(obj); } [Serializable] public class SimpleKeyedCollection : System.Collections.ObjectModel.KeyedCollection<int, Point> { protected override int GetKeyForItem(Point item) { return item.Y; } } [Serializable] internal class GenericTypeWithArg<T> { public T Test; public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var p = (GenericTypeWithArg<T>)obj; return Test.Equals(p.Test); } public override int GetHashCode() { return Test == null ? 0 : Test.GetHashCode(); } } [Serializable] internal class SomeType { public int SomeField; public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var p = (SomeType)obj; return SomeField.Equals(p.SomeField); } public override int GetHashCode() { return SomeField; } } internal static class EqualityHelpers { public static bool ArraysAreEqual<T>(T[] array1, T[] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i])) { return false; } } return true; } public static bool ArraysAreEqual(Array array1, Array array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; if (array1.Rank != array2.Rank) return false; for (int i = 0; i < array1.Rank; i++) { if (array1.GetLength(i) != array2.GetLength(i)) return false; } var e1 = array1.GetEnumerator(); var e2 = array2.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); if (!EqualityComparer<object>.Default.Equals(e1.Current, e2.Current)) { return false; } } return true; } public static bool ArraysAreEqual<T>(T[][] array1, T[][] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { T[] sub1 = array1[i], sub2 = array2[i]; if (sub1 == null || (sub2 == null && (sub1 != sub2))) return false; if (sub1.Length != sub2.Length) return false; for (int j = 0; j < sub1.Length; j++) { if (!EqualityComparer<T>.Default.Equals(sub1[j], sub2[j])) { return false; } } } return true; } } #pragma warning disable 0618 // obsolete warning [Serializable] internal class HashCodeProvider : IHashCodeProvider { public int GetHashCode(object obj) { return 8; } } #pragma warning restore 0618 }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; [Serializable] public struct TypeWithoutNamespace { } namespace System.Runtime.Serialization.Formatters.Tests { [Serializable] public sealed class SealedObjectWithIntStringFields { public int Member1; public string Member2; public string Member3; public override bool Equals(object obj) { var o = obj as SealedObjectWithIntStringFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(Member3, o.Member3); } public override int GetHashCode() => 1; } [Serializable] public class ObjectWithIntStringUShortUIntULongAndCustomObjectFields { public int Member1; public string Member2; public string _member3; public SealedObjectWithIntStringFields Member4; public SealedObjectWithIntStringFields Member4shared; public SealedObjectWithIntStringFields Member5; public string Member6; public string str1; public string str2; public string str3; public string str4; public ushort u16; public uint u32; public ulong u64; public override bool Equals(object obj) { var o = obj as ObjectWithIntStringUShortUIntULongAndCustomObjectFields; if (o == null) return false; return EqualityComparer<int>.Default.Equals(Member1, o.Member1) && EqualityComparer<string>.Default.Equals(Member2, o.Member2) && EqualityComparer<string>.Default.Equals(_member3, o._member3) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4, o.Member4) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member4shared, o.Member4shared) && EqualityComparer<SealedObjectWithIntStringFields>.Default.Equals(Member5, o.Member5) && EqualityComparer<string>.Default.Equals(Member6, o.Member6) && EqualityComparer<string>.Default.Equals(str1, o.str1) && EqualityComparer<string>.Default.Equals(str2, o.str2) && EqualityComparer<string>.Default.Equals(str3, o.str3) && EqualityComparer<string>.Default.Equals(str4, o.str4) && EqualityComparer<ushort>.Default.Equals(u16, o.u16) && EqualityComparer<uint>.Default.Equals(u16, o.u16) && EqualityComparer<ulong>.Default.Equals(u64, o.u64) && // make sure shared members are the same object ReferenceEquals(Member4, Member4shared) && ReferenceEquals(o.Member4, o.Member4shared); } public override int GetHashCode() => 1; } [Serializable] public class Point : IComparable<Point>, IEquatable<Point> { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public int CompareTo(object obj) { return CompareTo(obj as Point); } public int CompareTo(Point other) { return other == null ? 1 : 0; } public override bool Equals(object obj) => Equals(obj as Point); public bool Equals(Point other) { return other != null && X == other.X && Y == other.Y; } public override int GetHashCode() => 1; } [Serializable] public class Tree<T> { public Tree(T value, Tree<T> left, Tree<T> right) { Value = value; Left = left; Right = right; } public T Value { get; } public Tree<T> Left { get; } public Tree<T> Right { get; } public override bool Equals(object obj) { Tree<T> o = obj as Tree<T>; if (o == null) return false; return EqualityComparer<T>.Default.Equals(Value, o.Value) && EqualityComparer<Tree<T>>.Default.Equals(Left, o.Left) && EqualityComparer<Tree<T>>.Default.Equals(Right, o.Right) && // make sure the branches aren't actually the exact same object (Left == null || !ReferenceEquals(Left, o.Left)) && (Right == null || !ReferenceEquals(Right, o.Right)); } public override int GetHashCode() => 1; } [Serializable] public class Graph<T> { public T Value; public Graph<T>[] Links; public override bool Equals(object obj) { Graph<T> o = obj as Graph<T>; if (o == null) return false; var toExplore = new Stack<KeyValuePair<Graph<T>, Graph<T>>>(); toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(this, o)); var seen1 = new HashSet<Graph<T>>(ReferenceEqualityComparer.Instance); while (toExplore.Count > 0) { var cur = toExplore.Pop(); if (!seen1.Add(cur.Key)) { continue; } if (!EqualityComparer<T>.Default.Equals(cur.Key.Value, cur.Value.Value)) { return false; } if (Links == null || o.Links == null) { if (Links != o.Links) return false; continue; } if (Links.Length != o.Links.Length) { return false; } for (int i = 0; i < Links.Length; i++) { toExplore.Push(new KeyValuePair<Graph<T>, Graph<T>>(Links[i], o.Links[i])); } } return true; } public override int GetHashCode() => 1; } [Serializable] public sealed class ObjectWithArrays { public int[] IntArray; public string[] StringArray; public Tree<int>[] TreeArray; public byte[] ByteArray; public int[][] JaggedArray; public int[,] MultiDimensionalArray; public override bool Equals(object obj) { ObjectWithArrays o = obj as ObjectWithArrays; if (o == null) return false; return EqualityHelpers.ArraysAreEqual(IntArray, o.IntArray) && EqualityHelpers.ArraysAreEqual(StringArray, o.StringArray) && EqualityHelpers.ArraysAreEqual(TreeArray, o.TreeArray) && EqualityHelpers.ArraysAreEqual(ByteArray, o.ByteArray) && EqualityHelpers.ArraysAreEqual(JaggedArray, o.JaggedArray) && EqualityHelpers.ArraysAreEqual(MultiDimensionalArray, o.MultiDimensionalArray); } public override int GetHashCode() => 1; } [Serializable] public enum Colors { Red, Orange, Yellow, Green, Blue, Purple } [Serializable] public enum ByteEnum : byte { } [Serializable] public enum SByteEnum : sbyte { } [Serializable] public enum Int16Enum : short { } [Serializable] public enum UInt16Enum : ushort { } [Serializable] public enum Int32Enum : int { } [Serializable] public enum UInt32Enum : uint { } [Serializable] public enum Int64Enum : long { } [Serializable] public enum UInt64Enum : ulong { } public struct NonSerializableStruct { public int Value; } public class NonSerializableClass { public int Value; } [Serializable] public class SerializableClassDerivedFromNonSerializableClass : NonSerializableClass { public int AnotherValue; } [Serializable] public class SerializableClassWithBadField { public NonSerializableClass Value; } [Serializable] public struct EmptyStruct { } [Serializable] public struct StructWithIntField { public int X; } [Serializable] public struct StructWithStringFields { public string String1; public string String2; } [Serializable] public struct StructContainingOtherStructs { public StructWithStringFields Nested1; public StructWithStringFields Nested2; } [Serializable] public struct StructContainingArraysOfOtherStructs { public StructContainingOtherStructs[] Nested; public override bool Equals(object obj) { if (!(obj is StructContainingArraysOfOtherStructs)) return false; return EqualityHelpers.ArraysAreEqual(Nested, ((StructContainingArraysOfOtherStructs)obj).Nested); } public override int GetHashCode() => 1; } [Serializable] public class BasicISerializableObject : ISerializable { private NonSerializablePair<int, string> _data; public BasicISerializableObject(int value1, string value2) { _data = new NonSerializablePair<int, string> { Value1 = value1, Value2 = value2 }; } public BasicISerializableObject(SerializationInfo info, StreamingContext context) { _data = new NonSerializablePair<int, string> { Value1 = info.GetInt32("Value1"), Value2 = info.GetString("Value2") }; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Value1", _data.Value1); info.AddValue("Value2", _data.Value2); } public override bool Equals(object obj) { var o = obj as BasicISerializableObject; if (o == null) return false; if (_data == null || o._data == null) return _data == o._data; return _data.Value1 == o._data.Value1 && _data.Value2 == o._data.Value2; } public override int GetHashCode() => 1; } [Serializable] public sealed class DerivedISerializableWithNonPublicDeserializationCtor : BasicISerializableObject { public DerivedISerializableWithNonPublicDeserializationCtor(int value1, string value2) : base(value1, value2) { } private DerivedISerializableWithNonPublicDeserializationCtor(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class IncrementCountsDuringRoundtrip { public int IncrementedDuringOnSerializingMethod; public int IncrementedDuringOnSerializedMethod; [NonSerialized] public int IncrementedDuringOnDeserializingMethod; public int IncrementedDuringOnDeserializedMethod; public IncrementCountsDuringRoundtrip(string ignored) { } // non-default ctor so that we can observe changes from OnDeserializing [OnSerializing] private void OnSerializingMethod(StreamingContext context) => IncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => IncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => IncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => IncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class DerivedIncrementCountsDuringRoundtrip : IncrementCountsDuringRoundtrip { internal int DerivedIncrementedDuringOnSerializingMethod; internal int DerivedIncrementedDuringOnSerializedMethod; [NonSerialized] internal int DerivedIncrementedDuringOnDeserializingMethod; internal int DerivedIncrementedDuringOnDeserializedMethod; public DerivedIncrementCountsDuringRoundtrip(string ignored) : base(ignored) { } [OnSerializing] private void OnSerializingMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializingMethod++; [OnSerialized] private void OnSerializedMethod(StreamingContext context) => DerivedIncrementedDuringOnSerializedMethod++; [OnDeserializing] private void OnDeserializingMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializingMethod++; [OnDeserialized] private void OnDeserializedMethod(StreamingContext context) => DerivedIncrementedDuringOnDeserializedMethod++; } [Serializable] public sealed class ObjRefReturnsObj : IObjectReference { public object Real; public object GetRealObject(StreamingContext context) => Real; } internal sealed class NonSerializablePair<T1, T2> { public T1 Value1; public T2 Value2; } internal sealed class NonSerializablePairSurrogate : ISerializationSurrogate { public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { var pair = (NonSerializablePair<int, string>)obj; info.AddValue("Value1", pair.Value1); info.AddValue("Value2", pair.Value2); } public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { var pair = (NonSerializablePair<int, string>)obj; pair.Value1 = info.GetInt32("Value1"); pair.Value2 = info.GetString("Value2"); return pair; } } [Serializable] public class Version1ClassWithoutField { } [Serializable] public class Version2ClassWithoutOptionalField { public object Value; } [Serializable] public class Version2ClassWithOptionalField { [OptionalField(VersionAdded = 2)] public object Value; } [Serializable] public class ObjectWithStateAndMethod { public int State; public int GetState() => State; } [Serializable] public sealed class PointEqualityComparer : IEqualityComparer<Point> { public bool Equals(Point x, Point y) => (x.X == y.X) && (x.Y == y.Y); public int GetHashCode(Point obj) => RuntimeHelpers.GetHashCode(obj); } [Serializable] public class SimpleKeyedCollection : System.Collections.ObjectModel.KeyedCollection<int, Point> { protected override int GetKeyForItem(Point item) { return item.Y; } } [Serializable] internal class GenericTypeWithArg<T> { public T Test; public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var p = (GenericTypeWithArg<T>)obj; return Test.Equals(p.Test); } public override int GetHashCode() { return Test == null ? 0 : Test.GetHashCode(); } } [Serializable] internal class SomeType { public int SomeField; public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var p = (SomeType)obj; return SomeField.Equals(p.SomeField); } public override int GetHashCode() { return SomeField; } } internal static class EqualityHelpers { public static bool ArraysAreEqual<T>(T[] array1, T[] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i])) { return false; } } return true; } public static bool ArraysAreEqual(Array array1, Array array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; if (array1.Rank != array2.Rank) return false; for (int i = 0; i < array1.Rank; i++) { if (array1.GetLength(i) != array2.GetLength(i)) return false; } var e1 = array1.GetEnumerator(); var e2 = array2.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); if (!EqualityComparer<object>.Default.Equals(e1.Current, e2.Current)) { return false; } } return true; } public static bool ArraysAreEqual<T>(T[][] array1, T[][] array2) { if (array1 == null || array2 == null) return array1 == array2; if (array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) { T[] sub1 = array1[i], sub2 = array2[i]; if (sub1 == null || (sub2 == null && (sub1 != sub2))) return false; if (sub1.Length != sub2.Length) return false; for (int j = 0; j < sub1.Length; j++) { if (!EqualityComparer<T>.Default.Equals(sub1[j], sub2[j])) { return false; } } } return true; } } #pragma warning disable 0618 // obsolete warning [Serializable] internal class HashCodeProvider : IHashCodeProvider { public int GetHashCode(object obj) { return 8; } } #pragma warning restore 0618 }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/PermanentAllocatedMemoryBlobs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.NativeFormat; namespace Internal.Runtime.TypeLoader { public sealed partial class PermanentAllocatedMemoryBlobs { // Various functions in the type loader need to create permanent pointers for various purposes. private static PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr s_uintCellValues = new PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr(); private static PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr s_pointerIndirectionCellValues = new PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr(); private class PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr { private LowLevelDictionary<uint, IntPtr> _allocatedBlocks = new LowLevelDictionary<uint, IntPtr>(); private Lock _lock = new Lock(); public unsafe IntPtr GetMemoryBlockForValue(uint value) { using (LockHolder.Hold(_lock)) { IntPtr result; if (_allocatedBlocks.TryGetValue(value, out result)) { return result; } result = MemoryHelpers.AllocateMemory(IntPtr.Size); *(uint*)(result.ToPointer()) = value; _allocatedBlocks.Add(value, result); return result; } } } private class PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr { private LowLevelDictionary<IntPtr, IntPtr> _allocatedBlocks = new LowLevelDictionary<IntPtr, IntPtr>(); private Lock _lock = new Lock(); public unsafe IntPtr GetMemoryBlockForValue(IntPtr value) { using (LockHolder.Hold(_lock)) { IntPtr result; if (_allocatedBlocks.TryGetValue(value, out result)) { return result; } result = MemoryHelpers.AllocateMemory(IntPtr.Size); *(IntPtr*)(result.ToPointer()) = value; _allocatedBlocks.Add(value, result); return result; } } } public static IntPtr GetPointerToUInt(uint value) { return s_uintCellValues.GetMemoryBlockForValue(value); } public static IntPtr GetPointerToIntPtr(IntPtr value) { return s_pointerIndirectionCellValues.GetMemoryBlockForValue(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.NativeFormat; namespace Internal.Runtime.TypeLoader { public sealed partial class PermanentAllocatedMemoryBlobs { // Various functions in the type loader need to create permanent pointers for various purposes. private static PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr s_uintCellValues = new PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr(); private static PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr s_pointerIndirectionCellValues = new PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr(); private class PermanentlyAllocatedMemoryRegions_Uint_In_IntPtr { private LowLevelDictionary<uint, IntPtr> _allocatedBlocks = new LowLevelDictionary<uint, IntPtr>(); private Lock _lock = new Lock(); public unsafe IntPtr GetMemoryBlockForValue(uint value) { using (LockHolder.Hold(_lock)) { IntPtr result; if (_allocatedBlocks.TryGetValue(value, out result)) { return result; } result = MemoryHelpers.AllocateMemory(IntPtr.Size); *(uint*)(result.ToPointer()) = value; _allocatedBlocks.Add(value, result); return result; } } } private class PermanentlyAllocatedMemoryRegions_IntPtr_In_IntPtr { private LowLevelDictionary<IntPtr, IntPtr> _allocatedBlocks = new LowLevelDictionary<IntPtr, IntPtr>(); private Lock _lock = new Lock(); public unsafe IntPtr GetMemoryBlockForValue(IntPtr value) { using (LockHolder.Hold(_lock)) { IntPtr result; if (_allocatedBlocks.TryGetValue(value, out result)) { return result; } result = MemoryHelpers.AllocateMemory(IntPtr.Size); *(IntPtr*)(result.ToPointer()) = value; _allocatedBlocks.Add(value, result); return result; } } } public static IntPtr GetPointerToUInt(uint value) { return s_uintCellValues.GetMemoryBlockForValue(value); } public static IntPtr GetPointerToIntPtr(IntPtr value) { return s_pointerIndirectionCellValues.GetMemoryBlockForValue(value); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/StructureToPtrTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public class StructureToPtrTests { [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15102", TestRuntimes.Mono)] public void StructureToPtr_ByValBoolArray_Success() { var structure1 = new StructWithBoolArray() { array = new bool[] { true, true, true, true } }; int size = Marshal.SizeOf(structure1); IntPtr memory = Marshal.AllocHGlobal(size + sizeof(int)); try { Marshal.WriteInt32(memory, size, 0xFF); Marshal.StructureToPtr(structure1, memory, false); Marshal.StructureToPtr(structure1, memory, true); Assert.Equal(0xFF, Marshal.ReadInt32(memory, size)); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_ByValArrayInStruct_Success() { var structure = new StructWithByValArray() { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 }, new StructWithIntField { value = 5 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_OverflowByValArrayInStruct_Success() { var structure = new StructWithByValArray() { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 }, new StructWithIntField { value = 5 }, new StructWithIntField { value = 6 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.FreeHGlobal(memory); } } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15103", TestRuntimes.Mono)] public void StructureToPtr_ByValDateArray_Success() { var structure = new StructWithDateArray() { array = new DateTime[] { DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.DestroyStructure(memory, structure.GetType()); Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_NullPtr_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr((object)new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true)); AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr(new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true)); } [Fact] public void StructureToPtr_NullStructure_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr(null, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr<object>(null, (IntPtr)1, fDeleteOld: true)); } public static IEnumerable<object[]> StructureToPtr_GenericClass_TestData() { yield return new object[] { new GenericClass<string>() }; yield return new object[] { new GenericStruct<string>() }; } [Theory] [MemberData(nameof(StructureToPtr_GenericClass_TestData))] public void StructureToPtr_GenericObject_ThrowsArgumentException(object o) { AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true)); } public static IEnumerable<object[]> StructureToPtr_NonBlittableObject_TestData() { yield return new object[] { new NonGenericClass() }; yield return new object[] { "string" }; } [Theory] [MemberData(nameof(StructureToPtr_NonBlittableObject_TestData))] public void StructureToPtr_NonBlittable_ThrowsArgumentException(object o) { AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true)); } [Fact] public void StructureToPtr_AutoLayout_ThrowsArgumentException() { var someTs_Auto = new SomeTestStruct_Auto(); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr((object)someTs_Auto, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(someTs_Auto, (IntPtr)1, fDeleteOld: true)); } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15104", TestRuntimes.Mono)] public void StructureToPtr_InvalidLengthByValArrayInStruct_ThrowsArgumentException() { var structure = new StructWithByValArray { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, false)); Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, true)); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public unsafe void StructureToPtr_StructWithBlittableFixedBuffer_In_NonBlittable_Success() { var str = default(NonBlittableContainingBuffer); // Assign values to the bytes. byte* ptr = (byte*)&str.bufferStruct; for (int i = 0; i < sizeof(HasFixedBuffer); i++) ptr[i] = (byte)(0x11 * (i + 1)); HasFixedBuffer* original = (HasFixedBuffer*)ptr; // Marshal the parent struct. var parentStructIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf<NonBlittableContainingBuffer>()); Marshal.StructureToPtr(str, parentStructIntPtr, false); try { HasFixedBuffer* bufferStructPtr = (HasFixedBuffer*)parentStructIntPtr.ToPointer(); Assert.Equal(original->buffer[0], bufferStructPtr->buffer[0]); Assert.Equal(original->buffer[1], bufferStructPtr->buffer[1]); } finally { Marshal.DestroyStructure<NonBlittableContainingBuffer>(parentStructIntPtr); Marshal.FreeHGlobal(parentStructIntPtr); } } [Fact] public unsafe void StructureToPtr_NonBlittableStruct_WithBlittableFixedBuffer_Success() { NonBlittableWithBlittableBuffer x = new NonBlittableWithBlittableBuffer(); x.f[0] = 1; x.f[1] = 2; x.f[2] = 3; x.s = null; int size = Marshal.SizeOf(typeof(NonBlittableWithBlittableBuffer)); byte* p = stackalloc byte[size]; Marshal.StructureToPtr(x, (IntPtr)p, false); NonBlittableWithBlittableBuffer y = Marshal.PtrToStructure<NonBlittableWithBlittableBuffer>((IntPtr)p); Assert.Equal(x.f[0], y.f[0]); Assert.Equal(x.f[1], y.f[1]); Assert.Equal(x.f[2], y.f[2]); } [Fact] public unsafe void StructureToPtr_OpaqueStruct_In_NonBlittableStructure_Success() { NonBlittableWithOpaque x = new NonBlittableWithOpaque(); byte* opaqueData = (byte*)&x.opaque; *opaqueData = 1; int size = Marshal.SizeOf(typeof(NonBlittableWithOpaque)); byte* p = stackalloc byte[size]; Marshal.StructureToPtr(x, (IntPtr)p, false); NonBlittableWithOpaque y = Marshal.PtrToStructure<NonBlittableWithOpaque>((IntPtr)p); byte* marshaledOpaqueData = (byte*)&y.opaque; Assert.Equal(*opaqueData, *marshaledOpaqueData); } [Fact] public void StructureToPtr_Flat_And_Nested_NonBlittableStructure_Success() { MarshalAndDestroy(new NonBlittableStruct_Flat { del = null, b = 0x55, }); MarshalAndDestroy(new NonBlittableStruct_Nested { s = { del = null }, b = 0x55, }); static unsafe void MarshalAndDestroy<T>(T value) where T : struct { int sizeof_T = Marshal.SizeOf<T>(); void* ptr = stackalloc byte[sizeof_T]; Marshal.StructureToPtr(value, (IntPtr)ptr, false); Marshal.DestroyStructure<T>((IntPtr)ptr); } } public struct StructWithIntField { public int value; } public struct StructWithByValArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public StructWithIntField[] array; } public struct StructWithBoolArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public bool[] array; } public struct StructWithDateArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public DateTime[] array; } [StructLayout(LayoutKind.Auto)] public struct SomeTestStruct_Auto { public int i; } [StructLayout(LayoutKind.Sequential)] public unsafe struct HasFixedBuffer { public short member; public fixed byte buffer[2]; public short member2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct NonBlittableContainingBuffer { public HasFixedBuffer bufferStruct; public string str; public IntPtr intPtr; } unsafe struct NonBlittableWithBlittableBuffer { public fixed int f[100]; public string s; } [StructLayout(LayoutKind.Explicit, Size = 1)] public struct OpaqueStruct { } public struct NonBlittableWithOpaque { public OpaqueStruct opaque; public string str; } public struct NonBlittableStruct_Flat { public Delegate del; public byte b; } public struct NonBlittableStruct_Nested { public struct InnerStruct { public Delegate del; } public InnerStruct s; public byte b; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public class StructureToPtrTests { [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15102", TestRuntimes.Mono)] public void StructureToPtr_ByValBoolArray_Success() { var structure1 = new StructWithBoolArray() { array = new bool[] { true, true, true, true } }; int size = Marshal.SizeOf(structure1); IntPtr memory = Marshal.AllocHGlobal(size + sizeof(int)); try { Marshal.WriteInt32(memory, size, 0xFF); Marshal.StructureToPtr(structure1, memory, false); Marshal.StructureToPtr(structure1, memory, true); Assert.Equal(0xFF, Marshal.ReadInt32(memory, size)); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_ByValArrayInStruct_Success() { var structure = new StructWithByValArray() { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 }, new StructWithIntField { value = 5 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_OverflowByValArrayInStruct_Success() { var structure = new StructWithByValArray() { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 }, new StructWithIntField { value = 5 }, new StructWithIntField { value = 6 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.FreeHGlobal(memory); } } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15103", TestRuntimes.Mono)] public void StructureToPtr_ByValDateArray_Success() { var structure = new StructWithDateArray() { array = new DateTime[] { DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, memory, false); Marshal.StructureToPtr(structure, memory, true); } finally { Marshal.DestroyStructure(memory, structure.GetType()); Marshal.FreeHGlobal(memory); } } [Fact] public void StructureToPtr_NullPtr_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr((object)new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true)); AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr(new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true)); } [Fact] public void StructureToPtr_NullStructure_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr(null, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr<object>(null, (IntPtr)1, fDeleteOld: true)); } public static IEnumerable<object[]> StructureToPtr_GenericClass_TestData() { yield return new object[] { new GenericClass<string>() }; yield return new object[] { new GenericStruct<string>() }; } [Theory] [MemberData(nameof(StructureToPtr_GenericClass_TestData))] public void StructureToPtr_GenericObject_ThrowsArgumentException(object o) { AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true)); } public static IEnumerable<object[]> StructureToPtr_NonBlittableObject_TestData() { yield return new object[] { new NonGenericClass() }; yield return new object[] { "string" }; } [Theory] [MemberData(nameof(StructureToPtr_NonBlittableObject_TestData))] public void StructureToPtr_NonBlittable_ThrowsArgumentException(object o) { AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true)); } [Fact] public void StructureToPtr_AutoLayout_ThrowsArgumentException() { var someTs_Auto = new SomeTestStruct_Auto(); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr((object)someTs_Auto, (IntPtr)1, fDeleteOld: true)); AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(someTs_Auto, (IntPtr)1, fDeleteOld: true)); } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15104", TestRuntimes.Mono)] public void StructureToPtr_InvalidLengthByValArrayInStruct_ThrowsArgumentException() { var structure = new StructWithByValArray { array = new StructWithIntField[] { new StructWithIntField { value = 1 }, new StructWithIntField { value = 2 }, new StructWithIntField { value = 3 }, new StructWithIntField { value = 4 } } }; int size = Marshal.SizeOf(structure); IntPtr memory = Marshal.AllocHGlobal(size); try { Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, false)); Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, true)); } finally { Marshal.FreeHGlobal(memory); } } [Fact] public unsafe void StructureToPtr_StructWithBlittableFixedBuffer_In_NonBlittable_Success() { var str = default(NonBlittableContainingBuffer); // Assign values to the bytes. byte* ptr = (byte*)&str.bufferStruct; for (int i = 0; i < sizeof(HasFixedBuffer); i++) ptr[i] = (byte)(0x11 * (i + 1)); HasFixedBuffer* original = (HasFixedBuffer*)ptr; // Marshal the parent struct. var parentStructIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf<NonBlittableContainingBuffer>()); Marshal.StructureToPtr(str, parentStructIntPtr, false); try { HasFixedBuffer* bufferStructPtr = (HasFixedBuffer*)parentStructIntPtr.ToPointer(); Assert.Equal(original->buffer[0], bufferStructPtr->buffer[0]); Assert.Equal(original->buffer[1], bufferStructPtr->buffer[1]); } finally { Marshal.DestroyStructure<NonBlittableContainingBuffer>(parentStructIntPtr); Marshal.FreeHGlobal(parentStructIntPtr); } } [Fact] public unsafe void StructureToPtr_NonBlittableStruct_WithBlittableFixedBuffer_Success() { NonBlittableWithBlittableBuffer x = new NonBlittableWithBlittableBuffer(); x.f[0] = 1; x.f[1] = 2; x.f[2] = 3; x.s = null; int size = Marshal.SizeOf(typeof(NonBlittableWithBlittableBuffer)); byte* p = stackalloc byte[size]; Marshal.StructureToPtr(x, (IntPtr)p, false); NonBlittableWithBlittableBuffer y = Marshal.PtrToStructure<NonBlittableWithBlittableBuffer>((IntPtr)p); Assert.Equal(x.f[0], y.f[0]); Assert.Equal(x.f[1], y.f[1]); Assert.Equal(x.f[2], y.f[2]); } [Fact] public unsafe void StructureToPtr_OpaqueStruct_In_NonBlittableStructure_Success() { NonBlittableWithOpaque x = new NonBlittableWithOpaque(); byte* opaqueData = (byte*)&x.opaque; *opaqueData = 1; int size = Marshal.SizeOf(typeof(NonBlittableWithOpaque)); byte* p = stackalloc byte[size]; Marshal.StructureToPtr(x, (IntPtr)p, false); NonBlittableWithOpaque y = Marshal.PtrToStructure<NonBlittableWithOpaque>((IntPtr)p); byte* marshaledOpaqueData = (byte*)&y.opaque; Assert.Equal(*opaqueData, *marshaledOpaqueData); } [Fact] public void StructureToPtr_Flat_And_Nested_NonBlittableStructure_Success() { MarshalAndDestroy(new NonBlittableStruct_Flat { del = null, b = 0x55, }); MarshalAndDestroy(new NonBlittableStruct_Nested { s = { del = null }, b = 0x55, }); static unsafe void MarshalAndDestroy<T>(T value) where T : struct { int sizeof_T = Marshal.SizeOf<T>(); void* ptr = stackalloc byte[sizeof_T]; Marshal.StructureToPtr(value, (IntPtr)ptr, false); Marshal.DestroyStructure<T>((IntPtr)ptr); } } public struct StructWithIntField { public int value; } public struct StructWithByValArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)] public StructWithIntField[] array; } public struct StructWithBoolArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public bool[] array; } public struct StructWithDateArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public DateTime[] array; } [StructLayout(LayoutKind.Auto)] public struct SomeTestStruct_Auto { public int i; } [StructLayout(LayoutKind.Sequential)] public unsafe struct HasFixedBuffer { public short member; public fixed byte buffer[2]; public short member2; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct NonBlittableContainingBuffer { public HasFixedBuffer bufferStruct; public string str; public IntPtr intPtr; } unsafe struct NonBlittableWithBlittableBuffer { public fixed int f[100]; public string s; } [StructLayout(LayoutKind.Explicit, Size = 1)] public struct OpaqueStruct { } public struct NonBlittableWithOpaque { public OpaqueStruct opaque; public string str; } public struct NonBlittableStruct_Flat { public Delegate del; public byte b; } public struct NonBlittableStruct_Nested { public struct InnerStruct { public Delegate del; } public InnerStruct s; public byte b; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/native/corehost/hostpolicy/hostpolicy_context.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "hostpolicy_context.h" #include "hostpolicy.h" #include "deps_resolver.h" #include <error_codes.h> #include <trace.h> #include "bundle/runner.h" #include "bundle/file_entry.h" namespace { void log_duplicate_property_error(const pal::char_t *property_key) { trace::error(_X("Duplicate runtime property found: %s"), property_key); trace::error(_X("It is invalid to specify values for properties populated by the hosting layer in the the application's .runtimeconfig.json")); } // bundle_probe: // Probe the app-bundle for the file 'path' and return its location ('offset', 'size') if found. // // This function is an API exported to the runtime via the BUNDLE_PROBE property. // This function used by the runtime to probe for bundled assemblies // This function assumes that the currently executing app is a single-file bundle. bool STDMETHODCALLTYPE bundle_probe(const char* path, int64_t* offset, int64_t* size, int64_t* compressedSize) { if (path == nullptr) { return false; } pal::string_t file_path; if (!pal::clr_palstring(path, &file_path)) { trace::warning(_X("Failure probing contents of the application bundle.")); trace::warning(_X("Failed to convert path [%ls] to UTF8"), path); return false; } return bundle::runner_t::app()->probe(file_path, offset, size, compressedSize); } #if defined(NATIVE_LIBS_EMBEDDED) extern "C" const void* CompressionResolveDllImport(const char* name); extern "C" const void* SecurityResolveDllImport(const char* name); extern "C" const void* SystemResolveDllImport(const char* name); extern "C" const void* CryptoResolveDllImport(const char* name); extern "C" const void* CryptoAppleResolveDllImport(const char* name); // pinvoke_override: // Check if given function belongs to one of statically linked libraries and return a pointer if found. const void* STDMETHODCALLTYPE pinvoke_override(const char* libraryName, const char* entrypointName) { #if defined(_WIN32) const char* hostPolicyLib = "hostpolicy.dll"; if (strcmp(libraryName, "System.IO.Compression.Native") == 0) { return CompressionResolveDllImport(entrypointName); } #else const char* hostPolicyLib = "libhostpolicy"; if (strcmp(libraryName, "libSystem.IO.Compression.Native") == 0) { return CompressionResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Net.Security.Native") == 0) { return SecurityResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Native") == 0) { return SystemResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Security.Cryptography.Native.OpenSsl") == 0) { return CryptoResolveDllImport(entrypointName); } #endif // there are two PInvokes in the hostpolicy itself, redirect them here. if (strcmp(libraryName, hostPolicyLib) == 0) { if (strcmp(entrypointName, "corehost_resolve_component_dependencies") == 0) { return (void*)corehost_resolve_component_dependencies; } if (strcmp(entrypointName, "corehost_set_error_writer") == 0) { return (void*)corehost_set_error_writer; } } #if defined(TARGET_OSX) if (strcmp(libraryName, "libSystem.Security.Cryptography.Native.Apple") == 0) { return CryptoAppleResolveDllImport(entrypointName); } #endif return nullptr; } #endif } int hostpolicy_context_t::initialize(hostpolicy_init_t &hostpolicy_init, const arguments_t &args, bool enable_breadcrumbs) { application = args.managed_application; host_mode = hostpolicy_init.host_mode; host_path = args.host_path; breadcrumbs_enabled = enable_breadcrumbs; deps_resolver_t resolver { args, hostpolicy_init.fx_definitions, /* root_framework_rid_fallback_graph */ nullptr, // This means that the fx_definitions contains the root framework hostpolicy_init.is_framework_dependent }; pal::string_t resolver_errors; if (!resolver.valid(&resolver_errors)) { trace::error(_X("Error initializing the dependency resolver: %s"), resolver_errors.c_str()); return StatusCode::ResolverInitFailure; } probe_paths_t probe_paths; // Setup breadcrumbs. if (breadcrumbs_enabled) { pal::string_t policy_name = _STRINGIFY(HOST_POLICY_PKG_NAME); pal::string_t policy_version = _STRINGIFY(HOST_POLICY_PKG_VER); // Always insert the hostpolicy that the code is running on. breadcrumbs.insert(policy_name); breadcrumbs.insert(policy_name + _X(",") + policy_version); if (!resolver.resolve_probe_paths(&probe_paths, &breadcrumbs)) { return StatusCode::ResolverResolveFailure; } } else { if (!resolver.resolve_probe_paths(&probe_paths, nullptr)) { return StatusCode::ResolverResolveFailure; } } clr_path = probe_paths.coreclr; if (clr_path.empty() || !pal::realpath(&clr_path)) { // in a single-file case we may not need coreclr, // otherwise fail early. if (!bundle::info_t::is_single_file_bundle()) { trace::error(_X("Could not resolve CoreCLR path. For more details, enable tracing by setting COREHOST_TRACE environment variable to 1")); return StatusCode::CoreClrResolveFailure; } // save for tracing purposes. clr_dir = clr_path; } else { // Get path in which CoreCLR is present. clr_dir = get_directory(clr_path); } // If this is a self-contained single-file bundle, // System.Private.CoreLib.dll is expected to be within the bundle, unless it is explicitly excluded from the bundle. // In all other cases, // System.Private.CoreLib.dll is expected to be next to CoreCLR.dll - add its path to the TPA list. if (!bundle::info_t::is_single_file_bundle() || bundle::runner_t::app()->probe(CORELIB_NAME) == nullptr) { pal::string_t corelib_path = clr_dir; append_path(&corelib_path, CORELIB_NAME); // Append CoreLib path if (!probe_paths.tpa.empty() && probe_paths.tpa.back() != PATH_SEPARATOR) { probe_paths.tpa.push_back(PATH_SEPARATOR); } probe_paths.tpa.append(corelib_path); } const fx_definition_vector_t &fx_definitions = resolver.get_fx_definitions(); pal::string_t fx_deps_str; if (resolver.is_framework_dependent()) { // Use the root fx to define FX_DEPS_FILE fx_deps_str = get_root_framework(fx_definitions).get_deps_file(); } fx_definition_vector_t::iterator fx_begin; fx_definition_vector_t::iterator fx_end; resolver.get_app_context_deps_files_range(&fx_begin, &fx_end); pal::string_t app_context_deps_str; fx_definition_vector_t::iterator fx_curr = fx_begin; while (fx_curr != fx_end) { if (fx_curr != fx_begin) app_context_deps_str += _X(';'); // For the application's .deps.json if this is single file, 3.1 backward compat // then the path used internally is the bundle path, but externally we need to report // the path to the extraction folder. if (fx_curr == fx_begin && bundle::info_t::is_single_file_bundle() && bundle::runner_t::app()->is_netcoreapp3_compat_mode()) { pal::string_t deps_path = bundle::runner_t::app()->extraction_path(); append_path(&deps_path, get_filename((*fx_curr)->get_deps_file()).c_str()); app_context_deps_str += deps_path; } else { app_context_deps_str += (*fx_curr)->get_deps_file(); } ++fx_curr; } // Build properties for CoreCLR instantiation pal::string_t app_base; resolver.get_app_dir(&app_base); coreclr_properties.add(common_property::TrustedPlatformAssemblies, probe_paths.tpa.c_str()); coreclr_properties.add(common_property::NativeDllSearchDirectories, probe_paths.native.c_str()); coreclr_properties.add(common_property::PlatformResourceRoots, probe_paths.resources.c_str()); coreclr_properties.add(common_property::AppContextBaseDirectory, app_base.c_str()); coreclr_properties.add(common_property::AppContextDepsFiles, app_context_deps_str.c_str()); coreclr_properties.add(common_property::FxDepsFile, fx_deps_str.c_str()); coreclr_properties.add(common_property::ProbingDirectories, resolver.get_lookup_probe_directories().c_str()); coreclr_properties.add(common_property::RuntimeIdentifier, get_current_runtime_id(true /*use_fallback*/).c_str()); bool set_app_paths = false; // Runtime options config properties. for (size_t i = 0; i < hostpolicy_init.cfg_keys.size(); ++i) { // Provide opt-in compatible behavior by using the switch to set APP_PATHS const pal::char_t *key = hostpolicy_init.cfg_keys[i].c_str(); if (pal::strcasecmp(key, _X("Microsoft.NETCore.DotNetHostPolicy.SetAppPaths")) == 0) { set_app_paths = (pal::strcasecmp(hostpolicy_init.cfg_values[i].data(), _X("true")) == 0); } if (!coreclr_properties.add(key, hostpolicy_init.cfg_values[i].c_str())) { log_duplicate_property_error(key); return StatusCode::LibHostDuplicateProperty; } } // App paths. // Note: Keep this check outside of the loop above since the _last_ key wins // and that could indicate the app paths shouldn't be set. if (set_app_paths) { if (!coreclr_properties.add(common_property::AppPaths, app_base.c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::AppPaths)); return StatusCode::LibHostDuplicateProperty; } } // Startup hooks pal::string_t startup_hooks; if (pal::getenv(_X("DOTNET_STARTUP_HOOKS"), &startup_hooks)) { const pal::char_t *config_startup_hooks; if (coreclr_properties.try_get(common_property::StartUpHooks, &config_startup_hooks)) { // env startup hooks shoold have precedence over config startup hooks // therefore append config_startup_hooks AFTER startup_hooks startup_hooks.push_back(PATH_SEPARATOR); startup_hooks.append(config_startup_hooks); } coreclr_properties.add(common_property::StartUpHooks, startup_hooks.c_str()); } // Single-File Bundle Probe if (bundle::info_t::is_single_file_bundle()) { // Encode the bundle_probe function pointer as a string, and pass it to the runtime. pal::stringstream_t ptr_stream; ptr_stream << "0x" << std::hex << (size_t)(&bundle_probe); if (!coreclr_properties.add(common_property::BundleProbe, ptr_stream.str().c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::BundleProbe)); return StatusCode::LibHostDuplicateProperty; } } #if defined(NATIVE_LIBS_EMBEDDED) // PInvoke Override if (bundle::info_t::is_single_file_bundle()) { // Encode the pinvoke_override function pointer as a string, and pass it to the runtime. pal::stringstream_t ptr_stream; ptr_stream << "0x" << std::hex << (size_t)(&pinvoke_override); if (!coreclr_properties.add(common_property::PInvokeOverride, ptr_stream.str().c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::PInvokeOverride)); return StatusCode::LibHostDuplicateProperty; } } #endif #if defined(HOSTPOLICY_EMBEDDED) if (!coreclr_properties.add(common_property::HostPolicyEmbedded, _X("true"))) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::HostPolicyEmbedded)); return StatusCode::LibHostDuplicateProperty; } #endif return StatusCode::Success; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "hostpolicy_context.h" #include "hostpolicy.h" #include "deps_resolver.h" #include <error_codes.h> #include <trace.h> #include "bundle/runner.h" #include "bundle/file_entry.h" namespace { void log_duplicate_property_error(const pal::char_t *property_key) { trace::error(_X("Duplicate runtime property found: %s"), property_key); trace::error(_X("It is invalid to specify values for properties populated by the hosting layer in the the application's .runtimeconfig.json")); } // bundle_probe: // Probe the app-bundle for the file 'path' and return its location ('offset', 'size') if found. // // This function is an API exported to the runtime via the BUNDLE_PROBE property. // This function used by the runtime to probe for bundled assemblies // This function assumes that the currently executing app is a single-file bundle. bool STDMETHODCALLTYPE bundle_probe(const char* path, int64_t* offset, int64_t* size, int64_t* compressedSize) { if (path == nullptr) { return false; } pal::string_t file_path; if (!pal::clr_palstring(path, &file_path)) { trace::warning(_X("Failure probing contents of the application bundle.")); trace::warning(_X("Failed to convert path [%ls] to UTF8"), path); return false; } return bundle::runner_t::app()->probe(file_path, offset, size, compressedSize); } #if defined(NATIVE_LIBS_EMBEDDED) extern "C" const void* CompressionResolveDllImport(const char* name); extern "C" const void* SecurityResolveDllImport(const char* name); extern "C" const void* SystemResolveDllImport(const char* name); extern "C" const void* CryptoResolveDllImport(const char* name); extern "C" const void* CryptoAppleResolveDllImport(const char* name); // pinvoke_override: // Check if given function belongs to one of statically linked libraries and return a pointer if found. const void* STDMETHODCALLTYPE pinvoke_override(const char* libraryName, const char* entrypointName) { #if defined(_WIN32) const char* hostPolicyLib = "hostpolicy.dll"; if (strcmp(libraryName, "System.IO.Compression.Native") == 0) { return CompressionResolveDllImport(entrypointName); } #else const char* hostPolicyLib = "libhostpolicy"; if (strcmp(libraryName, "libSystem.IO.Compression.Native") == 0) { return CompressionResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Net.Security.Native") == 0) { return SecurityResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Native") == 0) { return SystemResolveDllImport(entrypointName); } if (strcmp(libraryName, "libSystem.Security.Cryptography.Native.OpenSsl") == 0) { return CryptoResolveDllImport(entrypointName); } #endif // there are two PInvokes in the hostpolicy itself, redirect them here. if (strcmp(libraryName, hostPolicyLib) == 0) { if (strcmp(entrypointName, "corehost_resolve_component_dependencies") == 0) { return (void*)corehost_resolve_component_dependencies; } if (strcmp(entrypointName, "corehost_set_error_writer") == 0) { return (void*)corehost_set_error_writer; } } #if defined(TARGET_OSX) if (strcmp(libraryName, "libSystem.Security.Cryptography.Native.Apple") == 0) { return CryptoAppleResolveDllImport(entrypointName); } #endif return nullptr; } #endif } int hostpolicy_context_t::initialize(hostpolicy_init_t &hostpolicy_init, const arguments_t &args, bool enable_breadcrumbs) { application = args.managed_application; host_mode = hostpolicy_init.host_mode; host_path = args.host_path; breadcrumbs_enabled = enable_breadcrumbs; deps_resolver_t resolver { args, hostpolicy_init.fx_definitions, /* root_framework_rid_fallback_graph */ nullptr, // This means that the fx_definitions contains the root framework hostpolicy_init.is_framework_dependent }; pal::string_t resolver_errors; if (!resolver.valid(&resolver_errors)) { trace::error(_X("Error initializing the dependency resolver: %s"), resolver_errors.c_str()); return StatusCode::ResolverInitFailure; } probe_paths_t probe_paths; // Setup breadcrumbs. if (breadcrumbs_enabled) { pal::string_t policy_name = _STRINGIFY(HOST_POLICY_PKG_NAME); pal::string_t policy_version = _STRINGIFY(HOST_POLICY_PKG_VER); // Always insert the hostpolicy that the code is running on. breadcrumbs.insert(policy_name); breadcrumbs.insert(policy_name + _X(",") + policy_version); if (!resolver.resolve_probe_paths(&probe_paths, &breadcrumbs)) { return StatusCode::ResolverResolveFailure; } } else { if (!resolver.resolve_probe_paths(&probe_paths, nullptr)) { return StatusCode::ResolverResolveFailure; } } clr_path = probe_paths.coreclr; if (clr_path.empty() || !pal::realpath(&clr_path)) { // in a single-file case we may not need coreclr, // otherwise fail early. if (!bundle::info_t::is_single_file_bundle()) { trace::error(_X("Could not resolve CoreCLR path. For more details, enable tracing by setting COREHOST_TRACE environment variable to 1")); return StatusCode::CoreClrResolveFailure; } // save for tracing purposes. clr_dir = clr_path; } else { // Get path in which CoreCLR is present. clr_dir = get_directory(clr_path); } // If this is a self-contained single-file bundle, // System.Private.CoreLib.dll is expected to be within the bundle, unless it is explicitly excluded from the bundle. // In all other cases, // System.Private.CoreLib.dll is expected to be next to CoreCLR.dll - add its path to the TPA list. if (!bundle::info_t::is_single_file_bundle() || bundle::runner_t::app()->probe(CORELIB_NAME) == nullptr) { pal::string_t corelib_path = clr_dir; append_path(&corelib_path, CORELIB_NAME); // Append CoreLib path if (!probe_paths.tpa.empty() && probe_paths.tpa.back() != PATH_SEPARATOR) { probe_paths.tpa.push_back(PATH_SEPARATOR); } probe_paths.tpa.append(corelib_path); } const fx_definition_vector_t &fx_definitions = resolver.get_fx_definitions(); pal::string_t fx_deps_str; if (resolver.is_framework_dependent()) { // Use the root fx to define FX_DEPS_FILE fx_deps_str = get_root_framework(fx_definitions).get_deps_file(); } fx_definition_vector_t::iterator fx_begin; fx_definition_vector_t::iterator fx_end; resolver.get_app_context_deps_files_range(&fx_begin, &fx_end); pal::string_t app_context_deps_str; fx_definition_vector_t::iterator fx_curr = fx_begin; while (fx_curr != fx_end) { if (fx_curr != fx_begin) app_context_deps_str += _X(';'); // For the application's .deps.json if this is single file, 3.1 backward compat // then the path used internally is the bundle path, but externally we need to report // the path to the extraction folder. if (fx_curr == fx_begin && bundle::info_t::is_single_file_bundle() && bundle::runner_t::app()->is_netcoreapp3_compat_mode()) { pal::string_t deps_path = bundle::runner_t::app()->extraction_path(); append_path(&deps_path, get_filename((*fx_curr)->get_deps_file()).c_str()); app_context_deps_str += deps_path; } else { app_context_deps_str += (*fx_curr)->get_deps_file(); } ++fx_curr; } // Build properties for CoreCLR instantiation pal::string_t app_base; resolver.get_app_dir(&app_base); coreclr_properties.add(common_property::TrustedPlatformAssemblies, probe_paths.tpa.c_str()); coreclr_properties.add(common_property::NativeDllSearchDirectories, probe_paths.native.c_str()); coreclr_properties.add(common_property::PlatformResourceRoots, probe_paths.resources.c_str()); coreclr_properties.add(common_property::AppContextBaseDirectory, app_base.c_str()); coreclr_properties.add(common_property::AppContextDepsFiles, app_context_deps_str.c_str()); coreclr_properties.add(common_property::FxDepsFile, fx_deps_str.c_str()); coreclr_properties.add(common_property::ProbingDirectories, resolver.get_lookup_probe_directories().c_str()); coreclr_properties.add(common_property::RuntimeIdentifier, get_current_runtime_id(true /*use_fallback*/).c_str()); bool set_app_paths = false; // Runtime options config properties. for (size_t i = 0; i < hostpolicy_init.cfg_keys.size(); ++i) { // Provide opt-in compatible behavior by using the switch to set APP_PATHS const pal::char_t *key = hostpolicy_init.cfg_keys[i].c_str(); if (pal::strcasecmp(key, _X("Microsoft.NETCore.DotNetHostPolicy.SetAppPaths")) == 0) { set_app_paths = (pal::strcasecmp(hostpolicy_init.cfg_values[i].data(), _X("true")) == 0); } if (!coreclr_properties.add(key, hostpolicy_init.cfg_values[i].c_str())) { log_duplicate_property_error(key); return StatusCode::LibHostDuplicateProperty; } } // App paths. // Note: Keep this check outside of the loop above since the _last_ key wins // and that could indicate the app paths shouldn't be set. if (set_app_paths) { if (!coreclr_properties.add(common_property::AppPaths, app_base.c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::AppPaths)); return StatusCode::LibHostDuplicateProperty; } } // Startup hooks pal::string_t startup_hooks; if (pal::getenv(_X("DOTNET_STARTUP_HOOKS"), &startup_hooks)) { const pal::char_t *config_startup_hooks; if (coreclr_properties.try_get(common_property::StartUpHooks, &config_startup_hooks)) { // env startup hooks shoold have precedence over config startup hooks // therefore append config_startup_hooks AFTER startup_hooks startup_hooks.push_back(PATH_SEPARATOR); startup_hooks.append(config_startup_hooks); } coreclr_properties.add(common_property::StartUpHooks, startup_hooks.c_str()); } // Single-File Bundle Probe if (bundle::info_t::is_single_file_bundle()) { // Encode the bundle_probe function pointer as a string, and pass it to the runtime. pal::stringstream_t ptr_stream; ptr_stream << "0x" << std::hex << (size_t)(&bundle_probe); if (!coreclr_properties.add(common_property::BundleProbe, ptr_stream.str().c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::BundleProbe)); return StatusCode::LibHostDuplicateProperty; } } #if defined(NATIVE_LIBS_EMBEDDED) // PInvoke Override if (bundle::info_t::is_single_file_bundle()) { // Encode the pinvoke_override function pointer as a string, and pass it to the runtime. pal::stringstream_t ptr_stream; ptr_stream << "0x" << std::hex << (size_t)(&pinvoke_override); if (!coreclr_properties.add(common_property::PInvokeOverride, ptr_stream.str().c_str())) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::PInvokeOverride)); return StatusCode::LibHostDuplicateProperty; } } #endif #if defined(HOSTPOLICY_EMBEDDED) if (!coreclr_properties.add(common_property::HostPolicyEmbedded, _X("true"))) { log_duplicate_property_error(coreclr_property_bag_t::common_property_to_string(common_property::HostPolicyEmbedded)); return StatusCode::LibHostDuplicateProperty; } #endif return StatusCode::Success; }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Net.Security/tests/StressTests/SslStress/docker-compose.yml
version: '3' services: client: build: context: ../../../../ # ~> src/libraries dockerfile: ./System.Net.Security/tests/StressTests/SslStress//${DOCKERFILE:-Dockerfile} links: - server environment: - SSLSTRESS_ARGS=--mode client --server-endpoint server:5001 ${SSLSTRESS_CLIENT_ARGS} server: build: context: ../../../../ # ~> src/libraries dockerfile: ./System.Net.Security/tests/StressTests/SslStress/${DOCKERFILE:-Dockerfile} ports: - "5001:5001" environment: - SSLSTRESS_ARGS=--mode server --server-endpoint 0.0.0.0:5001 ${SSLSTRESS_SERVER_ARGS}
version: '3' services: client: build: context: ../../../../ # ~> src/libraries dockerfile: ./System.Net.Security/tests/StressTests/SslStress//${DOCKERFILE:-Dockerfile} links: - server environment: - SSLSTRESS_ARGS=--mode client --server-endpoint server:5001 ${SSLSTRESS_CLIENT_ARGS} server: build: context: ../../../../ # ~> src/libraries dockerfile: ./System.Net.Security/tests/StressTests/SslStress/${DOCKERFILE:-Dockerfile} ports: - "5001:5001" environment: - SSLSTRESS_ARGS=--mode server --server-endpoint 0.0.0.0:5001 ${SSLSTRESS_SERVER_ARGS}
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Addition.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_AdditionSingle() { var test = new VectorBinaryOpTest__op_AdditionSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__op_AdditionSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionSingle testClass) { var result = _fld1 + _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_AdditionSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBinaryOpTest__op_AdditionSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Single>).GetMethod("op_Addition", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 + _clsVar2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = op1 + op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_AdditionSingle(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 + _fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Addition<Single>(Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_AdditionSingle() { var test = new VectorBinaryOpTest__op_AdditionSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__op_AdditionSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__op_AdditionSingle testClass) { var result = _fld1 + _fld2; Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__op_AdditionSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBinaryOpTest__op_AdditionSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) + Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Single>).GetMethod("op_Addition", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 + _clsVar2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = op1 + op2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__op_AdditionSingle(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 + _fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 + test._fld2; Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (float)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (float)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Addition<Single>(Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; namespace System.ComponentModel.DataAnnotations { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class CompareAttribute : ValidationAttribute { [RequiresUnreferencedCode("The property referenced by 'otherProperty' may be trimmed. Ensure it is preserved.")] public CompareAttribute(string otherProperty!!) : base(SR.CompareAttribute_MustMatch) { OtherProperty = otherProperty; } public string OtherProperty { get; } public string? OtherPropertyDisplayName { get; internal set; } public override bool RequiresValidationContext => true; public override string FormatErrorMessage(string name) => string.Format( CultureInfo.CurrentCulture, ErrorMessageString, name, OtherPropertyDisplayName ?? OtherProperty); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072:UnrecognizedReflectionPattern", Justification = "The ctor is marked with RequiresUnreferencedCode informing the caller to preserve the other property.")] protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty); if (otherPropertyInfo == null) { return new ValidationResult(SR.Format(SR.CompareAttribute_UnknownProperty, OtherProperty)); } if (otherPropertyInfo.GetIndexParameters().Length > 0) { throw new ArgumentException(SR.Format(SR.Common_PropertyNotFound, validationContext.ObjectType.FullName, OtherProperty)); } object? otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (!Equals(value, otherPropertyValue)) { if (OtherPropertyDisplayName == null) { OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo); } string[]? memberNames = validationContext.MemberName != null ? new[] { validationContext.MemberName } : null; return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames); } return null; } private string? GetDisplayNameForProperty(PropertyInfo property) { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(property, true); foreach (Attribute attribute in attributes) { if (attribute is DisplayAttribute display) { return display.GetName(); } } return OtherProperty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; namespace System.ComponentModel.DataAnnotations { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class CompareAttribute : ValidationAttribute { [RequiresUnreferencedCode("The property referenced by 'otherProperty' may be trimmed. Ensure it is preserved.")] public CompareAttribute(string otherProperty!!) : base(SR.CompareAttribute_MustMatch) { OtherProperty = otherProperty; } public string OtherProperty { get; } public string? OtherPropertyDisplayName { get; internal set; } public override bool RequiresValidationContext => true; public override string FormatErrorMessage(string name) => string.Format( CultureInfo.CurrentCulture, ErrorMessageString, name, OtherPropertyDisplayName ?? OtherProperty); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072:UnrecognizedReflectionPattern", Justification = "The ctor is marked with RequiresUnreferencedCode informing the caller to preserve the other property.")] protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty); if (otherPropertyInfo == null) { return new ValidationResult(SR.Format(SR.CompareAttribute_UnknownProperty, OtherProperty)); } if (otherPropertyInfo.GetIndexParameters().Length > 0) { throw new ArgumentException(SR.Format(SR.Common_PropertyNotFound, validationContext.ObjectType.FullName, OtherProperty)); } object? otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (!Equals(value, otherPropertyValue)) { if (OtherPropertyDisplayName == null) { OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo); } string[]? memberNames = validationContext.MemberName != null ? new[] { validationContext.MemberName } : null; return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames); } return null; } private string? GetDisplayNameForProperty(PropertyInfo property) { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(property, true); foreach (Attribute attribute in attributes) { if (attribute is DisplayAttribute display) { return display.GetName(); } } return OtherProperty; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Formats.Cbor/tests/Reader/CborReaderTests.Simple.netcoreapp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; using Xunit; namespace System.Formats.Cbor.Tests { public partial class CborReaderTests { [Theory] [InlineData(0.0, "f90000")] [InlineData(-0.0, "f98000")] [InlineData(1.0, "f93c00")] [InlineData(1.5, "f93e00")] [InlineData(65504.0, "f97bff")] [InlineData(5.960464477539063e-8, "f90001")] [InlineData(0.00006103515625, "f90400")] [InlineData(-4.0, "f9c400")] [InlineData(double.PositiveInfinity, "f97c00")] [InlineData(double.NaN, "f97e00")] [InlineData(double.NegativeInfinity, "f9fc00")] public static void ReadHalf_SingleValue_HappyPath(float expectedResult, string hexEncoding) { byte[] encoding = hexEncoding.HexToByteArray(); var reader = new CborReader(encoding); Assert.Equal(CborReaderState.HalfPrecisionFloat, reader.PeekState()); Half actualResult = reader.ReadHalf(); AssertHelpers.Equal((Half)expectedResult, actualResult); Assert.Equal(CborReaderState.Finished, reader.PeekState()); } [Theory] [InlineData("01")] // integer [InlineData("40")] // empty text string [InlineData("60")] // empty byte string [InlineData("80")] // [] [InlineData("a0")] // {} [InlineData("f6")] // null [InlineData("f4")] // false [InlineData("c202")] // tagged value [InlineData("fa47c35000")] // single-precision float encoding [InlineData("fb7ff0000000000000")] // double-precision float encoding public static void ReadHalf_InvalidTypes_ShouldThrowInvalidOperationException(string hexEncoding) { byte[] encoding = hexEncoding.HexToByteArray(); var reader = new CborReader(encoding); Assert.Throws<InvalidOperationException>(() => reader.ReadHalf()); Assert.Equal(encoding.Length, reader.BytesRemaining); } public static class AssertHelpers { // temporary workaround for xunit's lack of support for Half equality assertions public static void Equal(Half expected, Half actual) { if (Half.IsNaN(expected)) { Assert.True(Half.IsNaN(actual), $"Expected: {expected}\nActual: {actual}"); } else { Assert.Equal(expected, actual); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; using Xunit; namespace System.Formats.Cbor.Tests { public partial class CborReaderTests { [Theory] [InlineData(0.0, "f90000")] [InlineData(-0.0, "f98000")] [InlineData(1.0, "f93c00")] [InlineData(1.5, "f93e00")] [InlineData(65504.0, "f97bff")] [InlineData(5.960464477539063e-8, "f90001")] [InlineData(0.00006103515625, "f90400")] [InlineData(-4.0, "f9c400")] [InlineData(double.PositiveInfinity, "f97c00")] [InlineData(double.NaN, "f97e00")] [InlineData(double.NegativeInfinity, "f9fc00")] public static void ReadHalf_SingleValue_HappyPath(float expectedResult, string hexEncoding) { byte[] encoding = hexEncoding.HexToByteArray(); var reader = new CborReader(encoding); Assert.Equal(CborReaderState.HalfPrecisionFloat, reader.PeekState()); Half actualResult = reader.ReadHalf(); AssertHelpers.Equal((Half)expectedResult, actualResult); Assert.Equal(CborReaderState.Finished, reader.PeekState()); } [Theory] [InlineData("01")] // integer [InlineData("40")] // empty text string [InlineData("60")] // empty byte string [InlineData("80")] // [] [InlineData("a0")] // {} [InlineData("f6")] // null [InlineData("f4")] // false [InlineData("c202")] // tagged value [InlineData("fa47c35000")] // single-precision float encoding [InlineData("fb7ff0000000000000")] // double-precision float encoding public static void ReadHalf_InvalidTypes_ShouldThrowInvalidOperationException(string hexEncoding) { byte[] encoding = hexEncoding.HexToByteArray(); var reader = new CborReader(encoding); Assert.Throws<InvalidOperationException>(() => reader.ReadHalf()); Assert.Equal(encoding.Length, reader.BytesRemaining); } public static class AssertHelpers { // temporary workaround for xunit's lack of support for Half equality assertions public static void Equal(Half expected, Half actual) { if (Half.IsNaN(expected)) { Assert.True(Half.IsNaN(actual), $"Expected: {expected}\nActual: {actual}"); } else { Assert.Equal(expected, actual); } } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/Sqrt_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Sqrt.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Sqrt.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/General/NotSupported/Vector64UInt16AsGeneric_Boolean.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void Vector64UInt16AsGeneric_Boolean() { bool succeeded = false; try { Vector64<bool> result = default(Vector64<ushort>).As<ushort, bool>(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64UInt16AsGeneric_Boolean: RunNotSupportedScenario failed to throw NotSupportedException."); TestLibrary.TestFramework.LogInformation(string.Empty); throw new Exception("One or more scenarios did not complete as expected."); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void Vector64UInt16AsGeneric_Boolean() { bool succeeded = false; try { Vector64<bool> result = default(Vector64<ushort>).As<ushort, bool>(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64UInt16AsGeneric_Boolean: RunNotSupportedScenario failed to throw NotSupportedException."); TestLibrary.TestFramework.LogInformation(string.Empty); throw new Exception("One or more scenarios did not complete as expected."); } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracerConstants.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Threading.Tasks { internal enum AsyncCausalityStatus { Started = 0, Completed = 1, Canceled = 2, Error = 3, } internal enum CausalityRelation { AssignDelegate = 0, Join = 1, Choice = 2, Cancel = 3, Error = 4, } internal enum CausalitySynchronousWork { CompletionNotification = 0, ProgressNotification = 1, Execution = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Threading.Tasks { internal enum AsyncCausalityStatus { Started = 0, Completed = 1, Canceled = 2, Error = 3, } internal enum CausalityRelation { AssignDelegate = 0, Join = 1, Choice = 2, Cancel = 3, Error = 4, } internal enum CausalitySynchronousWork { CompletionNotification = 0, ProgressNotification = 1, Execution = 2, } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; using System.Globalization; using System.Text; namespace System.Runtime.InteropServices { // Exception for COM Interop errors where we don't recognize the HResult. /// <summary> /// Exception class for all errors from COM Interop where we don't /// recognize the HResult. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class COMException : ExternalException { public COMException() : base(SR.Arg_COMException) { HResult = HResults.E_FAIL; } public COMException(string? message) : base(message) { HResult = HResults.E_FAIL; } public COMException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.E_FAIL; } public COMException(string? message, int errorCode) : base(message) { HResult = errorCode; } protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string ToString() { StringBuilder s = new StringBuilder(); s.Append($"{GetType()} (0x{HResult:X8})"); string message = Message; if (!string.IsNullOrEmpty(message)) { s.Append(": ").Append(message); } Exception? innerException = InnerException; if (innerException != null) { s.Append(Environment.NewLineConst + InnerExceptionPrefix).Append(innerException.ToString()); } string? stackTrace = StackTrace; if (stackTrace != null) s.AppendLine().Append(stackTrace); return s.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Serialization; using System.Globalization; using System.Text; namespace System.Runtime.InteropServices { // Exception for COM Interop errors where we don't recognize the HResult. /// <summary> /// Exception class for all errors from COM Interop where we don't /// recognize the HResult. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class COMException : ExternalException { public COMException() : base(SR.Arg_COMException) { HResult = HResults.E_FAIL; } public COMException(string? message) : base(message) { HResult = HResults.E_FAIL; } public COMException(string? message, Exception? inner) : base(message, inner) { HResult = HResults.E_FAIL; } public COMException(string? message, int errorCode) : base(message) { HResult = errorCode; } protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string ToString() { StringBuilder s = new StringBuilder(); s.Append($"{GetType()} (0x{HResult:X8})"); string message = Message; if (!string.IsNullOrEmpty(message)) { s.Append(": ").Append(message); } Exception? innerException = InnerException; if (innerException != null) { s.Append(Environment.NewLineConst + InnerExceptionPrefix).Append(innerException.ToString()); } string? stackTrace = StackTrace; if (stackTrace != null) s.AppendLine().Append(stackTrace); return s.ToString(); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Directed/StructPromote/SpAddr.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System.Runtime.CompilerServices; using System; class SpAddr { // Struct in reg (2 ints) struct S { public int i0; public int i1; } [MethodImpl(MethodImplOptions.NoInlining)] static int Foo(S s0, S s1) { // Console.WriteLine("s0 = [{0}, {1}], s1 = [{2}, {3}]", s0.i0, s0.i1, s1.i0, s1.i1); return s0.i0 + s0.i1 + s1.i0 + s1.i1; } [MethodImpl(MethodImplOptions.NoInlining)] static int M(int i0, int i1, int i2, int i3) { S s0; s0.i0 = i1; s0.i1 = i0; S s1; s1.i0 = i2; s1.i1 = i3; return Foo(s0, s1); // r0 <= r1; r1 <= r0; r2 <= r3; r3 <= r2 } public static int Main(String[] args) { int res = M(1, 2, 3, 4); Console.WriteLine("M(1, 2, 3, 4) is {0}.", res); if (res == 10) return 100; else return 99; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System.Runtime.CompilerServices; using System; class SpAddr { // Struct in reg (2 ints) struct S { public int i0; public int i1; } [MethodImpl(MethodImplOptions.NoInlining)] static int Foo(S s0, S s1) { // Console.WriteLine("s0 = [{0}, {1}], s1 = [{2}, {3}]", s0.i0, s0.i1, s1.i0, s1.i1); return s0.i0 + s0.i1 + s1.i0 + s1.i1; } [MethodImpl(MethodImplOptions.NoInlining)] static int M(int i0, int i1, int i2, int i3) { S s0; s0.i0 = i1; s0.i1 = i0; S s1; s1.i0 = i2; s1.i1 = i3; return Foo(s0, s1); // r0 <= r1; r1 <= r0; r2 <= r3; r3 <= r2 } public static int Main(String[] args) { int res = M(1, 2, 3, 4); Console.WriteLine("M(1, 2, 3, 4) is {0}.", res); if (res == 10) return 100; else return 99; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography/tests/AesProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.Encryption.Aes.Tests { using Aes = System.Security.Cryptography.Aes; public class AesProvider : IAesProvider { public Aes Create() { return Aes.Create(); } } public partial class AesFactory { private static readonly IAesProvider s_provider = new AesProvider(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.Encryption.Aes.Tests { using Aes = System.Security.Cryptography.Aes; public class AesProvider : IAesProvider { public Aes Create() { return Aes.Create(); } } public partial class AesFactory { private static readonly IAesProvider s_provider = new AesProvider(); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/mono/mono/sgen/sgen-archdep.h
/** * \file * Architecture dependent parts of SGen. * * Copyright 2001-2003 Ximian, Inc * Copyright 2003-2010 Novell, Inc. * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_SGENARCHDEP_H__ #define __MONO_SGENARCHDEP_H__ #include <mono/utils/mono-context.h> #if defined(MONO_CROSS_COMPILE) #define REDZONE_SIZE 0 #elif defined(TARGET_X86) #define REDZONE_SIZE 0 #ifndef MONO_ARCH_HAS_MONO_CONTEXT #error 0 #endif #elif defined(TARGET_AMD64) #ifdef HOST_WIN32 /* The Windows x64 ABI defines no "red zone". The ABI states: "All memory beyond the current address of RSP is considered volatile" */ #define REDZONE_SIZE 0 #else #define REDZONE_SIZE 128 #endif #elif defined(TARGET_POWERPC) #define REDZONE_SIZE 224 #elif defined(TARGET_ARM) #define REDZONE_SIZE 0 #elif defined(TARGET_ARM64) #if defined(__APPLE__) #define REDZONE_SIZE 128 #else #define REDZONE_SIZE 0 #endif #elif defined(__mips__) #define REDZONE_SIZE 0 #elif defined(__s390x__) #define REDZONE_SIZE 0 #elif defined(__sparc__) #define REDZONE_SIZE 0 #elif defined (TARGET_RISCV) #define REDZONE_SIZE (0) #elif defined (TARGET_WASM) #define REDZONE_SIZE 0 #endif #endif /* __MONO_SGENARCHDEP_H__ */
/** * \file * Architecture dependent parts of SGen. * * Copyright 2001-2003 Ximian, Inc * Copyright 2003-2010 Novell, Inc. * Copyright (C) 2012 Xamarin Inc * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #ifndef __MONO_SGENARCHDEP_H__ #define __MONO_SGENARCHDEP_H__ #include <mono/utils/mono-context.h> #if defined(MONO_CROSS_COMPILE) #define REDZONE_SIZE 0 #elif defined(TARGET_X86) #define REDZONE_SIZE 0 #ifndef MONO_ARCH_HAS_MONO_CONTEXT #error 0 #endif #elif defined(TARGET_AMD64) #ifdef HOST_WIN32 /* The Windows x64 ABI defines no "red zone". The ABI states: "All memory beyond the current address of RSP is considered volatile" */ #define REDZONE_SIZE 0 #else #define REDZONE_SIZE 128 #endif #elif defined(TARGET_POWERPC) #define REDZONE_SIZE 224 #elif defined(TARGET_ARM) #define REDZONE_SIZE 0 #elif defined(TARGET_ARM64) #if defined(__APPLE__) #define REDZONE_SIZE 128 #else #define REDZONE_SIZE 0 #endif #elif defined(__mips__) #define REDZONE_SIZE 0 #elif defined(__s390x__) #define REDZONE_SIZE 0 #elif defined(__sparc__) #define REDZONE_SIZE 0 #elif defined (TARGET_RISCV) #define REDZONE_SIZE (0) #elif defined (TARGET_WASM) #define REDZONE_SIZE 0 #endif #endif /* __MONO_SGENARCHDEP_H__ */
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/ShiftRightLogical.Int64.64.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt6464() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt6464 { private struct TestStruct { public Vector256<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt6464 testClass) { var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar; private Vector256<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt6464() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt6464() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int64>(Vector256<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt6464() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt6464 { private struct TestStruct { public Vector256<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt6464 testClass) { var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar; private Vector256<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt6464() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt6464() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int64>(Vector256<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/BooleanClassifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Classifies characters as true or false based on a supplied <see cref="BDD"/>.</summary> /// <remarks> /// The classification is determined entirely by the BDD used to construct the classifier, and in fact /// simply calling Contains on the BDD instead of using the classifier would suffice from a correctness /// perspective. The classifier as a wrapper for the BDD is valuable in order to optimize for ASCII, as /// it precomputes the results for ASCII inputs and stores them in a separate table, only falling back /// to using the BDD for non-ASCII. /// </remarks> internal sealed class BooleanClassifier { /// <summary>Lookup table used for ASCII characters.</summary> private readonly bool[] _ascii; /// <summary>BDD used for non-ASCII characters.</summary> private readonly BDD _nonAscii; /// <summary>Create a Boolean classifier.</summary> /// <param name="solver">Character algebra (the algebra is not stored in the classifier)</param> /// <param name="bdd">Elements that map to true.</param> public BooleanClassifier(CharSetSolver solver, BDD bdd) { // We want to optimize for ASCII, so query the BDD for each ASCII character in // order to precompute a lookup table we'll use at match time. var ascii = new bool[128]; for (int i = 0; i < ascii.Length; i++) { ascii[i] = bdd.Contains(i); } // At this point, we'll never consult the BDD for ASCII characters, so as an // optimization we can remove them from the BDD in hopes of simplifying it and making // it faster to query for the non-ASCII characters we will use it for. However, while // this is typically an optimization, it isn't always: the act of removing some // characters from the BDD can actually make the branching more complicated. The // extreme case of this is when the BDD is True, meaning everything maps to True, which // is as simple a BDD as you can get. In such a case, even though it's rare, this would // definitively be a deoptimization, so we avoid doing so. Other trivial cases are handled // by And itself, e.g. if the BDD == False, then And will just return False. if (!bdd.IsFull) { bdd = solver.And(solver._nonAscii, bdd); } _ascii = ascii; _nonAscii = bdd; } /// <summary>Gets whether the specified character is classified as true.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsTrue(char c) { bool[] ascii = _ascii; return c < ascii.Length ? ascii[c] : _nonAscii.Contains(c); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Classifies characters as true or false based on a supplied <see cref="BDD"/>.</summary> /// <remarks> /// The classification is determined entirely by the BDD used to construct the classifier, and in fact /// simply calling Contains on the BDD instead of using the classifier would suffice from a correctness /// perspective. The classifier as a wrapper for the BDD is valuable in order to optimize for ASCII, as /// it precomputes the results for ASCII inputs and stores them in a separate table, only falling back /// to using the BDD for non-ASCII. /// </remarks> internal sealed class BooleanClassifier { /// <summary>Lookup table used for ASCII characters.</summary> private readonly bool[] _ascii; /// <summary>BDD used for non-ASCII characters.</summary> private readonly BDD _nonAscii; /// <summary>Create a Boolean classifier.</summary> /// <param name="solver">Character algebra (the algebra is not stored in the classifier)</param> /// <param name="bdd">Elements that map to true.</param> public BooleanClassifier(CharSetSolver solver, BDD bdd) { // We want to optimize for ASCII, so query the BDD for each ASCII character in // order to precompute a lookup table we'll use at match time. var ascii = new bool[128]; for (int i = 0; i < ascii.Length; i++) { ascii[i] = bdd.Contains(i); } // At this point, we'll never consult the BDD for ASCII characters, so as an // optimization we can remove them from the BDD in hopes of simplifying it and making // it faster to query for the non-ASCII characters we will use it for. However, while // this is typically an optimization, it isn't always: the act of removing some // characters from the BDD can actually make the branching more complicated. The // extreme case of this is when the BDD is True, meaning everything maps to True, which // is as simple a BDD as you can get. In such a case, even though it's rare, this would // definitively be a deoptimization, so we avoid doing so. Other trivial cases are handled // by And itself, e.g. if the BDD == False, then And will just return False. if (!bdd.IsFull) { bdd = solver.And(solver._nonAscii, bdd); } _ascii = ascii; _nonAscii = bdd; } /// <summary>Gets whether the specified character is classified as true.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsTrue(char c) { bool[] ascii = _ascii; return c < ascii.Length ? ascii[c] : _nonAscii.Contains(c); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/Loader/classloader/InterfaceFolding/TestCase3_Nested_J_Nested_I.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Nested_J_Nested_I\TestCase3.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Nested_J_Nested_I\TestCase3.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/mono/mono/utils/mono-hwcap-ppc.c
/** * \file * PowerPC hardware feature detection * * Authors: * Alex Rønne Petersen ([email protected]) * Elijah Taylor ([email protected]) * Miguel de Icaza ([email protected]) * Neale Ferguson ([email protected]) * Paolo Molaro ([email protected]) * Rodrigo Kumpera ([email protected]) * Sebastien Pouliot ([email protected]) * Zoltan Varga ([email protected]) * * Copyright 2003 Ximian, Inc. * Copyright 2003-2011 Novell, Inc * Copyright 2006 Broadcom * Copyright 2007-2008 Andreas Faerber * Copyright 2011-2013 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "mono/utils/mono-hwcap.h" #if defined(__linux__) && defined(HAVE_SYS_AUXV_H) #include <string.h> #include <sys/auxv.h> #elif defined(_AIX) #include <sys/systemcfg.h> #if !defined(POWER_4_ANDUP) #define POWER_4_ANDUP (POWER_4|POWER_5) #endif #if !defined(__power_4_andup) #define __power_4_andup() (_system_configuration.implementation & POWER_4_ANDUP) #endif #if !defined(__power_5_andup) #define __power_5_andup() (_system_configuration.implementation & POWER_5_ANDUP) #endif #endif void mono_hwcap_arch_init (void) { #if defined(__linux__) && defined(HAVE_SYS_AUXV_H) unsigned long hwcap; unsigned long platform; if ((hwcap = getauxval(AT_HWCAP))) { /* PPC_FEATURE_ICACHE_SNOOP */ if (hwcap & 0x00002000) mono_hwcap_ppc_has_icache_snoop = TRUE; /* PPC_FEATURE_POWER4, PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00080000 | 0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2x = TRUE; /* PPC_FEATURE_POWER4, PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00080000 | 0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2x = TRUE; /* PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2_03 = TRUE; /* PPC_FEATURE_64 */ if (hwcap & 0x40000000) mono_hwcap_ppc_is_isa_64 = TRUE; /* PPC_FEATURE_POWER6_EXT */ if (hwcap & 0x00000200) mono_hwcap_ppc_has_move_fpr_gpr = TRUE; } if ((platform = getauxval(AT_PLATFORM))) { const char *str = (const char *) platform; if (!strcmp (str, "ppc970") || (!strncmp (str, "power", 5) && str [5] >= '4' && str [5] <= '7')) mono_hwcap_ppc_has_multiple_ls_units = TRUE; } #elif defined(_AIX) /* Compatible platforms for Mono (V7R1, 6.1.9) require at least P4. */ mono_hwcap_ppc_is_isa_64 = TRUE; mono_hwcap_ppc_is_isa_2x = TRUE; if (__power_5_andup()) { mono_hwcap_ppc_is_isa_2_03 = TRUE; mono_hwcap_ppc_has_icache_snoop = TRUE; } /* not on POWER8 */ if (__power_4() || __power_5() || __power_6() || __power_7()) mono_hwcap_ppc_has_multiple_ls_units = TRUE; /* * This instruction is only available in POWER6 "raw mode" and unlikely * to work; I couldn't get it to work on the POWER6s I tried. */ /* if (__power_6()) mono_hwcap_ppc_has_move_fpr_gpr = TRUE; */ #endif }
/** * \file * PowerPC hardware feature detection * * Authors: * Alex Rønne Petersen ([email protected]) * Elijah Taylor ([email protected]) * Miguel de Icaza ([email protected]) * Neale Ferguson ([email protected]) * Paolo Molaro ([email protected]) * Rodrigo Kumpera ([email protected]) * Sebastien Pouliot ([email protected]) * Zoltan Varga ([email protected]) * * Copyright 2003 Ximian, Inc. * Copyright 2003-2011 Novell, Inc * Copyright 2006 Broadcom * Copyright 2007-2008 Andreas Faerber * Copyright 2011-2013 Xamarin Inc * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "mono/utils/mono-hwcap.h" #if defined(__linux__) && defined(HAVE_SYS_AUXV_H) #include <string.h> #include <sys/auxv.h> #elif defined(_AIX) #include <sys/systemcfg.h> #if !defined(POWER_4_ANDUP) #define POWER_4_ANDUP (POWER_4|POWER_5) #endif #if !defined(__power_4_andup) #define __power_4_andup() (_system_configuration.implementation & POWER_4_ANDUP) #endif #if !defined(__power_5_andup) #define __power_5_andup() (_system_configuration.implementation & POWER_5_ANDUP) #endif #endif void mono_hwcap_arch_init (void) { #if defined(__linux__) && defined(HAVE_SYS_AUXV_H) unsigned long hwcap; unsigned long platform; if ((hwcap = getauxval(AT_HWCAP))) { /* PPC_FEATURE_ICACHE_SNOOP */ if (hwcap & 0x00002000) mono_hwcap_ppc_has_icache_snoop = TRUE; /* PPC_FEATURE_POWER4, PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00080000 | 0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2x = TRUE; /* PPC_FEATURE_POWER4, PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00080000 | 0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2x = TRUE; /* PPC_FEATURE_POWER5, PPC_FEATURE_POWER5_PLUS, PPC_FEATURE_CELL_BE, PPC_FEATURE_PA6T, PPC_FEATURE_ARCH_2_05 */ if (hwcap & (0x00040000 | 0x00020000 | 0x00010000 | 0x00000800 | 0x00001000)) mono_hwcap_ppc_is_isa_2_03 = TRUE; /* PPC_FEATURE_64 */ if (hwcap & 0x40000000) mono_hwcap_ppc_is_isa_64 = TRUE; /* PPC_FEATURE_POWER6_EXT */ if (hwcap & 0x00000200) mono_hwcap_ppc_has_move_fpr_gpr = TRUE; } if ((platform = getauxval(AT_PLATFORM))) { const char *str = (const char *) platform; if (!strcmp (str, "ppc970") || (!strncmp (str, "power", 5) && str [5] >= '4' && str [5] <= '7')) mono_hwcap_ppc_has_multiple_ls_units = TRUE; } #elif defined(_AIX) /* Compatible platforms for Mono (V7R1, 6.1.9) require at least P4. */ mono_hwcap_ppc_is_isa_64 = TRUE; mono_hwcap_ppc_is_isa_2x = TRUE; if (__power_5_andup()) { mono_hwcap_ppc_is_isa_2_03 = TRUE; mono_hwcap_ppc_has_icache_snoop = TRUE; } /* not on POWER8 */ if (__power_4() || __power_5() || __power_6() || __power_7()) mono_hwcap_ppc_has_multiple_ls_units = TRUE; /* * This instruction is only available in POWER6 "raw mode" and unlikely * to work; I couldn't get it to work on the POWER6s I tried. */ /* if (__power_6()) mono_hwcap_ppc_has_move_fpr_gpr = TRUE; */ #endif }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography.Cng/tests/DSACngProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.Dsa.Tests { public class DSACngProvider : IDSAProvider { public DSA Create() { return new DSACng(); } public DSA Create(int keySize) { return new DSACng(keySize); } public bool SupportsFips186_3 => (!PlatformDetection.IsWindows7); public bool SupportsKeyGeneration => true; } public partial class DSAFactory { private static readonly IDSAProvider s_provider = new DSACngProvider(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.Dsa.Tests { public class DSACngProvider : IDSAProvider { public DSA Create() { return new DSACng(); } public DSA Create(int keySize) { return new DSACng(keySize); } public bool SupportsFips186_3 => (!PlatformDetection.IsWindows7); public bool SupportsKeyGeneration => true; } public partial class DSAFactory { private static readonly IDSAProvider s_provider = new DSACngProvider(); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTestBase.nonnetstandard.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public void EnumeratorTest() { this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void KeysTest() { this.KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { this.ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); this.VerifyAvlTreeState(map); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToBuilder()); Assert.Same(map, jointMap); } [Fact] public void AddDescendingTest() { this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { this.AddRemoveEnumerableTestHelper(Empty<int, int>()); } private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Assert.NotNull(map); Assert.NotNull(key); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); this.VerifyAvlTreeState(addedMap); return addedMap; } protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Assert.NotNull(map); for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Assert.NotNull(map); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); this.VerifyAvlTreeState(map); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Assert.NotNull(empty); Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>())); Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>())); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); this.VerifyAvlTreeState(nonEmpty); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); this.VerifyAvlTreeState(halfRemoved); } protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue)); } protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary); private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { Requires.NotNull(collection, nameof(collection)); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T))); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); AssertExtensions.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { var rootNode = this.GetRootNode(dictionary); rootNode.VerifyBalanced(); rootNode.VerifyHeightIsWithinTolerance(dictionary.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public void EnumeratorTest() { this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void KeysTest() { this.KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { this.ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); this.VerifyAvlTreeState(map); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToBuilder()); Assert.Same(map, jointMap); } [Fact] public void AddDescendingTest() { this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { this.AddRemoveEnumerableTestHelper(Empty<int, int>()); } private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Assert.NotNull(map); Assert.NotNull(key); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); this.VerifyAvlTreeState(addedMap); return addedMap; } protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Assert.NotNull(map); for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Assert.NotNull(map); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); this.VerifyAvlTreeState(map); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Assert.NotNull(empty); Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>())); Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>())); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); this.VerifyAvlTreeState(nonEmpty); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); this.VerifyAvlTreeState(halfRemoved); } protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue)); } protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary); private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { Requires.NotNull(collection, nameof(collection)); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T))); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); AssertExtensions.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { var rootNode = this.GetRootNode(dictionary); rootNode.VerifyBalanced(); rootNode.VerifyHeightIsWithinTolerance(dictionary.Count); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/native/external/rapidjson-version.txt
d87b698d0fcc10a5f632ecbc80a9cb2a8fa094a5 https://github.com/Tencent/rapidjson/commit/d87b698d0fcc10a5f632ecbc80a9cb2a8fa094a5 Note: This library is not using a proper release lifecycle. v1.1.0 was the last version released in 2016. Therefore, we are pointing to a random commit from 2019 rather than a version tag.
d87b698d0fcc10a5f632ecbc80a9cb2a8fa094a5 https://github.com/Tencent/rapidjson/commit/d87b698d0fcc10a5f632ecbc80a9cb2a8fa094a5 Note: This library is not using a proper release lifecycle. v1.1.0 was the last version released in 2016. Therefore, we are pointing to a random commit from 2019 rather than a version tag.
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/nativeaot/Runtime/arm/FloatingPoint.asm
;; Licensed to the .NET Foundation under one or more agreements. ;; The .NET Foundation licenses this file to you under the MIT license. #include "AsmMacros.h" TEXTAREA IMPORT fmod NESTED_ENTRY RhpFltRemRev PROLOG_PUSH {r4,lr} ; Save return address (and r4 for stack alignment) ;; The CRT only exports the double form of fmod, so we need to convert our input registers (s0, s1) to ;; doubles (d0, d1). Unfortunately these registers overlap (d0 == s0/s1) so we need to move our inputs ;; elsewhere first. In this case we can move them into s4/s5, which are also volatile and don't need ;; to be preserved. vmov.f32 s4, s0 vmov.f32 s5, s1 ;; Convert s4 and s5 into d0 and d1. vcvt.f64.f32 d0, s4 vcvt.f64.f32 d1, s5 ;; Call the CRT's fmod to calculate the remainder into d0. ldr r12, =fmod blx r12 ;; Convert double result back to single. As far as I can see it's legal to do this directly even ;; though d0 overlaps s0. vcvt.f32.f64 s0, d0 EPILOG_POP {r4,lr} EPILOG_RETURN NESTED_END RhpFltRemRev end
;; Licensed to the .NET Foundation under one or more agreements. ;; The .NET Foundation licenses this file to you under the MIT license. #include "AsmMacros.h" TEXTAREA IMPORT fmod NESTED_ENTRY RhpFltRemRev PROLOG_PUSH {r4,lr} ; Save return address (and r4 for stack alignment) ;; The CRT only exports the double form of fmod, so we need to convert our input registers (s0, s1) to ;; doubles (d0, d1). Unfortunately these registers overlap (d0 == s0/s1) so we need to move our inputs ;; elsewhere first. In this case we can move them into s4/s5, which are also volatile and don't need ;; to be preserved. vmov.f32 s4, s0 vmov.f32 s5, s1 ;; Convert s4 and s5 into d0 and d1. vcvt.f64.f32 d0, s4 vcvt.f64.f32 d1, s5 ;; Call the CRT's fmod to calculate the remainder into d0. ldr r12, =fmod blx r12 ;; Convert double result back to single. As far as I can see it's legal to do this directly even ;; though d0 overlaps s0. vcvt.f32.f64 s0, d0 EPILOG_POP {r4,lr} EPILOG_RETURN NESTED_END RhpFltRemRev end
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/ilverify/ILTests/ShiftTests.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Runtime { } .assembly ShiftTests { } .class public auto ansi beforefieldinit ShiftTestsType extends [System.Runtime]System.Object { .method public hidebysig instance int32 ShiftLeft.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftRight.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shr ret } .method public hidebysig instance int32 ShiftRightUn.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shr.un ret } .method public hidebysig instance int32 ShiftLeft.Int32ByNativeInt_Valid(int32 toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt32_Valid(int64 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByNativeInt_Valid(int64 toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt32_Valid(native int toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByNativeInt_Valid(native int toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByInt64_Invalid_StackUnexpected(int32 toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByFloat64_Invalid_StackUnexpected(int32 toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByInt32Ref_Invalid_StackUnexpected(int32 toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByObject_Invalid_StackUnexpected(int32 toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt64_Invalid_StackUnexpected(int64 toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByFloat64_Invalid_StackUnexpected(int64 toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt32Ref_Invalid_StackUnexpected(int64 toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByObject_Invalid_StackUnexpected(int64 toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt64_Invalid_StackUnexpected(native int toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByFloat64_Invalid_StackUnexpected(native int toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt32Ref_Invalid_StackUnexpected(native int toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByObject_Invalid_StackUnexpected(native int toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance float64 ShiftLeft.Float64ByInt32_Invalid_ExpectedIntegerType(float64 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32& ShiftLeft.Int32RefByInt32_Invalid_ExpectedIntegerType(int32& toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance object ShiftLeft.ObjectByInt32_Invalid_ExpectedIntegerType(object toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern System.Runtime { } .assembly ShiftTests { } .class public auto ansi beforefieldinit ShiftTestsType extends [System.Runtime]System.Object { .method public hidebysig instance int32 ShiftLeft.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftRight.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shr ret } .method public hidebysig instance int32 ShiftRightUn.Int32ByInt32_Valid(int32 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shr.un ret } .method public hidebysig instance int32 ShiftLeft.Int32ByNativeInt_Valid(int32 toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt32_Valid(int64 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByNativeInt_Valid(int64 toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt32_Valid(native int toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByNativeInt_Valid(native int toBeShifted, native int shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByInt64_Invalid_StackUnexpected(int32 toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByFloat64_Invalid_StackUnexpected(int32 toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByInt32Ref_Invalid_StackUnexpected(int32 toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32 ShiftLeft.Int32ByObject_Invalid_StackUnexpected(int32 toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt64_Invalid_StackUnexpected(int64 toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByFloat64_Invalid_StackUnexpected(int64 toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByInt32Ref_Invalid_StackUnexpected(int64 toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int64 ShiftLeft.Int64ByObject_Invalid_StackUnexpected(int64 toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt64_Invalid_StackUnexpected(native int toBeShifted, int64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByFloat64_Invalid_StackUnexpected(native int toBeShifted, float64 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByInt32Ref_Invalid_StackUnexpected(native int toBeShifted, int32& shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance native int ShiftLeft.NativeIntByObject_Invalid_StackUnexpected(native int toBeShifted, object shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance float64 ShiftLeft.Float64ByInt32_Invalid_ExpectedIntegerType(float64 toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance int32& ShiftLeft.Int32RefByInt32_Invalid_ExpectedIntegerType(int32& toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } .method public hidebysig instance object ShiftLeft.ObjectByInt32_Invalid_ExpectedIntegerType(object toBeShifted, int32 shiftBy) cil managed { ldarg.1 ldarg.2 shl ret } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignedDocuments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { internal static class SignedDocuments { internal static readonly byte[] RsaPssDocument = ( "308204EC06092A864886F70D010702A08204DD308204D9020103310D300B0609" + "608648016503040201301F06092A864886F70D010701A0120410546869732069" + "73206120746573740D0AA08202CA308202C63082022EA003020102020900F399" + "4D1706DEC3F8300D06092A864886F70D01010B0500307B310B30090603550406" + "130255533113301106035504080C0A57617368696E67746F6E3110300E060355" + "04070C075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420" + "436F72702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112" + "301006035504030C096C6F63616C686F7374301E170D31363033303230323337" + "35345A170D3137303330323032333735345A307B310B30090603550406130255" + "533113301106035504080C0A57617368696E67746F6E3110300E06035504070C" + "075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420436F72" + "702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112301006" + "035504030C096C6F63616C686F73743081A0300D06092A864886F70D01010105" + "0003818E0030818A02818200BCACB1A5349D7B35A580AC3B3998EB15EBF900EC" + "B329BF1F75717A00B2199C8A18D791B592B7EC52BD5AF2DB0D3B635F0595753D" + "FF7BA7C9872DBF7E3226DEF44A07CA568D1017992C2B41BFE5EC3570824CF1F4" + "B15919FED513FDA56204AF2034A2D08FF04C2CCA49D168FA03FA2FA32FCCD348" + "4C15F0A2E5467C76FC760B55090203010001A350304E301D0603551D0E041604" + "141063CAB14FB14C47DC211C0E0285F3EE5946BF2D301F0603551D2304183016" + "80141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300C0603551D13040530" + "030101FF300D06092A864886F70D01010B050003818200435774FB66802AB3CE" + "2F1392C079483B48CC8913E0BF3B7AD88351E4C15B55CAD3061AA5875900C56B" + "2E7E84BB49CA2A0C1895BD60149C6A0AE983E48370E2144052943B066BD85F70" + "543CF6F2F255C028AE1DC8FB898AD3DCA97BF1D607370287077A4C147268C911" + "8CF9CAD318D2830D3468727E0A3247B3FEB8D87A7DE4F1E2318201D4308201D0" + "02010380141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300B0609608648" + "016503040201A081E4301806092A864886F70D010903310B06092A864886F70D" + "010701301C06092A864886F70D010905310F170D313731303236303130363235" + "5A302F06092A864886F70D0109043122042007849DC26FCBB2F3BD5F57BDF214" + "BAE374575F1BD4E6816482324799417CB379307906092A864886F70D01090F31" + "6C306A300B060960864801650304012A300B0609608648016503040116300B06" + "09608648016503040102300A06082A864886F70D0307300E06082A864886F70D" + "030202020080300D06082A864886F70D0302020140300706052B0E030207300D" + "06082A864886F70D0302020128303D06092A864886F70D01010A3030A00D300B" + "0609608648016503040201A11A301806092A864886F70D010108300B06096086" + "48016503040201A20302015F048181B93E81D141B3C9F159AB0021910635DC72" + "E8E860BE43C28E5D53243D6DC247B7D4F18C20195E80DEDCC75B29C43CE5047A" + "D775B65BFC93589BD748B950C68BADDF1A4673130302BBDA8667D5DDE5EA91EC" + "CB13A9B4C04F1C4842FEB1697B7669C7692DD3BDAE13B5AA8EE3EB5679F3729D" + "1DC4F2EB9DC89B7E8773F2F8C6108C05").HexToByteArray(); public static byte[] RsaPkcs1OneSignerIssuerAndSerialNumber = ( "3082033706092A864886F70D010702A082032830820324020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "463181D73081D40201013032301E311C301A060355040313135253414B657954" + "72616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA3009" + "06052B0E03021A0500300D06092A864886F70D01010105000481805A1717621D" + "450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB34FAA" + "C33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF682D9C" + "A95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80DA27" + "FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3").HexToByteArray(); public static byte[] CounterSignedRsaPkcs1OneSigner = ( "3082044906092A864886F70D010702A082043A30820436020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201E8308201E40201013032301E311C301A060355040313135253414B65" + "795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" + "300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" + "621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" + "4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" + "2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" + "DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A18201" + "0C3082010806092A864886F70D0109063181FA3081F702010380146B4A6B92FD" + "ED07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A03F30180609" + "2A864886F70D010903310B06092A864886F70D010701302306092A864886F70D" + "010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DBA4300D06092A" + "864886F70D0101010500048180962518DEF789B0886C7E6295754ECDBDC4CB9D" + "153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844CBAEDCA9C4A068B2483" + "0E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA79D7312524F111A9B9" + "B0184007139F94E46C816E0E33F010AEB949F5D884DC8987765002F7A643F34B" + "7654E3B2FD5FB34A420279B1EA").HexToByteArray(); public static byte[] NoSignatureSignedWithAttributesAndCounterSignature = ( "3082042406092A864886F70D010702A082041530820411020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201C3308201BF020101301C3017311530130603550403130C44756D6D79" + "205369676E6572020100300906052B0E03021A0500A05D301806092A864886F7" + "0D010903310B06092A864886F70D010701301C06092A864886F70D010905310F" + "170D3137313130313137313731375A302306092A864886F70D01090431160414" + "A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300C06082B06010505070602" + "050004148B70D20D0477A35CD84AB962C10DC52FBA6FAD6BA182010C30820108" + "06092A864886F70D0109063181FA3081F702010380146B4A6B92FDED07EE0119" + "F3674A96D1A70D2A588D300906052B0E03021A0500A03F301806092A864886F7" + "0D010903310B06092A864886F70D010701302306092A864886F70D0109043116" + "0414833378066BDCCBA7047EF6919843D181A57D6479300D06092A864886F70D" + "01010105000481802155D226DD744166E582D040E60535210195050EA00F2C17" + "9897198521DABD0E6B27750FD8BA5F9AAF58B4863B6226456F38553A22453CAF" + "0A0F106766C7AB6F3D6AFD106753DC50F8A6E4F9E5508426D236C2DBB4BCB816" + "2FA42E995CBA16A340FD7C793569DF1B71368E68253299BC74E38312B40B8F52" + "EAEDE10DF414A522").HexToByteArray(); public static byte[] NoSignatureWithNoAttributes = ( "30819B06092A864886F70D010702A0818D30818A020101310B300906052B0E03" + "021A0500302406092A864886F70D010701A01704154D6963726F736F66742043" + "6F72706F726174696F6E31523050020101301C3017311530130603550403130C" + "44756D6D79205369676E6572020100300906052B0E03021A0500300C06082B06" + "01050507060205000414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E").HexToByteArray(); public static byte[] RsaCapiTransfer1_NoEmbeddedCert = ( "3082016606092A864886F70D010702A082015730820153020103310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6E318201193082011502010380146B4A6B92FDED" + "07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A05D301806092A" + "864886F70D010903310B06092A864886F70D010701301C06092A864886F70D01" + "0905310F170D3137313130323135333430345A302306092A864886F70D010904" + "31160414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300D06092A864886" + "F70D01010105000481800EDE3870B8A80B45A21BAEC4681D059B46502E1B1AA6" + "B8920CF50D4D837646A55559B4C05849126C655D95FF3C6C1B420E07DC42629F" + "294EE69822FEA56F32D41B824CBB6BF809B7583C27E77B7AC58DFC925B1C60EA" + "4A67AA84D73FC9E9191D33B36645F17FD6748A2D8B12C6C384C3C734D2727338" + "6211E4518FE2B4ED0147").HexToByteArray(); public static byte[] OneRsaSignerTwoRsaCounterSigners = ( "3082075106092A864886F70D010702A08207423082073E020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08203F9308201E530820152A0030201020210" + "D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F30" + "0D060355040313064D794E616D65301E170D3130303430313038303030305A17" + "0D3131303430313038303030305A3011310F300D060355040313064D794E616D" + "6530819F300D06092A864886F70D010101050003818D0030818902818100B11E" + "30EA87424A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056" + "128322B21F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7" + "322DD353B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA1068" + "70A4B5D50A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203" + "010001A346304430420603551D01043B3039801024859EBF125E76AF3F0D7979" + "B4AC7A96A1133011310F300D060355040313064D794E616D658210D5B5BC1C45" + "8A558845BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830E" + "D485B86D6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD" + "7234B7872611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63" + "CD84E57B5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A2" + "6B192B957304B89531E902FFC91B54B237BB228BE8AFCDA264763082020C3082" + "0179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03" + "021D0500301E311C301A060355040313135253414B65795472616E7366657243" + "61706931301E170D3135303431353037303030305A170D323530343135303730" + "3030305A301E311C301A060355040313135253414B65795472616E7366657243" + "6170693130819F300D06092A864886F70D010101050003818D00308189028181" + "00AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB66" + "71BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1" + "A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD" + "910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9942440" + "8D0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4" + "BA89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E" + "73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B" + "0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3C" + "CF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D0" + "19FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D119" + "57D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1AD" + "B09F291822E99A42964631820307308203030201013032301E311C301A060355" + "040313135253414B65795472616E73666572436170693102105D2FFFF863BABC" + "9B4D3C80AB178A4CCA300906052B0E03021A0500300D06092A864886F70D0101" + "0105000481805A1717621D450130B3463662160EEC06F7AE77E017DD95F294E9" + "7A0BDD433FE6B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE7" + "7B8495091E096EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB" + "09DF57A53B733A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E963" + "2ABF02BE2FE3A182022B3082010806092A864886F70D0109063181FA3081F702" + "010380146B4A6B92FDED07EE0119F3674A96D1A70D2A588D300906052B0E0302" + "1A0500A03F301806092A864886F70D010903310B06092A864886F70D01070130" + "2306092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A5091" + "23F9DBA4300D06092A864886F70D0101010500048180962518DEF789B0886C7E" + "6295754ECDBDC4CB9D153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844C" + "BAEDCA9C4A068B24830E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA" + "79D7312524F111A9B9B0184007139F94E46C816E0E33F010AEB949F5D884DC89" + "87765002F7A643F34B7654E3B2FD5FB34A420279B1EA3082011B06092A864886" + "F70D0109063182010C3082010802010130253011310F300D060355040313064D" + "794E616D650210D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021A" + "0500A03F301806092A864886F70D010903310B06092A864886F70D0107013023" + "06092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123" + "F9DBA4300D06092A864886F70D01010105000481801AA282DBED4D862D7CEA30" + "F803E790BDB0C97EE852778CEEDDCD94BB9304A1552E60A8D36052AC8C2D2875" + "5F3B2F473824100AB3A6ABD4C15ABD77E0FFE13D0DF253BCD99C718FA673B6CB" + "0CBBC68CE5A4AC671298C0A07C7223522E0E7FFF15CEDBAB55AAA99588517674" + "671691065EB083FB729D1E9C04B2BF99A9953DAA5E").HexToByteArray(); public static readonly byte[] RsaPkcs1CounterSignedWithNoSignature = ( "308203E106092A864886F70D010702A08203D2308203CE020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201803082017C0201013032301E311C301A060355040313135253414B65" + "795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" + "300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" + "621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" + "4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" + "2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" + "DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A181A5" + "3081A206092A864886F70D010906318194308191020101301C30173115301306" + "03550403130C44756D6D79205369676E6572020100300906052B0E03021A0500" + "A03F301806092A864886F70D010903310B06092A864886F70D01070130230609" + "2A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DB" + "A4300C06082B060105050706020500041466124B3D99FE06A19BBD3C83C593AB" + "55D875E28B").HexToByteArray(); public static readonly byte[] UnsortedSignerInfos = ( "30820B1E06092A864886F70D010702A0820B0F30820B0B020103310B30090605" + "2B0E03021A0500301006092A864886F70D010701A003040107A0820540308202" + "0C30820179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA30090605" + "2B0E03021D0500301E311C301A060355040313135253414B65795472616E7366" + "65724361706931301E170D3135303431353037303030305A170D323530343135" + "3037303030305A301E311C301A060355040313135253414B65795472616E7366" + "6572436170693130819F300D06092A864886F70D010101050003818D00308189" + "02818100AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75" + "B6EB6671BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B8" + "6570D1A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAAC" + "A965CD910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9" + "9424408D0203010001A3533051304F0603551D0104483046801015432DB116B3" + "5D07E4BA89EDB2469D7AA120301E311C301A060355040313135253414B657954" + "72616E73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA3009" + "06052B0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319" + "265F3CCF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2" + "FCE3D019FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A0" + "75D11957D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083" + "C8D1ADB09F291822E99A4296463082032C30820214A003020102020900E0D8AB" + "6819D7306E300D06092A864886F70D01010B0500303831363034060355040313" + "2D54776F2074686F7573616E6420666F7274792065696768742062697473206F" + "662052534120676F6F646E657373301E170D3137313130333233353131355A17" + "0D3138313130333233353131355A3038313630340603550403132D54776F2074" + "686F7573616E6420666F7274792065696768742062697473206F662052534120" + "676F6F646E65737330820122300D06092A864886F70D01010105000382010F00" + "3082010A028201010096C114A5898D09133EF859F89C1D848BA8CB5258793E05" + "B92D499C55EEFACE274BBBC26803FB813B9C11C6898153CC1745DED2C4D2672F" + "807F0B2D957BC4B65EBC9DDE26E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33" + "C8B57248B3D5E3901D8A38A283D7E25FF8E6F522381EE5484234CFF7B30C1746" + "35418FA89E14C468AD89DCFCBBB535E5AF53510F9EA7F9DA8C1B53375B6DAB95" + "A291439A5648726EE1012E41388E100691642CF6917F5569D8351F2782F435A5" + "79014E8448EEA0C4AECAFF2F476799D88457E2C8BCB56E5E128782B4FE26AFF0" + "720D91D52CCAFE344255808F5271D09F784F787E8323182080915BE0AE15A71D" + "66476D0F264DD084F30203010001A3393037301D0603551D0E04160414745B5F" + "12EF962E84B897E246D399A2BADEA9C5AC30090603551D1304023000300B0603" + "551D0F040403020780300D06092A864886F70D01010B0500038201010087A15D" + "F37FBD6E9DED7A8FFF25E60B731F635469BA01DD14BC03B2A24D99EFD8B894E9" + "493D63EC88C496CB04B33DF25222544F23D43F4023612C4D97B719C1F9431E4D" + "B7A580CDF66A3E5F0DAF89A267DD187ABFFB08361B1F79232376AA5FC5AD384C" + "C2F98FE36C1CEA0B943E1E3961190648889C8ABE8397A5A338843CBFB1D8B212" + "BE46685ACE7B80475CC7C97FC0377936ABD5F664E9C09C463897726650711A11" + "10FA9866BC1C278D95E5636AB96FAE95CCD67FD572A8C727E2C03E7B24245731" + "8BEC1BE52CA5BD9454A0A41140AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC9" + "4F7E3C7D476F298962245563953AD7225EDCEAC8B8509E49292E62D8BF318205" + "A1308202FB0201038014745B5F12EF962E84B897E246D399A2BADEA9C5AC3009" + "06052B0E03021A0500300D06092A864886F70D0101010500048201005E03C5E2" + "E736792EFB1C8632C3A864AA6F0E930717FE02C755C0F94DC671244A371926F6" + "09878DC8CBFCBA6F83A841B24F48952DA5344F2210BFE9B744E3367B1F8399C8" + "96F675923A57E084EBD7DC76A24A1530CD513F0DF6A7703246BF335CC3D09776" + "442942150F1C31B9B212AF48850B44B95EB5BD64105F09723EF6AD4711FD81CD" + "1FC0418E68EA4428CED9E184126761BF2B25756B6D9BC1A0530E56D38F2A0B78" + "3F21D6A5C0703C38F29A2B701B13CAFFCA1DC21C39059E4388E54AEA2519C4E8" + "83C7A6BD78200DCB931CA6AB3D18DBBF46A5444C89B6DFE2F48F32C44BA9C030" + "F399AC677AA323203137D33CEBFBF1BBF9A506309953B23C4100CA7CA18201C0" + "308201BC06092A864886F70D010906318201AD308201A9020101304530383136" + "30340603550403132D54776F2074686F7573616E6420666F7274792065696768" + "742062697473206F662052534120676F6F646E657373020900E0D8AB6819D730" + "6E300906052B0E03021A0500A03F301806092A864886F70D010903310B06092A" + "864886F70D010701302306092A864886F70D0109043116041481BF56A6550A60" + "A649B0D97971C49897635953D0300D06092A864886F70D010101050004820100" + "6E41B7585FEB419005362FEAAAAFB2059E98F8905221A7564F7B0B5510CB221D" + "F3DD914A4CD441EAC1C6746A6EC4FC8399C12A61C6B0F50DDA090F564F3D65B2" + "6D4BDBC1CE3D39CF47CF33B0D269D15A9FAF2169C60887C3E2CC9828B5E16D45" + "DC27A94BAF8D6650EE63D2DBB7DA319B3F61DD18E28AF6FE6DF2CC15C2910BD6" + "0B7E038F2C6E8BAEC35CBBBF9484D4C76ECE041DF534B8713B6537854EFE6D58" + "41768CCBB9A3B729FDDAE07780CB143A3EE5972DCDDF60A38C65CD3FFF35D1B6" + "B76227C1B53831773DA441603F4FB5764D33AADE102F9B85D2CDAEC0E3D6C6E8" + "C24C434BFAA3E12E02202142784ED0EB2D9CDCC276D21474747DCD3E4F4D54FC" + "3081D40201013032301E311C301A060355040313135253414B65795472616E73" + "666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021A0500300D06092A864886F70D01010105000481805EB33C6A9ED5B62240" + "90C431E79F51D70B4F2A7D31ED4ED8C3465F6E01281C3FFA44116238B2D168D8" + "9154136DDB8B4EB31EA685FB719B7384510F5EF077A10DE6A5CA86F4F6D28B58" + "79AFD6CFF0BDA005C2D7CFF53620D28988CBAA44F18AA2D50229FA930B0A7262" + "D780DFDEC0334A97DF872F1D95087DC11A881568AF5B88308201C70201013045" + "3038313630340603550403132D54776F2074686F7573616E6420666F72747920" + "65696768742062697473206F662052534120676F6F646E657373020900E0D8AB" + "6819D7306E300906052B0E03021A0500A05D301806092A864886F70D01090331" + "0B06092A864886F70D010701301C06092A864886F70D010905310F170D313731" + "3130393136303934315A302306092A864886F70D010904311604145D1BE7E9DD" + "A1EE8896BE5B7E34A85EE16452A7B4300D06092A864886F70D01010105000482" + "01000BB9410F23CFD9C1FCB16179612DB871224F5B88A8E2C012DCDBB3699780" + "A3311FD330FFDD6DF1434C52DADD6E07D81FEF145B806E71AF471223914B98CD" + "588CCCDFB50ABE3D991B11D62BD83DE158A9001BAED3549BC49B8C204D25C17B" + "D042756B026692959E321ACC1AFE6BF52C9356FD49936116D2B3D1F6569F8A8B" + "F0FBB2E403AD5788681F3AD131E57390ACB9B8C2EA0BE717F22EFE577EFB1063" + "6AC465469191B7E4B3F03CF8DC6C310A20D2B0891BC27350C7231BC2EAABF129" + "83755B4C0EDF8A0EE99A615D4E8B381C67A7CDB1405D98C2A6285FEDCED5A65F" + "C45C31CD33E3CEB96223DB45E9156B9BD7C8E442C40ED1BB6866C03548616061" + "3DAF").HexToByteArray(); public static byte[] OneDsa1024 = ( "3082044206092A864886F70D010702A08204333082042F020103310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08203913082038D3082034AA0030201020209" + "00AB740A714AA83C92300B060960864801650304030230818D310B3009060355" + "040613025553311330110603550408130A57617368696E67746F6E3110300E06" + "0355040713075265646D6F6E64311E301C060355040A13154D6963726F736F66" + "7420436F72706F726174696F6E3120301E060355040B13172E4E455420467261" + "6D65776F726B2028436F7265465829311530130603550403130C313032342D62" + "697420445341301E170D3135313132353134343030335A170D31353132323531" + "34343030335A30818D310B300906035504061302555331133011060355040813" + "0A57617368696E67746F6E3110300E060355040713075265646D6F6E64311E30" + "1C060355040A13154D6963726F736F667420436F72706F726174696F6E312030" + "1E060355040B13172E4E4554204672616D65776F726B2028436F726546582931" + "1530130603550403130C313032342D62697420445341308201B73082012C0607" + "2A8648CE3804013082011F02818100AEE3309FC7C9DB750D4C3797D333B3B9B2" + "34B462868DB6FFBDED790B7FC8DDD574C2BD6F5E749622507AB2C09DF5EAAD84" + "859FC0706A70BB8C9C8BE22B4890EF2325280E3A7F9A3CE341DBABEF6058D063" + "EA6783478FF8B3B7A45E0CA3F7BAC9995DCFDDD56DF168E91349130F719A4E71" + "7351FAAD1A77EAC043611DC5CC5A7F021500D23428A76743EA3B49C62EF0AA17" + "314A85415F0902818100853F830BDAA738465300CFEE02418E6B07965658EAFD" + "A7E338A2EB1531C0E0CA5EF1A12D9DDC7B550A5A205D1FF87F69500A4E4AF575" + "9F3F6E7F0C48C55396B738164D9E35FB506BD50E090F6A497C70E7E868C61BD4" + "477C1D62922B3DBB40B688DE7C175447E2E826901A109FAD624F1481B276BF63" + "A665D99C87CEE9FD06330381840002818025B8E7078E149BAC35266762362002" + "9F5E4A5D4126E336D56F1189F9FF71EA671B844EBD351514F27B69685DDF716B" + "32F102D60EA520D56F544D19B2F08F5D9BDDA3CBA3A73287E21E559E6A075861" + "94AFAC4F6E721EDCE49DE0029627626D7BD30EEB337311DB4FF62D7608997B6C" + "C32E9C42859820CA7EF399590D5A388C48A330302E302C0603551D1104253023" + "87047F00000187100000000000000000000000000000000182096C6F63616C68" + "6F7374300B0609608648016503040302033000302D021500B9316CC7E05C9F79" + "197E0B41F6FD4E3FCEB72A8A0214075505CCAECB18B7EF4C00F9C069FA3BC780" + "14DE31623060020103801428A2CB1D204C2656A79C931EFAE351AB548248D030" + "0906052B0E03021A0500300906072A8648CE380403042F302D021476DCB780CE" + "D5B308A3630726A85DB97FBC50DFD1021500CDF2649B50500BB7428B9DCA6BEF" + "2C7E7EF1B79C").HexToByteArray(); public static byte[] RsaPkcs1TwoCounterSignaturesInSingleAttribute = ( "30820BBA06092A864886F70D010702A0820BAB30820BA7020101310D300B0609" + "608648016503040201301406092A864886F70D010701A00704050102030405A0" + "82081D308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4D" + "C8300A06082A8648CE3D04030230153113301106035504030C0A454344534120" + "54657374301E170D3135303530313030333730335A170D313630353031303035" + "3730335A30153113301106035504030C0A454344534120546573743059301306" + "072A8648CE3D020106082A8648CE3D030107034200047590F69CA114E92927E0" + "34C997B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA3249" + "6FDAC84E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D" + "0F0101FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5C" + "CFB8220CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E" + "19F1AE4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CB" + "DF434FDD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E30" + "82032C30820214A003020102020900E0D8AB6819D7306E300D06092A864886F7" + "0D01010B05003038313630340603550403132D54776F2074686F7573616E6420" + "666F7274792065696768742062697473206F662052534120676F6F646E657373" + "301E170D3137313130333233353131355A170D3138313130333233353131355A" + "3038313630340603550403132D54776F2074686F7573616E6420666F72747920" + "65696768742062697473206F662052534120676F6F646E65737330820122300D" + "06092A864886F70D01010105000382010F003082010A028201010096C114A589" + "8D09133EF859F89C1D848BA8CB5258793E05B92D499C55EEFACE274BBBC26803" + "FB813B9C11C6898153CC1745DED2C4D2672F807F0B2D957BC4B65EBC9DDE26E2" + "EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33C8B57248B3D5E3901D8A38A283D7" + "E25FF8E6F522381EE5484234CFF7B30C174635418FA89E14C468AD89DCFCBBB5" + "35E5AF53510F9EA7F9DA8C1B53375B6DAB95A291439A5648726EE1012E41388E" + "100691642CF6917F5569D8351F2782F435A579014E8448EEA0C4AECAFF2F4767" + "99D88457E2C8BCB56E5E128782B4FE26AFF0720D91D52CCAFE344255808F5271" + "D09F784F787E8323182080915BE0AE15A71D66476D0F264DD084F30203010001" + "A3393037301D0603551D0E04160414745B5F12EF962E84B897E246D399A2BADE" + "A9C5AC30090603551D1304023000300B0603551D0F040403020780300D06092A" + "864886F70D01010B0500038201010087A15DF37FBD6E9DED7A8FFF25E60B731F" + "635469BA01DD14BC03B2A24D99EFD8B894E9493D63EC88C496CB04B33DF25222" + "544F23D43F4023612C4D97B719C1F9431E4DB7A580CDF66A3E5F0DAF89A267DD" + "187ABFFB08361B1F79232376AA5FC5AD384CC2F98FE36C1CEA0B943E1E396119" + "0648889C8ABE8397A5A338843CBFB1D8B212BE46685ACE7B80475CC7C97FC037" + "7936ABD5F664E9C09C463897726650711A1110FA9866BC1C278D95E5636AB96F" + "AE95CCD67FD572A8C727E2C03E7B242457318BEC1BE52CA5BD9454A0A41140AE" + "96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC94F7E3C7D476F298962245563953A" + "D7225EDCEAC8B8509E49292E62D8BF3082038D3082034AA003020102020900AB" + "740A714AA83C92300B060960864801650304030230818D310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D65" + "776F726B2028436F7265465829311530130603550403130C313032342D626974" + "20445341301E170D3135313132353134343030335A170D313531323235313434" + "3030335A30818D310B3009060355040613025553311330110603550408130A57" + "617368696E67746F6E3110300E060355040713075265646D6F6E64311E301C06" + "0355040A13154D6963726F736F667420436F72706F726174696F6E3120301E06" + "0355040B13172E4E4554204672616D65776F726B2028436F7265465829311530" + "130603550403130C313032342D62697420445341308201B73082012C06072A86" + "48CE3804013082011F02818100AEE3309FC7C9DB750D4C3797D333B3B9B234B4" + "62868DB6FFBDED790B7FC8DDD574C2BD6F5E749622507AB2C09DF5EAAD84859F" + "C0706A70BB8C9C8BE22B4890EF2325280E3A7F9A3CE341DBABEF6058D063EA67" + "83478FF8B3B7A45E0CA3F7BAC9995DCFDDD56DF168E91349130F719A4E717351" + "FAAD1A77EAC043611DC5CC5A7F021500D23428A76743EA3B49C62EF0AA17314A" + "85415F0902818100853F830BDAA738465300CFEE02418E6B07965658EAFDA7E3" + "38A2EB1531C0E0CA5EF1A12D9DDC7B550A5A205D1FF87F69500A4E4AF5759F3F" + "6E7F0C48C55396B738164D9E35FB506BD50E090F6A497C70E7E868C61BD4477C" + "1D62922B3DBB40B688DE7C175447E2E826901A109FAD624F1481B276BF63A665" + "D99C87CEE9FD06330381840002818025B8E7078E149BAC352667623620029F5E" + "4A5D4126E336D56F1189F9FF71EA671B844EBD351514F27B69685DDF716B32F1" + "02D60EA520D56F544D19B2F08F5D9BDDA3CBA3A73287E21E559E6A07586194AF" + "AC4F6E721EDCE49DE0029627626D7BD30EEB337311DB4FF62D7608997B6CC32E" + "9C42859820CA7EF399590D5A388C48A330302E302C0603551D11042530238704" + "7F00000187100000000000000000000000000000000182096C6F63616C686F73" + "74300B0609608648016503040302033000302D021500B9316CC7E05C9F79197E" + "0B41F6FD4E3FCEB72A8A0214075505CCAECB18B7EF4C00F9C069FA3BC78014DE" + "3182035A3082035602010130453038313630340603550403132D54776F207468" + "6F7573616E6420666F7274792065696768742062697473206F66205253412067" + "6F6F646E657373020900E0D8AB6819D7306E300B060960864801650304020130" + "0B06092A864886F70D01010104820100457E2996B3A1AE5C7DC2F4EF4D9010F4" + "8B62B72DFB43F2EDC503FD32408A1058EE7BBCF4750CB4B4242B11A599C40792" + "70D32D15A57FF791FF59836A027E634B9B97E1764173597A9A6155D5ED5365F6" + "5DF14FDD15928ABD63E1409DBF2D1A713D20D80E09EE76BC63775F3FA8638A26" + "ED3816FF87C7CDC8A9299485055BFC38AE158BB6577812AA98436FB54844544A" + "C92CD449690B8107447044580FAE590D8A7326A8D139886C8A4AC8CEEACB0458" + "1666D8447D267F1A9E9CAB20F155E05D5EC055AC863C047B5E1E3A98528EA766" + "7C19B33AD98B2D33ABBD7E607C1DA18BCDB87C626554C277E069CE9EC489BC87" + "2E7DEAED4C642DE5AB10BD2D558EAFB3A18201EA308201E606092A864886F70D" + "010906318201D73082010D02010130819B30818D310B30090603550406130255" + "53311330110603550408130A57617368696E67746F6E3110300E060355040713" + "075265646D6F6E64311E301C060355040A13154D6963726F736F667420436F72" + "706F726174696F6E3120301E060355040B13172E4E4554204672616D65776F72" + "6B2028436F7265465829311530130603550403130C313032342D626974204453" + "41020900AB740A714AA83C92300706052B0E03021AA025302306092A864886F7" + "0D0109043116041409200943E2EDD3DD3B186C5839BDC9B1051903FF30090607" + "2A8648CE380403042F302D0215009FDBE95176B1EC0697155ADDF335E5126A9F" + "59D60214736F650C74E73BEA577151BCFD226FEDC06832E53081C30201013029" + "30153113301106035504030C0A45434453412054657374021035428F3B3C5107" + "AD49E776D6E74C4DC8300B0609608648016503040201A031302F06092A864886" + "F70D01090431220420DF5D49DB775A8F94CAB3129038B200EDE9FCD2AE8F039D" + "B1AB96D9B827D299D2300A06082A8648CE3D0403020447304502202327A60E1A" + "5A798CD29B72C7C7991F968D29DB15C4865BEE83A7E2FD73326CA4022100899F" + "000179F77BFE296783548EAE56BA7F53C0DB0563A27A36A149BAEC9C23AC").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_IssuerSerial_NetFx = ( "3082047C06092A864886F70D010702A082046D30820469020101310B30090605" + "2B0E03021A05003082012406092A864886F70D010703A0820115308201110609" + "2A864886F70D010703A08201023081FF0201003181CC3081C90201003032301E" + "311C301A060355040313135253414B65795472616E7366657243617069310210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D010101050004" + "81800BB53BF3BD028A6B54703899B241CB358CACBF9018A4497A733C27EA223E" + "05BD31099EB80AE04ADBB23A5E397C181A14476668402EFE3BCA08BCA615C743" + "41FA06D56671AA940BF09B6B7B4C6905AD2927DE94960ED03DF141360589979F" + "9944DB48B91AA1B139EB652D6A1BAC48DF33AF14006CD9DB4C09E7DA270733D0" + "DF90302B06092A864886F70D010701301406082A864886F70D03070408E4972B" + "4188B1B4FE80084CBF0A9D37B094EBA08202103082020C30820179A003020102" + "02105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E31" + "1C301A060355040313135253414B65795472616E736665724361706931301E17" + "0D3135303431353037303030305A170D3235303431353037303030305A301E31" + "1C301A060355040313135253414B65795472616E73666572436170693130819F" + "300D06092A864886F70D010101050003818D0030818902818100AA272700586C" + "0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63B" + "A2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6" + "C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF" + "76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A3" + "533051304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7A" + "A120301E311C301A060355040313135253414B65795472616E73666572436170" + "693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D050003" + "81810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8" + "DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D5464697" + "5B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E52" + "91E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A" + "42964631820119308201150201013032301E311C301A06035504031313525341" + "4B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A" + "4CCA300906052B0E03021A0500A03F301806092A864886F70D010903310B0609" + "2A864886F70D010703302306092A864886F70D01090431160414FE46C861E86B" + "719D0F665AFAE48165B56CDFBFD4300D06092A864886F70D0101010500048180" + "32CEE36532673C2734C908A48B6E017FD695BE69FAC21028B6627466B72688D8" + "60FC65F2F18E5C19FED2301351F247DF90217087C5F88D76CA052287E6A2F47F" + "7DA5AC226B4FC202AB0B5B73A24B5C138247F54466621288F2DA941320C4CE89" + "A503ED3E6F63112798A841E55344BEE84E1366E4CF3788C9788C5E86D1879029").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_SKID_NetFx = ( "3082046006092A864886F70D010702A08204513082044D020103310B30090605" + "2B0E03021A05003082012806092A864886F70D010703A0820119048201153082" + "011106092A864886F70D010703A08201023081FF0201003181CC3081C9020100" + "3032301E311C301A060355040313135253414B65795472616E73666572436170" + "693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D0101" + "0105000481803ECF128C059F49199D3344979BD0EBAC2A5443D4F27775B8CFAC" + "7B1F28AFDDAD86097FF34DFB3ED2D514C325B78074D6D17CA14952EA954E860B" + "D5980F2C629C70AE402D3E9E867246E532E345712DFA33C37EF141E2EBFD10F7" + "249CFD193B313825CB7B297FB204DA755F02384659F51D97AB31F867C7E973C6" + "28B9F6E43018302B06092A864886F70D010701301406082A864886F70D030704" + "089FC5129D8AB0CDDE80086D7E35774EFA334AA08202103082020C30820179A0" + "0302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D05" + "00301E311C301A060355040313135253414B65795472616E7366657243617069" + "31301E170D3135303431353037303030305A170D323530343135303730303030" + "5A301E311C301A060355040313135253414B65795472616E7366657243617069" + "3130819F300D06092A864886F70D010101050003818D0030818902818100AA27" + "2700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA95" + "96C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44E" + "C86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37" + "DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203" + "010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA89ED" + "B2469D7AA120301E311C301A060355040313135253414B65795472616E736665" + "72436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF2336" + "9FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70" + "D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653" + "B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F29" + "1822E99A4296463181FA3081F702010380146B4A6B92FDED07EE0119F3674A96" + "D1A70D2A588D300906052B0E03021A0500A03F301806092A864886F70D010903" + "310B06092A864886F70D010703302306092A864886F70D0109043116041435DE" + "A4AE3B383A023271BA27D2D50EC021D40800300D06092A864886F70D01010105" + "00048180386A2EB06AB0ED0111EB37214480CD782243C66105948AD8EAB3236A" + "7ECF135F22B6558F3C601140F6BBDF313F7DB98B3E6277ED5C2407D57323348D" + "A97F6A9653C7C219EE1B0E3F85A970FA6CFC00B53E72484F732916E6067E2F0D" + "4D31EFF51CECD46F3EF245FEF8729C4E1F16C0A3054054477D6C787FC7C94D79" + "A24AC54B").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_IssuerSerial_CoreFx = ( "3082048E06092A864886F70D010702A082047F3082047B020103310D300B0609" + "6086480165030402013082012806092A864886F70D010703A082011904820115" + "3082011106092A864886F70D010703A08201023081FF0201003181CC3081C902" + "01003032301E311C301A060355040313135253414B65795472616E7366657243" + "6170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D" + "01010105000481801B7806566B26A92076D5C9F5A06FBC9AB1D53BD63D3B7F97" + "569B683219C4BA0B285F2F3EF533387EDD7E6BE38DFDD1F33EBA8E5001238BD0" + "E75B9A5C5E2504FD78954B372A2E8B183F4CBD2D239CB72D129E112D0476D9A9" + "A00AF0EC700776F4719BC4838DBAC7F06C671F67B977ABDF449B42C98D28035A" + "194CE2B786E8C8A2302B06092A864886F70D010701301406082A864886F70D03" + "070408B4B41A525B6E8F628008767424A015173966A08202103082020C308201" + "79A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D0500301E311C301A060355040313135253414B65795472616E736665724361" + "706931301E170D3135303431353037303030305A170D32353034313530373030" + "30305A301E311C301A060355040313135253414B65795472616E736665724361" + "70693130819F300D06092A864886F70D010101050003818D0030818902818100" + "AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671" + "BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1" + "D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD91" + "0B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D" + "0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA" + "89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E73" + "666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF" + "23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019" + "FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957" + "D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB0" + "9F291822E99A42964631820125308201210201013032301E311C301A06035504" + "0313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B" + "4D3C80AB178A4CCA300B0609608648016503040201A04B301806092A864886F7" + "0D010903310B06092A864886F70D010703302F06092A864886F70D0109043122" + "042018BEF3F24109B4BCD5BF3D5372EA7A0D16AF6DF46DE9BE5C2373DF065381" + "5E13300B06092A864886F70D01010104818016A02798B3CEC42BE258C85A4BED" + "06099339C9E716B8C72A3330923BE4B6A0538A5DCE031CD710589E8281E24074" + "F26AB6B86CEACF78449B82FF1512F511B5A97ABA4403029E2BA1D837D3F9D230" + "45E0EB3CE59E3AF7E52B814EFCBBCFD7A442327C5C408D166D4302AEFF807ECB" + "D107C811DC66EC35FE167408B58FB03B7F84").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_SKID_CoreFx = ( "3082047006092A864886F70D010702A08204613082045D020103310D300B0609" + "6086480165030402013082012806092A864886F70D010703A082011904820115" + "3082011106092A864886F70D010703A08201023081FF0201003181CC3081C902" + "01003032301E311C301A060355040313135253414B65795472616E7366657243" + "6170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D" + "0101010500048180724D9D5E0D2110B8147589120524B1D1E7019A3F436AD459" + "3DF555413423AE28FCBA01548B20FDCA21901ECF6B54331542CECD4326C7E292" + "54AA563D7F38C2287C146B648E6779FA3843FB0F11A3726265266DF87BAAF04B" + "AA1DD4825B9FFFEBD1DC47414EA4978580A03484B9159E57045018DAA3054704" + "84046F89465169A0302B06092A864886F70D010701301406082A864886F70D03" + "0704087E74D74C2652F5198008930CBA811F9E9E15A08202103082020C308201" + "79A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D0500301E311C301A060355040313135253414B65795472616E736665724361" + "706931301E170D3135303431353037303030305A170D32353034313530373030" + "30305A301E311C301A060355040313135253414B65795472616E736665724361" + "70693130819F300D06092A864886F70D010101050003818D0030818902818100" + "AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671" + "BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1" + "D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD91" + "0B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D" + "0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA" + "89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E73" + "666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF" + "23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019" + "FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957" + "D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB0" + "9F291822E99A429646318201073082010302010380146B4A6B92FDED07EE0119" + "F3674A96D1A70D2A588D300B0609608648016503040201A04B301806092A8648" + "86F70D010903310B06092A864886F70D010703302F06092A864886F70D010904" + "31220420873B6A3B7CE192922129761C3EDD8D68C4A6B0369F3BF5B3D30B0A9E" + "2336A8F4300B06092A864886F70D0101010481807D31B3260AE00DE3992DDD1E" + "B01FDECA28053F2B87AA723CCD27B92896E3199F7C4B3B4A391C181899E5CBD1" + "4A4BCDDFF6DC6CD10CA118DAA62E32589F066D1669D2948E51B5363B7BEE2BA9" + "351CDE1791D118E552F0C8A4FB58EC7C34F5BAB2D562B415C4B3F673179B8410" + "86A9B0F03ED56DBD4FA9CBB775307C9BB3045F72").HexToByteArray(); // This document signature was generated without sorting the attributes, // it ensures a compatibility fallback in CheckSignature. internal static readonly byte[] DigiCertTimeStampToken = ( "30820EC406092A864886F70D010702A0820EB530820EB1020103310F300D0609" + "608648016503040201050030818A060B2A864886F70D0109100104A07B047930" + "7702010106096086480186FD6C07013031300D06096086480165030402010500" + "04205A3B99F86CE06F5639C3ED7D0E16AE44A5CD58ABA0F6853A2AF389F91B6C" + "7D7F02104E640CDE5C761BFF32FA0ADEA58C5F56180F32303138303731373136" + "313732315A0211457A3006B9483730D09772076C4B74BDF8A0820BBB30820682" + "3082056AA003020102021009C0FC46C8044213B5598BAF284F4E41300D06092A" + "864886F70D01010B05003072310B300906035504061302555331153013060355" + "040A130C446967694365727420496E6331193017060355040B13107777772E64" + "696769636572742E636F6D3131302F0603550403132844696769436572742053" + "48413220417373757265642049442054696D657374616D70696E67204341301E" + "170D3137303130343030303030305A170D3238303131383030303030305A304C" + "310B30090603550406130255533111300F060355040A13084469676943657274" + "312A302806035504031321446967694365727420534841322054696D65737461" + "6D7020526573706F6E64657230820122300D06092A864886F70D010101050003" + "82010F003082010A02820101009E95986A343B731BA87EFCC7BE296989C76826" + "465F3D8D62738781A3A19CF0B75B24375A92D4F459D77689E4DCD527F0D566BC" + "0AEEB42B3167AC58C54A91592B451E0901D664B359EE8D664DFB235ECC100D0B" + "8A67EF52AEA00890C252F7F5A8B56E9B2C7B9DE7B53EFB78CD325018BF40B54C" + "8CBB57F4A04F11456C4242B9E5AFD6DFF4A77C0A68960FD25F2957CEFB1D32FF" + "F411A11322FB12CBEFD753D2EB97CBA2AC1B1D9D58215182C2C2DEEA2B3F2C22" + "84D043EC3B3B3F47C4F656DC453798B46B74B559AF785769C80F090278DDD853" + "C199DB60C49DEAAEAFE07E864A5CA95861A85E748A012868724EA7869DB50252" + "87706648D38EEF8124CCDCD8650203010001A382033830820334300E0603551D" + "0F0101FF040403020780300C0603551D130101FF0402300030160603551D2501" + "01FF040C300A06082B06010505070308308201BF0603551D20048201B6308201" + "B2308201A106096086480186FD6C070130820192302806082B06010505070201" + "161C68747470733A2F2F7777772E64696769636572742E636F6D2F4350533082" + "016406082B06010505070202308201561E8201520041006E0079002000750073" + "00650020006F0066002000740068006900730020004300650072007400690066" + "0069006300610074006500200063006F006E0073007400690074007500740065" + "007300200061006300630065007000740061006E006300650020006F00660020" + "007400680065002000440069006700690043006500720074002000430050002F" + "00430050005300200061006E00640020007400680065002000520065006C0079" + "0069006E0067002000500061007200740079002000410067007200650065006D" + "0065006E00740020007700680069006300680020006C0069006D006900740020" + "006C0069006100620069006C00690074007900200061006E0064002000610072" + "006500200069006E0063006F00720070006F0072006100740065006400200068" + "0065007200650069006E0020006200790020007200650066006500720065006E" + "00630065002E300B06096086480186FD6C0315301F0603551D23041830168014" + "F4B6E1201DFE29AED2E461A5B2A225B2C817356E301D0603551D0E04160414E1" + "A7324AEE0121287D54D5F207926EB4070F3D8730710603551D1F046A30683032" + "A030A02E862C687474703A2F2F63726C332E64696769636572742E636F6D2F73" + "6861322D617373757265642D74732E63726C3032A030A02E862C687474703A2F" + "2F63726C342E64696769636572742E636F6D2F736861322D617373757265642D" + "74732E63726C30818506082B0601050507010104793077302406082B06010505" + "0730018618687474703A2F2F6F6373702E64696769636572742E636F6D304F06" + "082B060105050730028643687474703A2F2F636163657274732E646967696365" + "72742E636F6D2F44696769436572745348413241737375726564494454696D65" + "7374616D70696E6743412E637274300D06092A864886F70D01010B0500038201" + "01001EF0418232AEEDF1B43513DC50C2D597AE22229D0E0EAF33D34CFD7CBF6F" + "0111A79465225CC622A1C889526B9A8C735CD95E3F32DE16604C8B36FD31990A" + "BDC184B78D1DEF8926130556F347CD475BAD84B238AF6A23B545E31E88324680" + "D2B7A69922FDC178CFF58BD80C8C0509EE44E680D56D70CC9F531E27DD2A48DE" + "DA9365AD6E65A399A7C2400E73CC584F8F4528E5BC9C88E628CE605D2D255D8B" + "732EA50D5B51DA9A4EFF50058928DAF278BBD258788D44A7AC3A009178698964" + "04D35D96DF2ABFF9A54C2C93FFE68ADD82ACF1D2B3A2869AC15589566A473FFA" + "D6339543358905785A3A69DA22B80443D36F6835367A143E45E99864860F130C" + "264A3082053130820419A00302010202100AA125D6D6321B7E41E405DA3697C2" + "15300D06092A864886F70D01010B05003065310B300906035504061302555331" + "153013060355040A130C446967694365727420496E6331193017060355040B13" + "107777772E64696769636572742E636F6D312430220603550403131B44696769" + "43657274204173737572656420494420526F6F74204341301E170D3136303130" + "373132303030305A170D3331303130373132303030305A3072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "0313284469676943657274205348413220417373757265642049442054696D65" + "7374616D70696E6720434130820122300D06092A864886F70D01010105000382" + "010F003082010A0282010100BDD032EE4BCD8F7FDDA9BA8299C539542857B623" + "4AC40E07453351107DD0F97D4D687EE7B6A0F48DB388E497BF63219098BF13BC" + "57D3C3E17E08D66A140038F72E1E3BEECCA6F63259FE5F653FE09BEBE3464706" + "1A557E0B277EC0A2F5A0E0DE223F0EFF7E95FBF3A3BA223E18AC11E4F099036D" + "3B857C09D3EE5DC89A0B54E3A809716BE0CF22100F75CF71724E0AADDF403A5C" + "B751E1A17914C64D2423305DBCEC3C606AAC2F07CCFDF0EA47D988505EFD666E" + "56612729898451E682E74650FD942A2CA7E4753EBA980F847F9F3114D6ADD5F2" + "64CB7B1E05D084197217F11706EF3DCDD64DEF0642FDA2532A4F851DC41D3CAF" + "CFDAAC10F5DDACACE956FF930203010001A38201CE308201CA301D0603551D0E" + "04160414F4B6E1201DFE29AED2E461A5B2A225B2C817356E301F0603551D2304" + "183016801445EBA2AFF492CB82312D518BA7A7219DF36DC80F30120603551D13" + "0101FF040830060101FF020100300E0603551D0F0101FF040403020186301306" + "03551D25040C300A06082B06010505070308307906082B06010505070101046D" + "306B302406082B060105050730018618687474703A2F2F6F6373702E64696769" + "636572742E636F6D304306082B060105050730028637687474703A2F2F636163" + "657274732E64696769636572742E636F6D2F4469676943657274417373757265" + "644944526F6F7443412E6372743081810603551D1F047A3078303AA038A03686" + "34687474703A2F2F63726C342E64696769636572742E636F6D2F446967694365" + "7274417373757265644944526F6F7443412E63726C303AA038A0368634687474" + "703A2F2F63726C332E64696769636572742E636F6D2F44696769436572744173" + "73757265644944526F6F7443412E63726C30500603551D20044930473038060A" + "6086480186FD6C000204302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F435053300B06096086480186FD" + "6C0701300D06092A864886F70D01010B05000382010100719512E951875669CD" + "EFDDDA7CAA637AB378CF06374084EF4B84BFCACF0302FDC5A7C30E20422CAF77" + "F32B1F0C215A2AB705341D6AAE99F827A266BF09AA60DF76A43A930FF8B2D1D8" + "7C1962E85E82251EC4BA1C7B2C21E2D65B2C1435430468B2DB7502E072C798D6" + "3C64E51F4810185F8938614D62462487638C91522CAF2989E5781FD60B14A580" + "D7124770B375D59385937EB69267FB536189A8F56B96C0F458690D7CC801B1B9" + "2875B7996385228C61CA79947E59FC8C0FE36FB50126B66CA5EE875121E45860" + "9BBA0C2D2B6DA2C47EBBC4252B4702087C49AE13B6E17C424228C61856CF4134" + "B6665DB6747BF55633222F2236B24BA24A95D8F5A68E523182024D3082024902" + "01013081863072310B300906035504061302555331153013060355040A130C44" + "6967694365727420496E6331193017060355040B13107777772E646967696365" + "72742E636F6D3131302F06035504031328446967694365727420534841322041" + "7373757265642049442054696D657374616D70696E67204341021009C0FC46C8" + "044213B5598BAF284F4E41300D06096086480165030402010500A08198301A06" + "092A864886F70D010903310D060B2A864886F70D0109100104301C06092A8648" + "86F70D010905310F170D3138303731373136313732315A302F06092A864886F7" + "0D01090431220420E66606A88254749C2E5575722F93AA67174FDDDB7703B7E6" + "FAD6B3FE000F3DE2302B060B2A864886F70D010910020C311C301A3018301604" + "14400191475C98891DEBA104AF47091B5EB6D4CBCB300D06092A864886F70D01" + "01010500048201005AF349DE87550378C702ED31AE6DD6D50E6B24298DB2DFD6" + "1396C6FA3E465FE7323ACD65AE157C06BCB993551F33702C6D1F6951AECDE74A" + "969E41A8F0F95188780F990EAF6B129633CDE42FF149501BFAC05C516B6DA9EF" + "E492488013928BA801D66C32EFE7EEDFF22DC96DDA4783674EEE8231E7A3AD8A" + "98A506DABB68D6337D7FFDBD2F7112AF2FEE718CF6E7E5544DB7B4BDCD8191EB" + "C73D568EE4D2A30B8478D676910E3B4EB868010AAF22400198D0593F987C86A9" + "101711B9C6AC5C5776923C699E772B07864755C1AC50F387655C4E67DB356207" + "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" + "9DA4C01214D4FA24").HexToByteArray(); internal static readonly byte[] RsaPkcs1Sha256WithRsa = ( "3082071B06092A864886F70D010702A082070C30820708020101310F300D0609" + "6086480165030402010500301606092A864886F70D010701A009040700010203" + "040506A08205223082051E30820406A00302010202100D85090F3FACFF0A9008" + "A12A9FB00A54300D06092A864886F70D01010B05003072310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D3131302F060355040313" + "2844696769436572742053484132204173737572656420494420436F64652053" + "69676E696E67204341301E170D3138303832393030303030305A170D31393039" + "30333132303030305A305B310B3009060355040613025553310B300906035504" + "0813025641311330110603550407130A416C6578616E64726961311430120603" + "55040A130B4B6576696E204A6F6E6573311430120603550403130B4B6576696E" + "204A6F6E657330820122300D06092A864886F70D01010105000382010F003082" + "010A0282010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D299" + "1C962D0A22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A35" + "80CC96A11F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F77" + "9CB4979544514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456" + "A8497758D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB" + "0780CD258F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214" + "533B2A47977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200" + "943EFB7D0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A" + "8C461760E6A4F30203010001A38201C5308201C1301F0603551D230418301680" + "145AC4B97B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E04160414" + "33795EB2D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF0404" + "0302078030130603551D25040C300A06082B0601050507030330770603551D1F" + "0470306E3035A033A031862F687474703A2F2F63726C332E6469676963657274" + "2E636F6D2F736861322D617373757265642D63732D67312E63726C3035A033A0" + "31862F687474703A2F2F63726C342E64696769636572742E636F6D2F73686132" + "2D617373757265642D63732D67312E63726C304C0603551D2004453043303706" + "096086480186FD6C0301302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F4350533008060667810C010401" + "30818406082B0601050507010104783076302406082B06010505073001861868" + "7474703A2F2F6F6373702E64696769636572742E636F6D304E06082B06010505" + "0730028642687474703A2F2F636163657274732E64696769636572742E636F6D" + "2F446967694365727453484132417373757265644944436F64655369676E696E" + "6743412E637274300C0603551D130101FF04023000300D06092A864886F70D01" + "010B0500038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD9" + "9BFC9B62E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A7" + "3041686C326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD50414" + "79BDBB6B93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE" + "9934817036338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D9" + "50EE0235B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02" + "A75F2D7EC07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660B" + "B452E35922D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16" + "819DC990F5F45CDE21318201B2308201AE0201013081863072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "03132844696769436572742053484132204173737572656420494420436F6465" + "205369676E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300D06" + "096086480165030402010500300D06092A864886F70D01010B050004820100E2" + "980C5A30EC00729D1CFA826D7A65B43FF6806B5E0ABA23A78E4F1CAA3F6436EF" + "00941C6947A9B8F20D0757B5346CF640AA217F7361BEEFF2BC997FB1D3597BF3" + "D7457BD4A94062FB03660F9D86710BE2FC99876A848251F4965E1B16192714C8" + "F9788C09CCDE83603ADC919297BA496E921B95F3BD9554A873E09912640FCFAA" + "D9DD1441D1851E637031D390C038223AE64B048E806462DDBAC98C156BE2EE47" + "2B78166BDB1612848B535ADC3F0E7BE52991A17F48AFDCCC1698A236BA338930" + "50EBAAC4460DAA35185C16670F597E0E6E0CB0AA83F51AAEF452F3367DD9350A" + "8A49A5A8F79DF8E921303AB5D6646A482F0F59D9980310E1AE3EE8D77CB857").HexToByteArray(); internal static readonly byte[] RsaPkcs1SignedSha1DeclaredSha256WithRsa = ( "3082071306092A864886F70D010702A082070430820700020101310B30090605" + "2B0E03021A0500301606092A864886F70D010701A009040700010203040506A0" + "8205223082051E30820406A00302010202100D85090F3FACFF0A9008A12A9FB0" + "0A54300D06092A864886F70D01010B05003072310B3009060355040613025553" + "31153013060355040A130C446967694365727420496E6331193017060355040B" + "13107777772E64696769636572742E636F6D3131302F06035504031328446967" + "69436572742053484132204173737572656420494420436F6465205369676E69" + "6E67204341301E170D3138303832393030303030305A170D3139303930333132" + "303030305A305B310B3009060355040613025553310B30090603550408130256" + "41311330110603550407130A416C6578616E6472696131143012060355040A13" + "0B4B6576696E204A6F6E6573311430120603550403130B4B6576696E204A6F6E" + "657330820122300D06092A864886F70D01010105000382010F003082010A0282" + "010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D2991C962D0A" + "22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A3580CC96A1" + "1F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F779CB49795" + "44514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456A8497758" + "D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB0780CD25" + "8F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214533B2A47" + "977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200943EFB7D" + "0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A8C461760" + "E6A4F30203010001A38201C5308201C1301F0603551D230418301680145AC4B9" + "7B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E0416041433795EB2" + "D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF040403020780" + "30130603551D25040C300A06082B0601050507030330770603551D1F0470306E" + "3035A033A031862F687474703A2F2F63726C332E64696769636572742E636F6D" + "2F736861322D617373757265642D63732D67312E63726C3035A033A031862F68" + "7474703A2F2F63726C342E64696769636572742E636F6D2F736861322D617373" + "757265642D63732D67312E63726C304C0603551D200445304330370609608648" + "0186FD6C0301302A302806082B06010505070201161C68747470733A2F2F7777" + "772E64696769636572742E636F6D2F4350533008060667810C01040130818406" + "082B0601050507010104783076302406082B060105050730018618687474703A" + "2F2F6F6373702E64696769636572742E636F6D304E06082B0601050507300286" + "42687474703A2F2F636163657274732E64696769636572742E636F6D2F446967" + "694365727453484132417373757265644944436F64655369676E696E6743412E" + "637274300C0603551D130101FF04023000300D06092A864886F70D01010B0500" + "038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD99BFC9B62" + "E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A73041686C" + "326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD5041479BDBB6B" + "93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE99348170" + "36338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D950EE0235" + "B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02A75F2D7E" + "C07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660BB452E359" + "22D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16819DC990" + "F5F45CDE21318201AE308201AA0201013081863072310B300906035504061302" + "555331153013060355040A130C446967694365727420496E6331193017060355" + "040B13107777772E64696769636572742E636F6D3131302F0603550403132844" + "696769436572742053484132204173737572656420494420436F646520536967" + "6E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300906052B0E03" + "021A0500300D06092A864886F70D01010B050004820100EAEEB9E1D4BFB979F1" + "A1C00EE1EC45069366CDD7489A0671F6DC9E3353F7FAEDCE7B87BD467ADFC850" + "877414966E7EB39C33367ABB03B3AA8BB1438BD952484CB807451499CAE8FDC9" + "527304D459D82CA039087560B5D3D0EA03DEA1B9472EFC44CBB55DD9A3C6A5C8" + "DFFD0786D5523F22604B412D6FC5A15E2D6285D7AB76EC216DE859391D129D51" + "6C27348EDAE7DC43335D12242D939CAF05385A118235F5B1E342EC034E70F655" + "793FF2FE037558EC2F45BD2683704F8FFD49B910131F4F2804B4282C5C36E41C" + "9E4E4F93446D44E3106760D265C5C7A849CF03426ACCB294712E51313D5414A7" + "8227AB79F6B18E2A2054E3FA781DAA2998EB33EDDCDA80").HexToByteArray(); internal static readonly byte[] IndefiniteLengthContentDocument = ( "3082265206092A864886F70D010702A08226433082263F020103310F300D0609" + "6086480165030402010500306806092A864886F70D010701A05B248004555665" + "7273696F6E3A310A0A322E31362E3834302E312E3130312E332E342E322E312D" + "486173683A49413134467074344A365A504F5A47506275364A676A524B696930" + "664E584A365A6B78746F744B665733383D0A0A0000A082106D308203C5308202" + "ADA003020102021002AC5C266A0B409B8F0B79F2AE462577300D06092A864886" + "F70D0101050500306C310B300906035504061302555331153013060355040A13" + "0C446967694365727420496E6331193017060355040B13107777772E64696769" + "636572742E636F6D312B30290603550403132244696769436572742048696768" + "204173737572616E636520455620526F6F74204341301E170D30363131313030" + "30303030305A170D3331313131303030303030305A306C310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D312B3029060355040313" + "2244696769436572742048696768204173737572616E636520455620526F6F74" + "20434130820122300D06092A864886F70D01010105000382010F003082010A02" + "82010100C6CCE573E6FBD4BBE52D2D32A6DFE5813FC9CD2549B6712AC3D59434" + "67A20A1CB05F69A640B1C4B7B28FD098A4A941593AD3DC94D63CDB7438A44ACC" + "4D2582F74AA5531238EEF3496D71917E63B6ABA65FC3A484F84F6251BEF8C5EC" + "DB3892E306E508910CC4284155FBCB5A89157E71E835BF4D72093DBE3A38505B" + "77311B8DB3C724459AA7AC6D00145A04B7BA13EB510A984141224E6561878141" + "50A6795C89DE194A57D52EE65D1C532C7E98CD1A0616A46873D03404135CA171" + "D35A7C55DB5E64E13787305604E511B4298012F1793988A202117C2766B788B7" + "78F2CA0AA838AB0A64C2BF665D9584C1A1251E875D1A500B2012CC41BB6E0B51" + "38B84BCB0203010001A3633061300E0603551D0F0101FF040403020186300F06" + "03551D130101FF040530030101FF301D0603551D0E04160414B13EC36903F8BF" + "4701D498261A0802EF63642BC3301F0603551D23041830168014B13EC36903F8" + "BF4701D498261A0802EF63642BC3300D06092A864886F70D0101050500038201" + "01001C1A0697DCD79C9F3C886606085721DB2147F82A67AABF183276401057C1" + "8AF37AD911658E35FA9EFC45B59ED94C314BB891E8432C8EB378CEDBE3537971" + "D6E5219401DA55879A2464F68A66CCDE9C37CDA834B1699B23C89E78222B7043" + "E35547316119EF58C5852F4E30F6A0311623C8E7E2651633CBBF1A1BA03DF8CA" + "5E8B318B6008892D0C065C52B7C4F90A98D1155F9F12BE7C366338BD44A47FE4" + "262B0AC497690DE98CE2C01057B8C876129155F24869D8BC2A025B0F44D42031" + "DBF4BA70265D90609EBC4B17092FB4CB1E4368C90727C1D25CF7EA21B968129C" + "3C9CBF9EFC805C9B63CDEC47AA252767A037F300827D54D7A9F8E92E13A377E8" + "1F4A308205E0308204C8A0030201020210070C57D60A8AB12F9B5F2D5CD2EDA5" + "04300D06092A864886F70D01010B0500306C310B300906035504061302555331" + "153013060355040A130C446967694365727420496E6331193017060355040B13" + "107777772E64696769636572742E636F6D312B30290603550403132244696769" + "4365727420455620436F6465205369676E696E6720434120285348413229301E" + "170D3137303531363030303030305A170D3230303532303132303030305A3081" + "F6311D301B060355040F0C1450726976617465204F7267616E697A6174696F6E" + "31133011060B2B0601040182373C0201031302555331193017060B2B06010401" + "82373C02010213084E657720596F726B3110300E060355040513073531303136" + "3333311E301C06035504091315353435205720456E6420417665204170742031" + "3645310E300C060355041113053130303234310B300906035504061302555331" + "0B3009060355040813024E593111300F060355040713084E657720596F726B31" + "1A3018060355040A13114F72656E204E6F766F746E792C204C4C43311A301806" + "0355040313114F72656E204E6F766F746E792C204C4C4330820122300D06092A" + "864886F70D01010105000382010F003082010A0282010100E253870D0B9B81C7" + "B2449CBD7BA9837EDFE23C79F54CE2C1BFA0F5C92C261AAC4E3D40CD890F8046" + "289C7BCF0525BC0D2E193C28E7AD3ABF87FD35CAB9CBC869CEF8964B80DD77CE" + "E209EFCC42A465FDC1338A478DAA80254D17679548ED78528A13632B66FD0531" + "555E04BCAF14A67AD266CECB03346FAB4757C1AC120FE34C15E4B5BBBDE3E601" + "EF9A8BBE6EE1802EF18E852233130B9DE0995FAACC869D414380B478E5E343AB" + "B2C18DDEC8170EB601301EC178B6CD66FF1E10D81637CB609FECCFBF91666090" + "A30F0D95B3BC204FDFC6314913C20091DBE60DEC88488C6B48E66E71247E11D2" + "7662A2A7106806BE8B95041F46D1375688F0B3C0BE805C750203010001A38201" + "F1308201ED301F0603551D230418301680148FE87EF06D326A000523C770976A" + "3A90FF6BEAD4301D0603551D0E0416041451B49AE070DEBDAE12B71C87F99F4E" + "0E495B30A1302E0603551D1104273025A02306082B06010505070803A0173015" + "0C1355532D4E455720594F524B2D35313031363333300E0603551D0F0101FF04" + "040302078030130603551D25040C300A06082B06010505070303307B0603551D" + "1F047430723037A035A0338631687474703A2F2F63726C332E64696769636572" + "742E636F6D2F4556436F64655369676E696E67534841322D67312E63726C3037" + "A035A0338631687474703A2F2F63726C342E64696769636572742E636F6D2F45" + "56436F64655369676E696E67534841322D67312E63726C304B0603551D200444" + "3042303706096086480186FD6C0302302A302806082B06010505070201161C68" + "747470733A2F2F7777772E64696769636572742E636F6D2F4350533007060567" + "810C0103307E06082B0601050507010104723070302406082B06010505073001" + "8618687474703A2F2F6F6373702E64696769636572742E636F6D304806082B06" + "010505073002863C687474703A2F2F636163657274732E64696769636572742E" + "636F6D2F44696769436572744556436F64655369676E696E6743412D53484132" + "2E637274300C0603551D130101FF04023000300D06092A864886F70D01010B05" + "0003820101000481103296C95A10AE7055ECB980F0A5910F756DB48704BB078C" + "B53E8859EDDF906E4B6207301C8BAE9CE39BE70D6D897EA2F32BD05270B8DC1E" + "44ADB0ECDCCAC7A858295E81E030B9A5CF571CD81536EBE36E4D87A9DD6E0C42" + "3B5E6F3A249C90AFB1418925F806C6B91346EBFDC61C1D392FA0861AE7B5ADF8" + "E0E213BBCCA53F826DA3B7514A80A7148968DC4855F584DBB2AB6E99569C6C89" + "333CFEEA0914F3C77A04E5EE44D7A27370F34FDFF4753762B62D55809C43FD63" + "F37BBB0239CB1B25F1F7C1932D0885F526CC87F589ED40BCEFBBDDD76620AA2D" + "5D373B9EE51F9FD02905EEC71DD5F5419010E5D061643A6A04211FA3165943AE" + "D0FF1FB58D23308206BC308205A4A003020102021003F1B4E15F3A82F1149678" + "B3D7D8475C300D06092A864886F70D01010B0500306C310B3009060355040613" + "02555331153013060355040A130C446967694365727420496E63311930170603" + "55040B13107777772E64696769636572742E636F6D312B302906035504031322" + "44696769436572742048696768204173737572616E636520455620526F6F7420" + "4341301E170D3132303431383132303030305A170D3237303431383132303030" + "305A306C310B300906035504061302555331153013060355040A130C44696769" + "4365727420496E6331193017060355040B13107777772E64696769636572742E" + "636F6D312B302906035504031322446967694365727420455620436F64652053" + "69676E696E672043412028534841322930820122300D06092A864886F70D0101" + "0105000382010F003082010A0282010100A753FA0FB2B513F164CF8480FCAE80" + "35D1B6D7C7A32CAC1A2CACF184AC3A35123A9291BA57E4C4C9F32FA8483CB7D6" + "6EDC9722BA517961AF432F0DB79BB44931AE44583EA4A196A7874F237EC36C65" + "2490553EA1CA237CC542E9C47A62459B7DDE6374CB9E6325F8849A9AAD454FAE" + "7D1FC813CB759BC9E1E18AF80B0C98F4CA3ED045AA7A1EA558933634BE2B2E2B" + "315866B432109F9DF052A1EFE83ED376F2405ADCFA6A3D1B4BAD76B08C5CEE36" + "BA83EA30A84CDEF10B2A584188AE0089AB03D11682202276EB5E54381262E1D2" + "7024DBED1F70D26409802DE2B69DCE1FF2BB21F36CDBD8B3197B8A509FEFEC36" + "0A5C9AB74AD308A03979FDDDBF3D3A09250203010001A3820358308203543012" + "0603551D130101FF040830060101FF020100300E0603551D0F0101FF04040302" + "018630130603551D25040C300A06082B06010505070303307F06082B06010505" + "07010104733071302406082B060105050730018618687474703A2F2F6F637370" + "2E64696769636572742E636F6D304906082B06010505073002863D687474703A" + "2F2F636163657274732E64696769636572742E636F6D2F446967694365727448" + "6967684173737572616E63654556526F6F7443412E63727430818F0603551D1F" + "0481873081843040A03EA03C863A687474703A2F2F63726C332E646967696365" + "72742E636F6D2F4469676943657274486967684173737572616E63654556526F" + "6F7443412E63726C3040A03EA03C863A687474703A2F2F63726C342E64696769" + "636572742E636F6D2F4469676943657274486967684173737572616E63654556" + "526F6F7443412E63726C308201C40603551D20048201BB308201B7308201B306" + "096086480186FD6C0302308201A4303A06082B06010505070201162E68747470" + "3A2F2F7777772E64696769636572742E636F6D2F73736C2D6370732D7265706F" + "7369746F72792E68746D3082016406082B06010505070202308201561E820152" + "0041006E007900200075007300650020006F0066002000740068006900730020" + "0043006500720074006900660069006300610074006500200063006F006E0073" + "007400690074007500740065007300200061006300630065007000740061006E" + "006300650020006F006600200074006800650020004400690067006900430065" + "00720074002000430050002F00430050005300200061006E0064002000740068" + "0065002000520065006C00790069006E00670020005000610072007400790020" + "00410067007200650065006D0065006E00740020007700680069006300680020" + "006C0069006D006900740020006C0069006100620069006C0069007400790020" + "0061006E0064002000610072006500200069006E0063006F00720070006F0072" + "0061007400650064002000680065007200650069006E00200062007900200072" + "00650066006500720065006E00630065002E301D0603551D0E041604148FE87E" + "F06D326A000523C770976A3A90FF6BEAD4301F0603551D23041830168014B13E" + "C36903F8BF4701D498261A0802EF63642BC3300D06092A864886F70D01010B05" + "00038201010019334A0C813337DBAD36C9E4C93ABBB51B2E7AA2E2F44342179E" + "BF4EA14DE1B1DBE981DD9F01F2E488D5E9FE09FD21C1EC5D80D2F0D6C143C2FE" + "772BDBF9D79133CE6CD5B2193BE62ED6C9934F88408ECDE1F57EF10FC6595672" + "E8EB6A41BD1CD546D57C49CA663815C1BFE091707787DCC98D31C90C29A233ED" + "8DE287CD898D3F1BFFD5E01A978B7CDA6DFBA8C6B23A666B7B01B3CDD8A634EC" + "1201AB9558A5C45357A860E6E70212A0B92364A24DBB7C81256421BECFEE4218" + "4397BBA53706AF4DFF26A54D614BEC4641B865CEB8799E08960B818C8A3B8FC7" + "998CA32A6E986D5E61C696B78AB9612D93B8EB0E0443D7F5FEA6F062D4996AA5" + "C1C1F06494803182154C30821548020103801451B49AE070DEBDAE12B71C87F9" + "9F4E0E495B30A1300D06096086480165030402010500A082015B301806092A86" + "4886F70D010903310B06092A864886F70D010701301C06092A864886F70D0109" + "05310F170D3138303632333139303131385A301E060B2A864886F70D01091002" + "10310F300D060B2A864886F70D0109100601302F06092A864886F70D01090431" + "220420F67BA3F4A22E1F7D27A0FF8940FD931FF3D5AAA6BA99B92B6ABA6B63B3" + "93E5DB3081CF060B2A864886F70D010910022F3181BF3081BC3081B93081B630" + "0B0609608648016503040201042017B677DFF2A3A70C935DCABCEAF6595183D6" + "2F8972E77AC688369EDE50D2B2563081843070A46E306C310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D312B3029060355040313" + "22446967694365727420455620436F6465205369676E696E6720434120285348" + "4132290210070C57D60A8AB12F9B5F2D5CD2EDA504300D06092A864886F70D01" + "010B050004820100AA697F9C5F4517BB139B8A7FAEC1BBBBAB53381B4F649EE1" + "9A35E9F5D47ABE0C2FCF881C6DC176E52F8191A43486630939264F42464B865D" + "B46979EF4996CD081CF615F194BBC9F539609000F2A2A6CBD9F88E497F4B907F" + "AEE95B55E73921CCAF89287FDC3F18FA1DB5D13BA7932A0559A9C4194E937611" + "003228D161B2EE40FD5C8BDB0463F90DFC5B0D0ABBBDFE7918BDDA2F5658F8E2" + "BA47362DC677CD8785D0AD76B73CC544411B7B168E471A449FDF8BD356719D56" + "C67E69F81F9534A2DE9D1CDD22717D3D3F84D6CB10C7FC2651945A000A2B7696" + "6A69CBE5D37B513E67E945B29CE2CC09CB2E4C8CDBAF105BCFE0927D14B8CEEF" + "92851AF4476053DCA18212AA308212A6060B2A864886F70D010910020E318212" + "953082129106092A864886F70D010702A08212823082127E020103310F300D06" + "09608648016503040201050030819C060B2A864886F70D0109100104A0818C04" + "818930818602010106096086480186FD6C07013031300D060960864801650304" + "0201050004208A42931DB9A7486014564D4922BE742D01B6ADF152B1421227B7" + "D6FBB943EEC202105B0A3E465D2092EB05B245401BC2594E180F323031383036" + "32333139303132305A02205718795810783FECCC7143D821251F44AEE16A57A1" + "CA24C1B2EF1796CB777AD3A0820F76308203B73082029FA00302010202100CE7" + "E0E517D846FE8FE560FC1BF03039300D06092A864886F70D0101050500306531" + "0B300906035504061302555331153013060355040A130C446967694365727420" + "496E6331193017060355040B13107777772E64696769636572742E636F6D3124" + "30220603550403131B4469676943657274204173737572656420494420526F6F" + "74204341301E170D3036313131303030303030305A170D333131313130303030" + "3030305A3065310B300906035504061302555331153013060355040A130C4469" + "67694365727420496E6331193017060355040B13107777772E64696769636572" + "742E636F6D312430220603550403131B44696769436572742041737375726564" + "20494420526F6F7420434130820122300D06092A864886F70D01010105000382" + "010F003082010A0282010100AD0E15CEE443805CB187F3B760F97112A5AEDC26" + "9488AAF4CEF520392858600CF880DAA9159532613CB5B128848A8ADC9F0A0C83" + "177A8F90AC8AE779535C31842AF60F98323676CCDEDD3CA8A2EF6AFB21F25261" + "DF9F20D71FE2B1D9FE1864D2125B5FF9581835BC47CDA136F96B7FD4B0383EC1" + "1BC38C33D9D82F18FE280FB3A783D6C36E44C061359616FE599C8B766DD7F1A2" + "4B0D2BFF0B72DA9E60D08E9035C678558720A1CFE56D0AC8497C3198336C22E9" + "87D0325AA2BA138211ED39179D993A72A1E6FAA4D9D5173175AE857D22AE3F01" + "4686F62879C8B1DAE45717C47E1C0EB0B492A656B3BDB297EDAAA7F0B7C5A83F" + "9516D0FFA196EB085F18774F0203010001A3633061300E0603551D0F0101FF04" + "0403020186300F0603551D130101FF040530030101FF301D0603551D0E041604" + "1445EBA2AFF492CB82312D518BA7A7219DF36DC80F301F0603551D2304183016" + "801445EBA2AFF492CB82312D518BA7A7219DF36DC80F300D06092A864886F70D" + "01010505000382010100A20EBCDFE2EDF0E372737A6494BFF77266D832E44275" + "62AE87EBF2D5D9DE56B39FCCCE1428B90D97605C124C58E4D33D834945589735" + "691AA847EA56C679AB12D8678184DF7F093C94E6B8262C20BD3DB32889F75FFF" + "22E297841FE965EF87E0DFC16749B35DEBB2092AEB26ED78BE7D3F2BF3B72635" + "6D5F8901B6495B9F01059BAB3D25C1CCB67FC2F16F86C6FA6468EB812D94EB42" + "B7FA8C1EDD62F1BE5067B76CBDF3F11F6B0C3607167F377CA95B6D7AF1124660" + "83D72704BE4BCE97BEC3672A6811DF80E70C3366BF130D146EF37F1F63101EFA" + "8D1B256D6C8FA5B76101B1D2A326A110719DADE2C3F9C39951B72B0708CE2EE6" + "50B2A7FA0A452FA2F0F23082053130820419A00302010202100AA125D6D6321B" + "7E41E405DA3697C215300D06092A864886F70D01010B05003065310B30090603" + "5504061302555331153013060355040A130C446967694365727420496E633119" + "3017060355040B13107777772E64696769636572742E636F6D31243022060355" + "0403131B4469676943657274204173737572656420494420526F6F7420434130" + "1E170D3136303130373132303030305A170D3331303130373132303030305A30" + "72310B300906035504061302555331153013060355040A130C44696769436572" + "7420496E6331193017060355040B13107777772E64696769636572742E636F6D" + "3131302F06035504031328446967694365727420534841322041737375726564" + "2049442054696D657374616D70696E6720434130820122300D06092A864886F7" + "0D01010105000382010F003082010A0282010100BDD032EE4BCD8F7FDDA9BA82" + "99C539542857B6234AC40E07453351107DD0F97D4D687EE7B6A0F48DB388E497" + "BF63219098BF13BC57D3C3E17E08D66A140038F72E1E3BEECCA6F63259FE5F65" + "3FE09BEBE34647061A557E0B277EC0A2F5A0E0DE223F0EFF7E95FBF3A3BA223E" + "18AC11E4F099036D3B857C09D3EE5DC89A0B54E3A809716BE0CF22100F75CF71" + "724E0AADDF403A5CB751E1A17914C64D2423305DBCEC3C606AAC2F07CCFDF0EA" + "47D988505EFD666E56612729898451E682E74650FD942A2CA7E4753EBA980F84" + "7F9F3114D6ADD5F264CB7B1E05D084197217F11706EF3DCDD64DEF0642FDA253" + "2A4F851DC41D3CAFCFDAAC10F5DDACACE956FF930203010001A38201CE308201" + "CA301D0603551D0E04160414F4B6E1201DFE29AED2E461A5B2A225B2C817356E" + "301F0603551D2304183016801445EBA2AFF492CB82312D518BA7A7219DF36DC8" + "0F30120603551D130101FF040830060101FF020100300E0603551D0F0101FF04" + "040302018630130603551D25040C300A06082B06010505070308307906082B06" + "010505070101046D306B302406082B060105050730018618687474703A2F2F6F" + "6373702E64696769636572742E636F6D304306082B0601050507300286376874" + "74703A2F2F636163657274732E64696769636572742E636F6D2F446967694365" + "7274417373757265644944526F6F7443412E6372743081810603551D1F047A30" + "78303AA038A0368634687474703A2F2F63726C342E64696769636572742E636F" + "6D2F4469676943657274417373757265644944526F6F7443412E63726C303AA0" + "38A0368634687474703A2F2F63726C332E64696769636572742E636F6D2F4469" + "676943657274417373757265644944526F6F7443412E63726C30500603551D20" + "044930473038060A6086480186FD6C000204302A302806082B06010505070201" + "161C68747470733A2F2F7777772E64696769636572742E636F6D2F435053300B" + "06096086480186FD6C0701300D06092A864886F70D01010B0500038201010071" + "9512E951875669CDEFDDDA7CAA637AB378CF06374084EF4B84BFCACF0302FDC5" + "A7C30E20422CAF77F32B1F0C215A2AB705341D6AAE99F827A266BF09AA60DF76" + "A43A930FF8B2D1D87C1962E85E82251EC4BA1C7B2C21E2D65B2C1435430468B2" + "DB7502E072C798D63C64E51F4810185F8938614D62462487638C91522CAF2989" + "E5781FD60B14A580D7124770B375D59385937EB69267FB536189A8F56B96C0F4" + "58690D7CC801B1B92875B7996385228C61CA79947E59FC8C0FE36FB50126B66C" + "A5EE875121E458609BBA0C2D2B6DA2C47EBBC4252B4702087C49AE13B6E17C42" + "4228C61856CF4134B6665DB6747BF55633222F2236B24BA24A95D8F5A68E5230" + "8206823082056AA003020102021009C0FC46C8044213B5598BAF284F4E41300D" + "06092A864886F70D01010B05003072310B300906035504061302555331153013" + "060355040A130C446967694365727420496E6331193017060355040B13107777" + "772E64696769636572742E636F6D3131302F0603550403132844696769436572" + "74205348413220417373757265642049442054696D657374616D70696E672043" + "41301E170D3137303130343030303030305A170D323830313138303030303030" + "5A304C310B30090603550406130255533111300F060355040A13084469676943" + "657274312A302806035504031321446967694365727420534841322054696D65" + "7374616D7020526573706F6E64657230820122300D06092A864886F70D010101" + "05000382010F003082010A02820101009E95986A343B731BA87EFCC7BE296989" + "C76826465F3D8D62738781A3A19CF0B75B24375A92D4F459D77689E4DCD527F0" + "D566BC0AEEB42B3167AC58C54A91592B451E0901D664B359EE8D664DFB235ECC" + "100D0B8A67EF52AEA00890C252F7F5A8B56E9B2C7B9DE7B53EFB78CD325018BF" + "40B54C8CBB57F4A04F11456C4242B9E5AFD6DFF4A77C0A68960FD25F2957CEFB" + "1D32FFF411A11322FB12CBEFD753D2EB97CBA2AC1B1D9D58215182C2C2DEEA2B" + "3F2C2284D043EC3B3B3F47C4F656DC453798B46B74B559AF785769C80F090278" + "DDD853C199DB60C49DEAAEAFE07E864A5CA95861A85E748A012868724EA7869D" + "B5025287706648D38EEF8124CCDCD8650203010001A382033830820334300E06" + "03551D0F0101FF040403020780300C0603551D130101FF040230003016060355" + "1D250101FF040C300A06082B06010505070308308201BF0603551D20048201B6" + "308201B2308201A106096086480186FD6C070130820192302806082B06010505" + "070201161C68747470733A2F2F7777772E64696769636572742E636F6D2F4350" + "533082016406082B06010505070202308201561E8201520041006E0079002000" + "75007300650020006F0066002000740068006900730020004300650072007400" + "6900660069006300610074006500200063006F006E0073007400690074007500" + "740065007300200061006300630065007000740061006E006300650020006F00" + "6600200074006800650020004400690067006900430065007200740020004300" + "50002F00430050005300200061006E0064002000740068006500200052006500" + "6C00790069006E00670020005000610072007400790020004100670072006500" + "65006D0065006E00740020007700680069006300680020006C0069006D006900" + "740020006C0069006100620069006C00690074007900200061006E0064002000" + "610072006500200069006E0063006F00720070006F0072006100740065006400" + "2000680065007200650069006E00200062007900200072006500660065007200" + "65006E00630065002E300B06096086480186FD6C0315301F0603551D23041830" + "168014F4B6E1201DFE29AED2E461A5B2A225B2C817356E301D0603551D0E0416" + "0414E1A7324AEE0121287D54D5F207926EB4070F3D8730710603551D1F046A30" + "683032A030A02E862C687474703A2F2F63726C332E64696769636572742E636F" + "6D2F736861322D617373757265642D74732E63726C3032A030A02E862C687474" + "703A2F2F63726C342E64696769636572742E636F6D2F736861322D6173737572" + "65642D74732E63726C30818506082B0601050507010104793077302406082B06" + "0105050730018618687474703A2F2F6F6373702E64696769636572742E636F6D" + "304F06082B060105050730028643687474703A2F2F636163657274732E646967" + "69636572742E636F6D2F44696769436572745348413241737375726564494454" + "696D657374616D70696E6743412E637274300D06092A864886F70D01010B0500" + "03820101001EF0418232AEEDF1B43513DC50C2D597AE22229D0E0EAF33D34CFD" + "7CBF6F0111A79465225CC622A1C889526B9A8C735CD95E3F32DE16604C8B36FD" + "31990ABDC184B78D1DEF8926130556F347CD475BAD84B238AF6A23B545E31E88" + "324680D2B7A69922FDC178CFF58BD80C8C0509EE44E680D56D70CC9F531E27DD" + "2A48DEDA9365AD6E65A399A7C2400E73CC584F8F4528E5BC9C88E628CE605D2D" + "255D8B732EA50D5B51DA9A4EFF50058928DAF278BBD258788D44A7AC3A009178" + "69896404D35D96DF2ABFF9A54C2C93FFE68ADD82ACF1D2B3A2869AC15589566A" + "473FFAD6339543358905785A3A69DA22B80443D36F6835367A143E45E9986486" + "0F130C264A3182024D308202490201013081863072310B300906035504061302" + "555331153013060355040A130C446967694365727420496E6331193017060355" + "040B13107777772E64696769636572742E636F6D3131302F0603550403132844" + "69676943657274205348413220417373757265642049442054696D657374616D" + "70696E67204341021009C0FC46C8044213B5598BAF284F4E41300D0609608648" + "0165030402010500A08198301A06092A864886F70D010903310D060B2A864886" + "F70D0109100104301C06092A864886F70D010905310F170D3138303632333139" + "303132305A302F06092A864886F70D01090431220420DAE824F466CED9AD07AC" + "66897D7489E25E678911AA3E85BBBAB76F93DF77FFCA302B060B2A864886F70D" + "010910020C311C301A301830160414400191475C98891DEBA104AF47091B5EB6" + "D4CBCB300D06092A864886F70D010101050004820100451DCB791B5E31865B9F" + "697B8A790C4DB1867261B10EDCEB65F8AD03350D8D25D89012E8A9C46D3DA436" + "04F222C645A8C4C7658D0C5C31A473A09FE314D049A886001CAC3C2C5B106BD7" + "1D02785A3BD02E4171E70A9AA1C7EC5BDB7D1B5A2F3A5F6EF92EE3296CB8FC52" + "D7ABF3ADB91F2BF30A2D0DE9713CFE5CF203B6D3F0F51897DCB075E8AAB8CB96" + "1F9505656CA73C8935E29A71C09BE3AA0BA1326FA295B6686771D6431BB2DAB3" + "8DECE164DE7487945C09DC0BF525086256C4D22CC71C70DD886BDD2EEF609631" + "771EF1E49426819679F9C080815B27AD93090D56DBF566D585693B27B5FDA70B" + "18401534B87B522B7B0AA98E3F31DFDD64FDA0DE9471").HexToByteArray(); internal static readonly byte[] MD5WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D010104301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D010104300B06092A864886F70D010101048201005C" + "5174F8B1C6EF0A555CDBA272DF76BB798CB4170D361E4238C3A260748598B7C9" + "561605640BCAFC23C66C45A99E54A25854C5379CE2D26DECABDB6C6AE1FDC79E" + "1BBFA5833640BD8C96AF66CD3379B83B8A53660FB2FA6C1BD8ACE986741FF73A" + "14C437B7AF8617854A8F9484D84E684255EB7C37CBCA51BBC81D8D7E9A6287A0" + "409AC5AE0FA7D6411F7B25BDFC49EC91BD664630741ECCB0C6F02FFC5B9256A3" + "8AC30FDB4A7C2253E372858DF5D2333BBE29CEBCE24A0FABB9E62B0E631CAB2F" + "7A9137FE16A0448BE17ACF55F630CD6A522D94A42D6AB79C82C9AAB0DE7284C5" + "F8F16BF845A7619AE6DEE8016D42EA13189B51E50440F18F52475453B6F899").HexToByteArray(); internal static readonly byte[] SHA1WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D010105301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D010105300B06092A864886F70D010101048201002A" + "1EAADFA508990F3395BCCBCB5ECB9CDFF236B94306481C3F7EB6C0C0189FEDC0" + "3AF8DA8BB0474F7D10DD87A81661D8A703FF7D695A45BCC25D8185CF9C5EF39B" + "C0D582ABD3392B19D9A29BC4629FC401A97B2135C73F2D356B369EA18D864C3E" + "2CE77EAF0B1B71244D3D5FE442E6C92E2A0FB24EFF7EC8FD5EBB248870FDBDC5" + "FA8F458DB3C2159234BCF1FCDBCCB232CDEF7A7208C51A7DD4AC5AD01613B603" + "B11E5E1D7509286B92C701C4538D44DC3487656F9E25BA8C5CF6FBD7F532B749" + "0FBBBC5F4FC9BA6FFCB3910E85295C9C7DD36CF5AC3B3A1C425FAD84EA99CBE0" + "962CE8F7AAED44AA202273A3B5A2A7D8D98978642EE321703F9AB8768BECD2").HexToByteArray(); internal static readonly byte[] SHA256WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010B301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010B300B06092A864886F70D0101010482010054" + "5BAEC400A8F0EC436BDCE64B2FB22E8332C17538C9BBB72FCCF7C1F539A859A3" + "7E96754CA81AE81B24F937E1601681EB2315E632A76162B87C33403534DC64F0" + "E7DC8999BA05E7E030505B538124BB13FEC099F16372AE61DB75464DDE663ACE" + "10F136A6DA45CD988866B3630DEC1288AFA0B1864B93EE2B0713BA6C745A6775" + "061F19A1960218564478A814054EF844A6EF2C0ABFA5A854E60E1F275D7FB42A" + "0A4844DFB480AE88ABC83401DB59B333612AD2AAC6F5BB24FC09460D22499257" + "43F59476A8EC6E9E7E6C423F6574034B371F4562F347D10981141D9C7C36F47F" + "54882AD0FE5C78487C1F96785BD6BEBB958F5C140F86DFCE6F1E03B0AAE8C5").HexToByteArray(); internal static readonly byte[] SHA384WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010C301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010C300B06092A864886F70D0101010482010066" + "7739542DAC383580DD47E88B092FA77F8C7C2AF3C71E1E532D0CE6CA91FA27CF" + "A30F89AE9ACB3BD2ED666D8C7BE83FADEBC22847A8D12465AA5009967365E089" + "C1177FC71F80EF8EFFC0EC109368517EFEE26C989AAD2C7DA4C9DB52E9349F84" + "2EB3CFEA3E66338565715124D0980E6B27619B9F1CB8B1FA84946E034CDBDE43" + "18241EFC89D5E90F9B4434E4452827C00D01803C9E40B1E98D97E822AE549B32" + "6E547F8E8176DC3BAB9C9B2B9A87AC7EC5E0B2E5135C6FC9EC2B8ACC8F9D152D" + "A729967FAE63AEA42730A49E2740C9064DAA8F981E27DAB42D142FACE3D0261D" + "45C46FA632B0D7FFFC6F9EAC26E5EFC765D01A9C739C08D10775536488BF0D").HexToByteArray(); internal static readonly byte[] SHA512WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010D301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010D300B06092A864886F70D0101010482010045" + "B324E7BE9FD3B1279018B01CD177A55A47A5C811CA693ED6BB32C8A243B1404D" + "89DC4EAA348453CB07BF8B1A11DE1BAF6397502C41D384790C0A285D69C17006" + "4F49D5735045EAAFAE43998D2660C6D15AEA1433FDFB7C4A995BBA4231AEB66B" + "81E29A035973CD148906A2FA16D6E551174D232E9DD738FE18D09E21517753A3" + "DF2687B83E0F8B70912F68FCF12311593637A362A3525BE875172BB402D998AE" + "D54F085DA892DD967FFE8906E23C0EF7E1C2ED89BB3986871BA997E725876535" + "119CFE807690BC067BA5781231E68A61CDE4D66AA67CD31981CF92275FD3485C" + "01CBA2BA29AED480F7AD26B361B39EE3622D1A705238E5C1A8BE2BBE921804").HexToByteArray(); internal static readonly byte[] SHA256ECDSAWithRsaSha256DigestIdentifier = ( "3082023006092A864886F70D010702A08202213082021D020101310D300B0609" + "2A864886F70D01010B301206092A864886F70D010701A0050403010203A08201" + "5C308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4DC830" + "0A06082A8648CE3D04030230153113301106035504030C0A4543445341205465" + "7374301E170D3135303530313030333730335A170D3136303530313030353730" + "335A30153113301106035504030C0A454344534120546573743059301306072A" + "8648CE3D020106082A8648CE3D030107034200047590F69CA114E92927E034C9" + "97B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA32496FDA" + "C84E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D0F01" + "01FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5CCFB8" + "220CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E19F1" + "AE4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CBDF43" + "4FDD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E318194" + "308191020101302930153113301106035504030C0A4543445341205465737402" + "1035428F3B3C5107AD49E776D6E74C4DC8300B06092A864886F70D01010B300A" + "06082A8648CE3D0403020448304602210087FAF07C8B9259F453A8EF63A1F2E9" + "36D6845255FE1109D84592E23E8E384611022100C8BA4D440C8AD0753CC43966" + "0CBB1A3FA93E7C1F8427BAB27150EB15F92D2928").HexToByteArray(); internal static readonly byte[] SHA256withRSADigestAndSHA256WithRSASignatureAlgorithm = ( "3082071B06092A864886F70D010702A082070C30820708020101310F300D0609" + "2A864886F70D01010B0500301606092A864886F70D010701A009040700010203" + "040506A08205223082051E30820406A00302010202100D85090F3FACFF0A9008" + "A12A9FB00A54300D06092A864886F70D01010B05003072310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D3131302F060355040313" + "2844696769436572742053484132204173737572656420494420436F64652053" + "69676E696E67204341301E170D3138303832393030303030305A170D31393039" + "30333132303030305A305B310B3009060355040613025553310B300906035504" + "0813025641311330110603550407130A416C6578616E64726961311430120603" + "55040A130B4B6576696E204A6F6E6573311430120603550403130B4B6576696E" + "204A6F6E657330820122300D06092A864886F70D01010105000382010F003082" + "010A0282010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D299" + "1C962D0A22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A35" + "80CC96A11F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F77" + "9CB4979544514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456" + "A8497758D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB" + "0780CD258F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214" + "533B2A47977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200" + "943EFB7D0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A" + "8C461760E6A4F30203010001A38201C5308201C1301F0603551D230418301680" + "145AC4B97B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E04160414" + "33795EB2D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF0404" + "0302078030130603551D25040C300A06082B0601050507030330770603551D1F" + "0470306E3035A033A031862F687474703A2F2F63726C332E6469676963657274" + "2E636F6D2F736861322D617373757265642D63732D67312E63726C3035A033A0" + "31862F687474703A2F2F63726C342E64696769636572742E636F6D2F73686132" + "2D617373757265642D63732D67312E63726C304C0603551D2004453043303706" + "096086480186FD6C0301302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F4350533008060667810C010401" + "30818406082B0601050507010104783076302406082B06010505073001861868" + "7474703A2F2F6F6373702E64696769636572742E636F6D304E06082B06010505" + "0730028642687474703A2F2F636163657274732E64696769636572742E636F6D" + "2F446967694365727453484132417373757265644944436F64655369676E696E" + "6743412E637274300C0603551D130101FF04023000300D06092A864886F70D01" + "010B0500038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD9" + "9BFC9B62E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A7" + "3041686C326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD50414" + "79BDBB6B93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE" + "9934817036338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D9" + "50EE0235B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02" + "A75F2D7EC07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660B" + "B452E35922D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16" + "819DC990F5F45CDE21318201B2308201AE0201013081863072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "03132844696769436572742053484132204173737572656420494420436F6465" + "205369676E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300D06" + "092A864886F70D01010B0500300D06092A864886F70D01010B050004820100E2" + "980C5A30EC00729D1CFA826D7A65B43FF6806B5E0ABA23A78E4F1CAA3F6436EF" + "00941C6947A9B8F20D0757B5346CF640AA217F7361BEEFF2BC997FB1D3597BF3" + "D7457BD4A94062FB03660F9D86710BE2FC99876A848251F4965E1B16192714C8" + "F9788C09CCDE83603ADC919297BA496E921B95F3BD9554A873E09912640FCFAA" + "D9DD1441D1851E637031D390C038223AE64B048E806462DDBAC98C156BE2EE47" + "2B78166BDB1612848B535ADC3F0E7BE52991A17F48AFDCCC1698A236BA338930" + "50EBAAC4460DAA35185C16670F597E0E6E0CB0AA83F51AAEF452F3367DD9350A" + "8A49A5A8F79DF8E921303AB5D6646A482F0F59D9980310E1AE3EE8D77CB857").HexToByteArray(); internal static readonly byte[] TstWithAttributeCertificate = ( "308212E306092A864886F70D010702A08212D4308212D0020103310F300D0609" + "608648016503040201050030820159060B2A864886F70D0109100104A0820148" + "0482014430820140020101060A2B0601040184590A03013031300D0609608648" + "01650304020105000420C61245B435391DCDD1EFF021681FA2A46E69410A9E23" + "09F1B1736BB7C2BB504402066148B8B838B11813323032313130303730343230" + "30372E3037345A3004800201F4A081D8A481D53081D2310B3009060355040613" + "025553311330110603550408130A57617368696E67746F6E3110300E06035504" + "0713075265646D6F6E64311E301C060355040A13154D6963726F736F66742043" + "6F72706F726174696F6E312D302B060355040B13244D6963726F736F66742049" + "72656C616E64204F7065726174696F6E73204C696D6974656431263024060355" + "040B131D5468616C6573205453532045534E3A303834322D344245362D433239" + "41312530230603550403131C4D6963726F736F66742054696D652D5374616D70" + "2053657276696365A0820E4A308204F9308203E1A00302010202133300000139" + "CCE8E8438BF034E1000000000139300D06092A864886F70D01010B0500307C31" + "0B3009060355040613025553311330110603550408130A57617368696E67746F" + "6E3110300E060355040713075265646D6F6E64311E301C060355040A13154D69" + "63726F736F667420436F72706F726174696F6E312630240603550403131D4D69" + "63726F736F66742054696D652D5374616D70205043412032303130301E170D32" + "30313031353137323832315A170D3232303131323137323832315A3081D2310B" + "3009060355040613025553311330110603550408130A57617368696E67746F6E" + "3110300E060355040713075265646D6F6E64311E301C060355040A13154D6963" + "726F736F667420436F72706F726174696F6E312D302B060355040B13244D6963" + "726F736F6674204972656C616E64204F7065726174696F6E73204C696D697465" + "6431263024060355040B131D5468616C6573205453532045534E3A303834322D" + "344245362D43323941312530230603550403131C4D6963726F736F6674205469" + "6D652D5374616D70205365727669636530820122300D06092A864886F70D0101" + "0105000382010F003082010A0282010100DA13F98CE3259325A18EB32A06FCA2" + "78F85A1F98374F7F50C1DBBA1EA02759C2E5CFDFD92A80BF405CF8E606F469DD" + "7822FA856859B627AA3EBE185B7F8A1024E1C34DC8D95C12904DB413FF0E8B09" + "6BDD0979C5425D9AF2711DE3612613BAF145598ABA66C7A04295F90C1874673B" + "D2AE4EF0CD9892A27F4AD72B16116D9A117172F559FA08386B3CEF13CEFEB282" + "33615EB3A8CD8A58EFD34B2F597A88B95F84286D5E802AEC091F4F32499DA540" + "15F39DDF2BC03CF2EBE058A895E29BE6FE57EEC4DFBE356FA710F5F98E340A47" + "2E1906AA8D3BFC1D783641AAA8EF7BF210235ED5684292A32AEEB2C57CECB294" + "278F4AE57EC57F1F2496FE5FA2CF1ECA4F0203010001A382011B30820117301D" + "0603551D0E04160414999E9B867254C299DA928AB19F46F6502D060CE9301F06" + "03551D23041830168014D5633A5C8A3190F3437B7C461BC533685A856D553056" + "0603551D1F044F304D304BA049A0478645687474703A2F2F63726C2E6D696372" + "6F736F66742E636F6D2F706B692F63726C2F70726F64756374732F4D69635469" + "6D5374615043415F323031302D30372D30312E63726C305A06082B0601050507" + "0101044E304C304A06082B06010505073002863E687474703A2F2F7777772E6D" + "6963726F736F66742E636F6D2F706B692F63657274732F4D696354696D537461" + "5043415F323031302D30372D30312E637274300C0603551D130101FF04023000" + "30130603551D25040C300A06082B06010505070308300D06092A864886F70D01" + "010B05000382010100585C286AF3FF371A85CDC15AED438288BF100DB126FBBA" + "F6118893A16D20F1D758C8AE566B514077FCA7243D6AC9CFD9C71F473FDD32A9" + "7293FABCF8835C08B1049694A09BDD71B821586C584084B26DA28CDFDFC687E6" + "B63667158DF5BB831249C97E21A22BA43EF2490235699B5A3D83C51C0417C21F" + "0708C5EC43E160381D8A52B3E3CEAEC21828B28AF51AE0D68A56231A830DAB79" + "6BC0322463FF37294A49868AE5A6205D908344B159027F3C842E67BD0B7B5A99" + "9B4C497C6B519C17E96ADFDDD498100AB2DFA3C9649AE2C13C21BF38C87AA0FC" + "78ACD4521DEE7C4DBF1231006DA6C1842A36FAD528CA74FA4C026D8DD8AF6B88" + "3B3FBDFF550AD270C73082067130820459A003020102020A6109812A00000000" + "0002300D06092A864886F70D01010B0500308188310B30090603550406130255" + "53311330110603550408130A57617368696E67746F6E3110300E060355040713" + "075265646D6F6E64311E301C060355040A13154D6963726F736F667420436F72" + "706F726174696F6E31323030060355040313294D6963726F736F667420526F6F" + "7420436572746966696361746520417574686F726974792032303130301E170D" + "3130303730313231333635355A170D3235303730313231343635355A307C310B" + "3009060355040613025553311330110603550408130A57617368696E67746F6E" + "3110300E060355040713075265646D6F6E64311E301C060355040A13154D6963" + "726F736F667420436F72706F726174696F6E312630240603550403131D4D6963" + "726F736F66742054696D652D5374616D7020504341203230313030820122300D" + "06092A864886F70D01010105000382010F003082010A0282010100A91D0DBC77" + "118A3A20ECFC1397F5FA7F69946B745410D5A50A008285FBED7C684B2C5FC5C3" + "E561C276B73E662B5BF015532704311F411B1A951DCE09138E7C613059B13044" + "0FF160888454430CD74DB83808B342DD93ACD67330572682A3450DD0EAF54781" + "CDBF246032586046F258478632841E746167915F8154B1CF934C92C1C4A65DD1" + "61136E28C61AF98680BBDF61FC46C1271D246712721A218AAF4B64895062B15D" + "FD771F3DF05775ACBD8A424D4051D10F9C063E677FF566C00396447EEFD04BFD" + "6EE59ACAB1A8F27A2A0A31F0DA4E0691B6880835E8781CB0E999CD3CE72F44BA" + "A7F4DC64BDA401C120099378CDFCBCC0C9445D5E169C01054F224D0203010001" + "A38201E6308201E2301006092B06010401823715010403020100301D0603551D" + "0E04160414D5633A5C8A3190F3437B7C461BC533685A856D55301906092B0601" + "040182371402040C1E0A00530075006200430041300B0603551D0F0404030201" + "86300F0603551D130101FF040530030101FF301F0603551D23041830168014D5" + "F656CB8FE8A25C6268D13D94905BD7CE9A18C430560603551D1F044F304D304B" + "A049A0478645687474703A2F2F63726C2E6D6963726F736F66742E636F6D2F70" + "6B692F63726C2F70726F64756374732F4D6963526F6F4365724175745F323031" + "302D30362D32332E63726C305A06082B06010505070101044E304C304A06082B" + "06010505073002863E687474703A2F2F7777772E6D6963726F736F66742E636F" + "6D2F706B692F63657274732F4D6963526F6F4365724175745F323031302D3036" + "2D32332E6372743081A00603551D200101FF04819530819230818F06092B0601" + "040182372E03308181303D06082B060105050702011631687474703A2F2F7777" + "772E6D6963726F736F66742E636F6D2F504B492F646F63732F4350532F646566" + "61756C742E68746D304006082B0601050507020230341E32201D004C00650067" + "0061006C005F0050006F006C006900630079005F00530074006100740065006D" + "0065006E0074002E201D300D06092A864886F70D01010B0500038202010007E6" + "88510DE2C6E0983F8171033D9DA3A1216FB3EBA6CCF531BECF05E2A9FEFA576D" + "1930B3C2C566C96ADFF5E7F078BDC7A89E25E3F9BCED6B5457082B51824412FB" + "B9538CCCF460128A76CC4040419BDC5C17FF5CF95E17359824564B74EF4210C8" + "AFBF7FC67FF2377D5A3F1CF299794A915200AF380F17F52F798165D9A9B56BE4" + "C7CEF6CA7A006F4B304424223CCFED03A5968F5929BCB6FD04E1709F324A27FD" + "55AF2FFEB6E58E33BB625F9ADB5740E9F1CE9966908CFF6A627FDDC54A0B9126" + "E239EC194A71639D7B216DC39CA3A23CFA7F7D966A9078A66DD2E19CF91DFC38" + "D894F4C6A50A9686A4BD9E1AAE044283B8B5809B223820B525E564ECF7F4BF7E" + "6359250F7A2E395776A271AA068A0F8916BA61A711CB9AD80E479A80C5D0CDA7" + "D0EF7D83F0E13B7109DF5D7498220861DAB0501E6FBDF1E100DFE73107A4933A" + "F7654778E8F8A848ABF7DE727E616B6F77A981CBA709AC39BBECC6CBD882B472" + "CD1DF4B885011E80FB1B892A5439B25BDAC80D55997A87733B08E6982DEA8DE0" + "332E1229F5C02F542721F7C8AC4EDA28B8B1A9DB96B2A742A2C9CF19414DE086" + "F92A9AA3116630D3BB74324BDF637BF5998A2F1BC721AF59B5AEDC443C975071" + "D7A1D2C555E369DE57C1D1DE30C0FDCCE64DFB0DBF5D4FE99D1E19382FBCCF58" + "052EEF0DA05035DAEF09271CD5B37E351E08BADA36DBD35F8FDE74884912A182" + "02D43082023D02010130820100A181D8A481D53081D2310B3009060355040613" + "025553311330110603550408130A57617368696E67746F6E3110300E06035504" + "0713075265646D6F6E64311E301C060355040A13154D6963726F736F66742043" + "6F72706F726174696F6E312D302B060355040B13244D6963726F736F66742049" + "72656C616E64204F7065726174696F6E73204C696D6974656431263024060355" + "040B131D5468616C6573205453532045534E3A303834322D344245362D433239" + "41312530230603550403131C4D6963726F736F66742054696D652D5374616D70" + "2053657276696365A2230A0101300706052B0E03021A0315000D4D94FE1BDE96" + "848D743F1DEE4A04C6B3658C07A08183308180A47E307C310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E312630240603550403131D4D6963726F736F667420" + "54696D652D5374616D70205043412032303130300D06092A864886F70D010105" + "0500020500E5084E973022180F32303231313030373030333433315A180F3230" + "3231313030383030333433315A3074303A060A2B0601040184590A0401312C30" + "2A300A020500E5084E97020100300702010002021DE630070201000202113630" + "0A020500E509A0170201003036060A2B0601040184590A040231283026300C06" + "0A2B0601040184590A0302A00A3008020100020307A120A10A30080201000203" + "0186A0300D06092A864886F70D0101050500038181002AE0DF2A01AAE13A86C0" + "2DD8ECA787327C8F04A7C13D47256E65C60676B8372EE46362CD35391B6B898E" + "DC1884082AAA7CF9B1CF40BE2C30146D0080ACB225C50B7C1FE94694732EDEEB" + "9EDE73DB7D8C0762CBDFABD3ACCC82DD3858AA16C3ED185A40A39E9676772099" + "346E3362621286651B06D9AD26D574F967F6C7EC335A3182030D308203090201" + "01308193307C310B3009060355040613025553311330110603550408130A5761" + "7368696E67746F6E3110300E060355040713075265646D6F6E64311E301C0603" + "55040A13154D6963726F736F667420436F72706F726174696F6E312630240603" + "550403131D4D6963726F736F66742054696D652D5374616D7020504341203230" + "313002133300000139CCE8E8438BF034E1000000000139300D06096086480165" + "030402010500A082014A301A06092A864886F70D010903310D060B2A864886F7" + "0D0109100104302F06092A864886F70D01090431220420EA37C01965AB5A8B08" + "C2A59F8EF2008C2B60F78E7F0385E2DD18A07C63433EF43081FA060B2A864886" + "F70D010910022F3181EA3081E73081E43081BD04203CA18EE438A3D7247B3142" + "B1E28105AE7C6A5527F39A7A9F26A6D4A0070FFC9F308198308180A47E307C31" + "0B3009060355040613025553311330110603550408130A57617368696E67746F" + "6E3110300E060355040713075265646D6F6E64311E301C060355040A13154D69" + "63726F736F667420436F72706F726174696F6E312630240603550403131D4D69" + "63726F736F66742054696D652D5374616D702050434120323031300213330000" + "0139CCE8E8438BF034E1000000000139302204204A6E54AC16FAF6985726E0CB" + "5480381C41888386AB1D1BECC241E6BCFCBDD45B300D06092A864886F70D0101" + "0B0500048201006957F018A5C13CC539EB266EC2725998F4AC0ED50CE1CAA696" + "CAE377977F45FB8030136A4038B49F7E5A6ADCF72FA3901C26B52815621F52A2" + "EB2ACFC423087ECD954F34C341342E31BDF30443CAC4F1297AB0181467B90604" + "DDCF11F9F8930290614E8AA9D868E56971E4F83427819F8A1A11ED87AD1D5469" + "7AFFE60A8D7B7877CBB1D09F46397769B9D0F8EB605DBFE8F05C47A3F8BC1F65" + "F9F63553F187194B35E971FEFFB00C9127BDFD0F7FCF2424BE2A108AC5C532EA" + "6AB46C76047604BA7DF071EE0137B73F4D9DF616095C8F1CA9EB925B6D4C6ABC" + "FFEB73A81903169C6B487B316AFC951F696831A4B29B9ABCEA7EBCD243A553D2" + "F8B44FDA1B0AC0").HexToByteArray(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { internal static class SignedDocuments { internal static readonly byte[] RsaPssDocument = ( "308204EC06092A864886F70D010702A08204DD308204D9020103310D300B0609" + "608648016503040201301F06092A864886F70D010701A0120410546869732069" + "73206120746573740D0AA08202CA308202C63082022EA003020102020900F399" + "4D1706DEC3F8300D06092A864886F70D01010B0500307B310B30090603550406" + "130255533113301106035504080C0A57617368696E67746F6E3110300E060355" + "04070C075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420" + "436F72702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112" + "301006035504030C096C6F63616C686F7374301E170D31363033303230323337" + "35345A170D3137303330323032333735345A307B310B30090603550406130255" + "533113301106035504080C0A57617368696E67746F6E3110300E06035504070C" + "075265646D6F6E6431183016060355040A0C0F4D6963726F736F667420436F72" + "702E31173015060355040B0C0E2E4E4554204672616D65776F726B3112301006" + "035504030C096C6F63616C686F73743081A0300D06092A864886F70D01010105" + "0003818E0030818A02818200BCACB1A5349D7B35A580AC3B3998EB15EBF900EC" + "B329BF1F75717A00B2199C8A18D791B592B7EC52BD5AF2DB0D3B635F0595753D" + "FF7BA7C9872DBF7E3226DEF44A07CA568D1017992C2B41BFE5EC3570824CF1F4" + "B15919FED513FDA56204AF2034A2D08FF04C2CCA49D168FA03FA2FA32FCCD348" + "4C15F0A2E5467C76FC760B55090203010001A350304E301D0603551D0E041604" + "141063CAB14FB14C47DC211C0E0285F3EE5946BF2D301F0603551D2304183016" + "80141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300C0603551D13040530" + "030101FF300D06092A864886F70D01010B050003818200435774FB66802AB3CE" + "2F1392C079483B48CC8913E0BF3B7AD88351E4C15B55CAD3061AA5875900C56B" + "2E7E84BB49CA2A0C1895BD60149C6A0AE983E48370E2144052943B066BD85F70" + "543CF6F2F255C028AE1DC8FB898AD3DCA97BF1D607370287077A4C147268C911" + "8CF9CAD318D2830D3468727E0A3247B3FEB8D87A7DE4F1E2318201D4308201D0" + "02010380141063CAB14FB14C47DC211C0E0285F3EE5946BF2D300B0609608648" + "016503040201A081E4301806092A864886F70D010903310B06092A864886F70D" + "010701301C06092A864886F70D010905310F170D313731303236303130363235" + "5A302F06092A864886F70D0109043122042007849DC26FCBB2F3BD5F57BDF214" + "BAE374575F1BD4E6816482324799417CB379307906092A864886F70D01090F31" + "6C306A300B060960864801650304012A300B0609608648016503040116300B06" + "09608648016503040102300A06082A864886F70D0307300E06082A864886F70D" + "030202020080300D06082A864886F70D0302020140300706052B0E030207300D" + "06082A864886F70D0302020128303D06092A864886F70D01010A3030A00D300B" + "0609608648016503040201A11A301806092A864886F70D010108300B06096086" + "48016503040201A20302015F048181B93E81D141B3C9F159AB0021910635DC72" + "E8E860BE43C28E5D53243D6DC247B7D4F18C20195E80DEDCC75B29C43CE5047A" + "D775B65BFC93589BD748B950C68BADDF1A4673130302BBDA8667D5DDE5EA91EC" + "CB13A9B4C04F1C4842FEB1697B7669C7692DD3BDAE13B5AA8EE3EB5679F3729D" + "1DC4F2EB9DC89B7E8773F2F8C6108C05").HexToByteArray(); public static byte[] RsaPkcs1OneSignerIssuerAndSerialNumber = ( "3082033706092A864886F70D010702A082032830820324020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "463181D73081D40201013032301E311C301A060355040313135253414B657954" + "72616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA3009" + "06052B0E03021A0500300D06092A864886F70D01010105000481805A1717621D" + "450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB34FAA" + "C33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF682D9C" + "A95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80DA27" + "FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3").HexToByteArray(); public static byte[] CounterSignedRsaPkcs1OneSigner = ( "3082044906092A864886F70D010702A082043A30820436020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201E8308201E40201013032301E311C301A060355040313135253414B65" + "795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" + "300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" + "621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" + "4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" + "2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" + "DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A18201" + "0C3082010806092A864886F70D0109063181FA3081F702010380146B4A6B92FD" + "ED07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A03F30180609" + "2A864886F70D010903310B06092A864886F70D010701302306092A864886F70D" + "010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DBA4300D06092A" + "864886F70D0101010500048180962518DEF789B0886C7E6295754ECDBDC4CB9D" + "153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844CBAEDCA9C4A068B2483" + "0E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA79D7312524F111A9B9" + "B0184007139F94E46C816E0E33F010AEB949F5D884DC8987765002F7A643F34B" + "7654E3B2FD5FB34A420279B1EA").HexToByteArray(); public static byte[] NoSignatureSignedWithAttributesAndCounterSignature = ( "3082042406092A864886F70D010702A082041530820411020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201C3308201BF020101301C3017311530130603550403130C44756D6D79" + "205369676E6572020100300906052B0E03021A0500A05D301806092A864886F7" + "0D010903310B06092A864886F70D010701301C06092A864886F70D010905310F" + "170D3137313130313137313731375A302306092A864886F70D01090431160414" + "A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300C06082B06010505070602" + "050004148B70D20D0477A35CD84AB962C10DC52FBA6FAD6BA182010C30820108" + "06092A864886F70D0109063181FA3081F702010380146B4A6B92FDED07EE0119" + "F3674A96D1A70D2A588D300906052B0E03021A0500A03F301806092A864886F7" + "0D010903310B06092A864886F70D010701302306092A864886F70D0109043116" + "0414833378066BDCCBA7047EF6919843D181A57D6479300D06092A864886F70D" + "01010105000481802155D226DD744166E582D040E60535210195050EA00F2C17" + "9897198521DABD0E6B27750FD8BA5F9AAF58B4863B6226456F38553A22453CAF" + "0A0F106766C7AB6F3D6AFD106753DC50F8A6E4F9E5508426D236C2DBB4BCB816" + "2FA42E995CBA16A340FD7C793569DF1B71368E68253299BC74E38312B40B8F52" + "EAEDE10DF414A522").HexToByteArray(); public static byte[] NoSignatureWithNoAttributes = ( "30819B06092A864886F70D010702A0818D30818A020101310B300906052B0E03" + "021A0500302406092A864886F70D010701A01704154D6963726F736F66742043" + "6F72706F726174696F6E31523050020101301C3017311530130603550403130C" + "44756D6D79205369676E6572020100300906052B0E03021A0500300C06082B06" + "01050507060205000414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E").HexToByteArray(); public static byte[] RsaCapiTransfer1_NoEmbeddedCert = ( "3082016606092A864886F70D010702A082015730820153020103310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6E318201193082011502010380146B4A6B92FDED" + "07EE0119F3674A96D1A70D2A588D300906052B0E03021A0500A05D301806092A" + "864886F70D010903310B06092A864886F70D010701301C06092A864886F70D01" + "0905310F170D3137313130323135333430345A302306092A864886F70D010904" + "31160414A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E300D06092A864886" + "F70D01010105000481800EDE3870B8A80B45A21BAEC4681D059B46502E1B1AA6" + "B8920CF50D4D837646A55559B4C05849126C655D95FF3C6C1B420E07DC42629F" + "294EE69822FEA56F32D41B824CBB6BF809B7583C27E77B7AC58DFC925B1C60EA" + "4A67AA84D73FC9E9191D33B36645F17FD6748A2D8B12C6C384C3C734D2727338" + "6211E4518FE2B4ED0147").HexToByteArray(); public static byte[] OneRsaSignerTwoRsaCounterSigners = ( "3082075106092A864886F70D010702A08207423082073E020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08203F9308201E530820152A0030201020210" + "D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021D05003011310F30" + "0D060355040313064D794E616D65301E170D3130303430313038303030305A17" + "0D3131303430313038303030305A3011310F300D060355040313064D794E616D" + "6530819F300D06092A864886F70D010101050003818D0030818902818100B11E" + "30EA87424A371E30227E933CE6BE0E65FF1C189D0D888EC8FF13AA7B42B68056" + "128322B21F2B6976609B62B6BC4CF2E55FF5AE64E9B68C78A3C2DACC916A1BC7" + "322DD353B32898675CFB5B298B176D978B1F12313E3D865BC53465A11CCA1068" + "70A4B5D50A2C410938240E92B64902BAEA23EB093D9599E9E372E48336730203" + "010001A346304430420603551D01043B3039801024859EBF125E76AF3F0D7979" + "B4AC7A96A1133011310F300D060355040313064D794E616D658210D5B5BC1C45" + "8A558845BFF51CB4DFF31C300906052B0E03021D0500038181009BF6E2CF830E" + "D485B86D6B9E8DFFDCD65EFC7EC145CB9348923710666791FCFA3AB59D689FFD" + "7234B7872611C5C23E5E0714531ABADB5DE492D2C736E1C929E648A65CC9EB63" + "CD84E57B5909DD5DDF5DBBBA4A6498B9CA225B6E368B94913BFC24DE6B2BD9A2" + "6B192B957304B89531E902FFC91B54B237BB228BE8AFCDA264763082020C3082" + "0179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03" + "021D0500301E311C301A060355040313135253414B65795472616E7366657243" + "61706931301E170D3135303431353037303030305A170D323530343135303730" + "3030305A301E311C301A060355040313135253414B65795472616E7366657243" + "6170693130819F300D06092A864886F70D010101050003818D00308189028181" + "00AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB66" + "71BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1" + "A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD" + "910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9942440" + "8D0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4" + "BA89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E" + "73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B" + "0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3C" + "CF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D0" + "19FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D119" + "57D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1AD" + "B09F291822E99A42964631820307308203030201013032301E311C301A060355" + "040313135253414B65795472616E73666572436170693102105D2FFFF863BABC" + "9B4D3C80AB178A4CCA300906052B0E03021A0500300D06092A864886F70D0101" + "0105000481805A1717621D450130B3463662160EEC06F7AE77E017DD95F294E9" + "7A0BDD433FE6B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE7" + "7B8495091E096EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB" + "09DF57A53B733A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E963" + "2ABF02BE2FE3A182022B3082010806092A864886F70D0109063181FA3081F702" + "010380146B4A6B92FDED07EE0119F3674A96D1A70D2A588D300906052B0E0302" + "1A0500A03F301806092A864886F70D010903310B06092A864886F70D01070130" + "2306092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A5091" + "23F9DBA4300D06092A864886F70D0101010500048180962518DEF789B0886C7E" + "6295754ECDBDC4CB9D153ECE5EBBE7A82142B92C30DDBBDFC22B5B954F5D844C" + "BAEDCA9C4A068B24830E2A96141A5D0320B69EA5DFCFEA441E162D04506F8FFA" + "79D7312524F111A9B9B0184007139F94E46C816E0E33F010AEB949F5D884DC89" + "87765002F7A643F34B7654E3B2FD5FB34A420279B1EA3082011B06092A864886" + "F70D0109063182010C3082010802010130253011310F300D060355040313064D" + "794E616D650210D5B5BC1C458A558845BFF51CB4DFF31C300906052B0E03021A" + "0500A03F301806092A864886F70D010903310B06092A864886F70D0107013023" + "06092A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123" + "F9DBA4300D06092A864886F70D01010105000481801AA282DBED4D862D7CEA30" + "F803E790BDB0C97EE852778CEEDDCD94BB9304A1552E60A8D36052AC8C2D2875" + "5F3B2F473824100AB3A6ABD4C15ABD77E0FFE13D0DF253BCD99C718FA673B6CB" + "0CBBC68CE5A4AC671298C0A07C7223522E0E7FFF15CEDBAB55AAA99588517674" + "671691065EB083FB729D1E9C04B2BF99A9953DAA5E").HexToByteArray(); public static readonly byte[] RsaPkcs1CounterSignedWithNoSignature = ( "308203E106092A864886F70D010702A08203D2308203CE020101310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08202103082020C30820179A0030201020210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E311C30" + "1A060355040313135253414B65795472616E736665724361706931301E170D31" + "35303431353037303030305A170D3235303431353037303030305A301E311C30" + "1A060355040313135253414B65795472616E73666572436170693130819F300D" + "06092A864886F70D010101050003818D0030818902818100AA272700586C0CC4" + "1B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63BA2B1" + "AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6C9D2" + "B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF76C1" + "3B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A35330" + "51304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7AA120" + "301E311C301A060355040313135253414B65795472616E736665724361706931" + "82105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500038181" + "0081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8DC19" + "38952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D54646975B6D" + "C2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E5291E4" + "401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A4296" + "46318201803082017C0201013032301E311C301A060355040313135253414B65" + "795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" + "300906052B0E03021A0500300D06092A864886F70D01010105000481805A1717" + "621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6B2CCB3" + "4FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E096EEF68" + "2D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B733A4E80" + "DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3A181A5" + "3081A206092A864886F70D010906318194308191020101301C30173115301306" + "03550403130C44756D6D79205369676E6572020100300906052B0E03021A0500" + "A03F301806092A864886F70D010903310B06092A864886F70D01070130230609" + "2A864886F70D010904311604148C054D6DF2B08E69A86D8DB23C1A509123F9DB" + "A4300C06082B060105050706020500041466124B3D99FE06A19BBD3C83C593AB" + "55D875E28B").HexToByteArray(); public static readonly byte[] UnsortedSignerInfos = ( "30820B1E06092A864886F70D010702A0820B0F30820B0B020103310B30090605" + "2B0E03021A0500301006092A864886F70D010701A003040107A0820540308202" + "0C30820179A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA30090605" + "2B0E03021D0500301E311C301A060355040313135253414B65795472616E7366" + "65724361706931301E170D3135303431353037303030305A170D323530343135" + "3037303030305A301E311C301A060355040313135253414B65795472616E7366" + "6572436170693130819F300D06092A864886F70D010101050003818D00308189" + "02818100AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75" + "B6EB6671BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B8" + "6570D1A1D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAAC" + "A965CD910B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F9" + "9424408D0203010001A3533051304F0603551D0104483046801015432DB116B3" + "5D07E4BA89EDB2469D7AA120301E311C301A060355040313135253414B657954" + "72616E73666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA3009" + "06052B0E03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319" + "265F3CCF23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2" + "FCE3D019FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A0" + "75D11957D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083" + "C8D1ADB09F291822E99A4296463082032C30820214A003020102020900E0D8AB" + "6819D7306E300D06092A864886F70D01010B0500303831363034060355040313" + "2D54776F2074686F7573616E6420666F7274792065696768742062697473206F" + "662052534120676F6F646E657373301E170D3137313130333233353131355A17" + "0D3138313130333233353131355A3038313630340603550403132D54776F2074" + "686F7573616E6420666F7274792065696768742062697473206F662052534120" + "676F6F646E65737330820122300D06092A864886F70D01010105000382010F00" + "3082010A028201010096C114A5898D09133EF859F89C1D848BA8CB5258793E05" + "B92D499C55EEFACE274BBBC26803FB813B9C11C6898153CC1745DED2C4D2672F" + "807F0B2D957BC4B65EBC9DDE26E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33" + "C8B57248B3D5E3901D8A38A283D7E25FF8E6F522381EE5484234CFF7B30C1746" + "35418FA89E14C468AD89DCFCBBB535E5AF53510F9EA7F9DA8C1B53375B6DAB95" + "A291439A5648726EE1012E41388E100691642CF6917F5569D8351F2782F435A5" + "79014E8448EEA0C4AECAFF2F476799D88457E2C8BCB56E5E128782B4FE26AFF0" + "720D91D52CCAFE344255808F5271D09F784F787E8323182080915BE0AE15A71D" + "66476D0F264DD084F30203010001A3393037301D0603551D0E04160414745B5F" + "12EF962E84B897E246D399A2BADEA9C5AC30090603551D1304023000300B0603" + "551D0F040403020780300D06092A864886F70D01010B0500038201010087A15D" + "F37FBD6E9DED7A8FFF25E60B731F635469BA01DD14BC03B2A24D99EFD8B894E9" + "493D63EC88C496CB04B33DF25222544F23D43F4023612C4D97B719C1F9431E4D" + "B7A580CDF66A3E5F0DAF89A267DD187ABFFB08361B1F79232376AA5FC5AD384C" + "C2F98FE36C1CEA0B943E1E3961190648889C8ABE8397A5A338843CBFB1D8B212" + "BE46685ACE7B80475CC7C97FC0377936ABD5F664E9C09C463897726650711A11" + "10FA9866BC1C278D95E5636AB96FAE95CCD67FD572A8C727E2C03E7B24245731" + "8BEC1BE52CA5BD9454A0A41140AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC9" + "4F7E3C7D476F298962245563953AD7225EDCEAC8B8509E49292E62D8BF318205" + "A1308202FB0201038014745B5F12EF962E84B897E246D399A2BADEA9C5AC3009" + "06052B0E03021A0500300D06092A864886F70D0101010500048201005E03C5E2" + "E736792EFB1C8632C3A864AA6F0E930717FE02C755C0F94DC671244A371926F6" + "09878DC8CBFCBA6F83A841B24F48952DA5344F2210BFE9B744E3367B1F8399C8" + "96F675923A57E084EBD7DC76A24A1530CD513F0DF6A7703246BF335CC3D09776" + "442942150F1C31B9B212AF48850B44B95EB5BD64105F09723EF6AD4711FD81CD" + "1FC0418E68EA4428CED9E184126761BF2B25756B6D9BC1A0530E56D38F2A0B78" + "3F21D6A5C0703C38F29A2B701B13CAFFCA1DC21C39059E4388E54AEA2519C4E8" + "83C7A6BD78200DCB931CA6AB3D18DBBF46A5444C89B6DFE2F48F32C44BA9C030" + "F399AC677AA323203137D33CEBFBF1BBF9A506309953B23C4100CA7CA18201C0" + "308201BC06092A864886F70D010906318201AD308201A9020101304530383136" + "30340603550403132D54776F2074686F7573616E6420666F7274792065696768" + "742062697473206F662052534120676F6F646E657373020900E0D8AB6819D730" + "6E300906052B0E03021A0500A03F301806092A864886F70D010903310B06092A" + "864886F70D010701302306092A864886F70D0109043116041481BF56A6550A60" + "A649B0D97971C49897635953D0300D06092A864886F70D010101050004820100" + "6E41B7585FEB419005362FEAAAAFB2059E98F8905221A7564F7B0B5510CB221D" + "F3DD914A4CD441EAC1C6746A6EC4FC8399C12A61C6B0F50DDA090F564F3D65B2" + "6D4BDBC1CE3D39CF47CF33B0D269D15A9FAF2169C60887C3E2CC9828B5E16D45" + "DC27A94BAF8D6650EE63D2DBB7DA319B3F61DD18E28AF6FE6DF2CC15C2910BD6" + "0B7E038F2C6E8BAEC35CBBBF9484D4C76ECE041DF534B8713B6537854EFE6D58" + "41768CCBB9A3B729FDDAE07780CB143A3EE5972DCDDF60A38C65CD3FFF35D1B6" + "B76227C1B53831773DA441603F4FB5764D33AADE102F9B85D2CDAEC0E3D6C6E8" + "C24C434BFAA3E12E02202142784ED0EB2D9CDCC276D21474747DCD3E4F4D54FC" + "3081D40201013032301E311C301A060355040313135253414B65795472616E73" + "666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021A0500300D06092A864886F70D01010105000481805EB33C6A9ED5B62240" + "90C431E79F51D70B4F2A7D31ED4ED8C3465F6E01281C3FFA44116238B2D168D8" + "9154136DDB8B4EB31EA685FB719B7384510F5EF077A10DE6A5CA86F4F6D28B58" + "79AFD6CFF0BDA005C2D7CFF53620D28988CBAA44F18AA2D50229FA930B0A7262" + "D780DFDEC0334A97DF872F1D95087DC11A881568AF5B88308201C70201013045" + "3038313630340603550403132D54776F2074686F7573616E6420666F72747920" + "65696768742062697473206F662052534120676F6F646E657373020900E0D8AB" + "6819D7306E300906052B0E03021A0500A05D301806092A864886F70D01090331" + "0B06092A864886F70D010701301C06092A864886F70D010905310F170D313731" + "3130393136303934315A302306092A864886F70D010904311604145D1BE7E9DD" + "A1EE8896BE5B7E34A85EE16452A7B4300D06092A864886F70D01010105000482" + "01000BB9410F23CFD9C1FCB16179612DB871224F5B88A8E2C012DCDBB3699780" + "A3311FD330FFDD6DF1434C52DADD6E07D81FEF145B806E71AF471223914B98CD" + "588CCCDFB50ABE3D991B11D62BD83DE158A9001BAED3549BC49B8C204D25C17B" + "D042756B026692959E321ACC1AFE6BF52C9356FD49936116D2B3D1F6569F8A8B" + "F0FBB2E403AD5788681F3AD131E57390ACB9B8C2EA0BE717F22EFE577EFB1063" + "6AC465469191B7E4B3F03CF8DC6C310A20D2B0891BC27350C7231BC2EAABF129" + "83755B4C0EDF8A0EE99A615D4E8B381C67A7CDB1405D98C2A6285FEDCED5A65F" + "C45C31CD33E3CEB96223DB45E9156B9BD7C8E442C40ED1BB6866C03548616061" + "3DAF").HexToByteArray(); public static byte[] OneDsa1024 = ( "3082044206092A864886F70D010702A08204333082042F020103310B30090605" + "2B0E03021A0500302406092A864886F70D010701A01704154D6963726F736F66" + "7420436F72706F726174696F6EA08203913082038D3082034AA0030201020209" + "00AB740A714AA83C92300B060960864801650304030230818D310B3009060355" + "040613025553311330110603550408130A57617368696E67746F6E3110300E06" + "0355040713075265646D6F6E64311E301C060355040A13154D6963726F736F66" + "7420436F72706F726174696F6E3120301E060355040B13172E4E455420467261" + "6D65776F726B2028436F7265465829311530130603550403130C313032342D62" + "697420445341301E170D3135313132353134343030335A170D31353132323531" + "34343030335A30818D310B300906035504061302555331133011060355040813" + "0A57617368696E67746F6E3110300E060355040713075265646D6F6E64311E30" + "1C060355040A13154D6963726F736F667420436F72706F726174696F6E312030" + "1E060355040B13172E4E4554204672616D65776F726B2028436F726546582931" + "1530130603550403130C313032342D62697420445341308201B73082012C0607" + "2A8648CE3804013082011F02818100AEE3309FC7C9DB750D4C3797D333B3B9B2" + "34B462868DB6FFBDED790B7FC8DDD574C2BD6F5E749622507AB2C09DF5EAAD84" + "859FC0706A70BB8C9C8BE22B4890EF2325280E3A7F9A3CE341DBABEF6058D063" + "EA6783478FF8B3B7A45E0CA3F7BAC9995DCFDDD56DF168E91349130F719A4E71" + "7351FAAD1A77EAC043611DC5CC5A7F021500D23428A76743EA3B49C62EF0AA17" + "314A85415F0902818100853F830BDAA738465300CFEE02418E6B07965658EAFD" + "A7E338A2EB1531C0E0CA5EF1A12D9DDC7B550A5A205D1FF87F69500A4E4AF575" + "9F3F6E7F0C48C55396B738164D9E35FB506BD50E090F6A497C70E7E868C61BD4" + "477C1D62922B3DBB40B688DE7C175447E2E826901A109FAD624F1481B276BF63" + "A665D99C87CEE9FD06330381840002818025B8E7078E149BAC35266762362002" + "9F5E4A5D4126E336D56F1189F9FF71EA671B844EBD351514F27B69685DDF716B" + "32F102D60EA520D56F544D19B2F08F5D9BDDA3CBA3A73287E21E559E6A075861" + "94AFAC4F6E721EDCE49DE0029627626D7BD30EEB337311DB4FF62D7608997B6C" + "C32E9C42859820CA7EF399590D5A388C48A330302E302C0603551D1104253023" + "87047F00000187100000000000000000000000000000000182096C6F63616C68" + "6F7374300B0609608648016503040302033000302D021500B9316CC7E05C9F79" + "197E0B41F6FD4E3FCEB72A8A0214075505CCAECB18B7EF4C00F9C069FA3BC780" + "14DE31623060020103801428A2CB1D204C2656A79C931EFAE351AB548248D030" + "0906052B0E03021A0500300906072A8648CE380403042F302D021476DCB780CE" + "D5B308A3630726A85DB97FBC50DFD1021500CDF2649B50500BB7428B9DCA6BEF" + "2C7E7EF1B79C").HexToByteArray(); public static byte[] RsaPkcs1TwoCounterSignaturesInSingleAttribute = ( "30820BBA06092A864886F70D010702A0820BAB30820BA7020101310D300B0609" + "608648016503040201301406092A864886F70D010701A00704050102030405A0" + "82081D308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4D" + "C8300A06082A8648CE3D04030230153113301106035504030C0A454344534120" + "54657374301E170D3135303530313030333730335A170D313630353031303035" + "3730335A30153113301106035504030C0A454344534120546573743059301306" + "072A8648CE3D020106082A8648CE3D030107034200047590F69CA114E92927E0" + "34C997B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA3249" + "6FDAC84E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D" + "0F0101FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5C" + "CFB8220CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E" + "19F1AE4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CB" + "DF434FDD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E30" + "82032C30820214A003020102020900E0D8AB6819D7306E300D06092A864886F7" + "0D01010B05003038313630340603550403132D54776F2074686F7573616E6420" + "666F7274792065696768742062697473206F662052534120676F6F646E657373" + "301E170D3137313130333233353131355A170D3138313130333233353131355A" + "3038313630340603550403132D54776F2074686F7573616E6420666F72747920" + "65696768742062697473206F662052534120676F6F646E65737330820122300D" + "06092A864886F70D01010105000382010F003082010A028201010096C114A589" + "8D09133EF859F89C1D848BA8CB5258793E05B92D499C55EEFACE274BBBC26803" + "FB813B9C11C6898153CC1745DED2C4D2672F807F0B2D957BC4B65EBC9DDE26E2" + "EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33C8B57248B3D5E3901D8A38A283D7" + "E25FF8E6F522381EE5484234CFF7B30C174635418FA89E14C468AD89DCFCBBB5" + "35E5AF53510F9EA7F9DA8C1B53375B6DAB95A291439A5648726EE1012E41388E" + "100691642CF6917F5569D8351F2782F435A579014E8448EEA0C4AECAFF2F4767" + "99D88457E2C8BCB56E5E128782B4FE26AFF0720D91D52CCAFE344255808F5271" + "D09F784F787E8323182080915BE0AE15A71D66476D0F264DD084F30203010001" + "A3393037301D0603551D0E04160414745B5F12EF962E84B897E246D399A2BADE" + "A9C5AC30090603551D1304023000300B0603551D0F040403020780300D06092A" + "864886F70D01010B0500038201010087A15DF37FBD6E9DED7A8FFF25E60B731F" + "635469BA01DD14BC03B2A24D99EFD8B894E9493D63EC88C496CB04B33DF25222" + "544F23D43F4023612C4D97B719C1F9431E4DB7A580CDF66A3E5F0DAF89A267DD" + "187ABFFB08361B1F79232376AA5FC5AD384CC2F98FE36C1CEA0B943E1E396119" + "0648889C8ABE8397A5A338843CBFB1D8B212BE46685ACE7B80475CC7C97FC037" + "7936ABD5F664E9C09C463897726650711A1110FA9866BC1C278D95E5636AB96F" + "AE95CCD67FD572A8C727E2C03E7B242457318BEC1BE52CA5BD9454A0A41140AE" + "96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC94F7E3C7D476F298962245563953A" + "D7225EDCEAC8B8509E49292E62D8BF3082038D3082034AA003020102020900AB" + "740A714AA83C92300B060960864801650304030230818D310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D65" + "776F726B2028436F7265465829311530130603550403130C313032342D626974" + "20445341301E170D3135313132353134343030335A170D313531323235313434" + "3030335A30818D310B3009060355040613025553311330110603550408130A57" + "617368696E67746F6E3110300E060355040713075265646D6F6E64311E301C06" + "0355040A13154D6963726F736F667420436F72706F726174696F6E3120301E06" + "0355040B13172E4E4554204672616D65776F726B2028436F7265465829311530" + "130603550403130C313032342D62697420445341308201B73082012C06072A86" + "48CE3804013082011F02818100AEE3309FC7C9DB750D4C3797D333B3B9B234B4" + "62868DB6FFBDED790B7FC8DDD574C2BD6F5E749622507AB2C09DF5EAAD84859F" + "C0706A70BB8C9C8BE22B4890EF2325280E3A7F9A3CE341DBABEF6058D063EA67" + "83478FF8B3B7A45E0CA3F7BAC9995DCFDDD56DF168E91349130F719A4E717351" + "FAAD1A77EAC043611DC5CC5A7F021500D23428A76743EA3B49C62EF0AA17314A" + "85415F0902818100853F830BDAA738465300CFEE02418E6B07965658EAFDA7E3" + "38A2EB1531C0E0CA5EF1A12D9DDC7B550A5A205D1FF87F69500A4E4AF5759F3F" + "6E7F0C48C55396B738164D9E35FB506BD50E090F6A497C70E7E868C61BD4477C" + "1D62922B3DBB40B688DE7C175447E2E826901A109FAD624F1481B276BF63A665" + "D99C87CEE9FD06330381840002818025B8E7078E149BAC352667623620029F5E" + "4A5D4126E336D56F1189F9FF71EA671B844EBD351514F27B69685DDF716B32F1" + "02D60EA520D56F544D19B2F08F5D9BDDA3CBA3A73287E21E559E6A07586194AF" + "AC4F6E721EDCE49DE0029627626D7BD30EEB337311DB4FF62D7608997B6CC32E" + "9C42859820CA7EF399590D5A388C48A330302E302C0603551D11042530238704" + "7F00000187100000000000000000000000000000000182096C6F63616C686F73" + "74300B0609608648016503040302033000302D021500B9316CC7E05C9F79197E" + "0B41F6FD4E3FCEB72A8A0214075505CCAECB18B7EF4C00F9C069FA3BC78014DE" + "3182035A3082035602010130453038313630340603550403132D54776F207468" + "6F7573616E6420666F7274792065696768742062697473206F66205253412067" + "6F6F646E657373020900E0D8AB6819D7306E300B060960864801650304020130" + "0B06092A864886F70D01010104820100457E2996B3A1AE5C7DC2F4EF4D9010F4" + "8B62B72DFB43F2EDC503FD32408A1058EE7BBCF4750CB4B4242B11A599C40792" + "70D32D15A57FF791FF59836A027E634B9B97E1764173597A9A6155D5ED5365F6" + "5DF14FDD15928ABD63E1409DBF2D1A713D20D80E09EE76BC63775F3FA8638A26" + "ED3816FF87C7CDC8A9299485055BFC38AE158BB6577812AA98436FB54844544A" + "C92CD449690B8107447044580FAE590D8A7326A8D139886C8A4AC8CEEACB0458" + "1666D8447D267F1A9E9CAB20F155E05D5EC055AC863C047B5E1E3A98528EA766" + "7C19B33AD98B2D33ABBD7E607C1DA18BCDB87C626554C277E069CE9EC489BC87" + "2E7DEAED4C642DE5AB10BD2D558EAFB3A18201EA308201E606092A864886F70D" + "010906318201D73082010D02010130819B30818D310B30090603550406130255" + "53311330110603550408130A57617368696E67746F6E3110300E060355040713" + "075265646D6F6E64311E301C060355040A13154D6963726F736F667420436F72" + "706F726174696F6E3120301E060355040B13172E4E4554204672616D65776F72" + "6B2028436F7265465829311530130603550403130C313032342D626974204453" + "41020900AB740A714AA83C92300706052B0E03021AA025302306092A864886F7" + "0D0109043116041409200943E2EDD3DD3B186C5839BDC9B1051903FF30090607" + "2A8648CE380403042F302D0215009FDBE95176B1EC0697155ADDF335E5126A9F" + "59D60214736F650C74E73BEA577151BCFD226FEDC06832E53081C30201013029" + "30153113301106035504030C0A45434453412054657374021035428F3B3C5107" + "AD49E776D6E74C4DC8300B0609608648016503040201A031302F06092A864886" + "F70D01090431220420DF5D49DB775A8F94CAB3129038B200EDE9FCD2AE8F039D" + "B1AB96D9B827D299D2300A06082A8648CE3D0403020447304502202327A60E1A" + "5A798CD29B72C7C7991F968D29DB15C4865BEE83A7E2FD73326CA4022100899F" + "000179F77BFE296783548EAE56BA7F53C0DB0563A27A36A149BAEC9C23AC").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_IssuerSerial_NetFx = ( "3082047C06092A864886F70D010702A082046D30820469020101310B30090605" + "2B0E03021A05003082012406092A864886F70D010703A0820115308201110609" + "2A864886F70D010703A08201023081FF0201003181CC3081C90201003032301E" + "311C301A060355040313135253414B65795472616E7366657243617069310210" + "5D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D010101050004" + "81800BB53BF3BD028A6B54703899B241CB358CACBF9018A4497A733C27EA223E" + "05BD31099EB80AE04ADBB23A5E397C181A14476668402EFE3BCA08BCA615C743" + "41FA06D56671AA940BF09B6B7B4C6905AD2927DE94960ED03DF141360589979F" + "9944DB48B91AA1B139EB652D6A1BAC48DF33AF14006CD9DB4C09E7DA270733D0" + "DF90302B06092A864886F70D010701301406082A864886F70D03070408E4972B" + "4188B1B4FE80084CBF0A9D37B094EBA08202103082020C30820179A003020102" + "02105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D0500301E31" + "1C301A060355040313135253414B65795472616E736665724361706931301E17" + "0D3135303431353037303030305A170D3235303431353037303030305A301E31" + "1C301A060355040313135253414B65795472616E73666572436170693130819F" + "300D06092A864886F70D010101050003818D0030818902818100AA272700586C" + "0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA9596C5C63B" + "A2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44EC86AA8F6" + "C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37DA4093EF" + "76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203010001A3" + "533051304F0603551D0104483046801015432DB116B35D07E4BA89EDB2469D7A" + "A120301E311C301A060355040313135253414B65795472616E73666572436170" + "693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D050003" + "81810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF23369FA533C8" + "DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70D5464697" + "5B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653B5C78E52" + "91E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F291822E99A" + "42964631820119308201150201013032301E311C301A06035504031313525341" + "4B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A" + "4CCA300906052B0E03021A0500A03F301806092A864886F70D010903310B0609" + "2A864886F70D010703302306092A864886F70D01090431160414FE46C861E86B" + "719D0F665AFAE48165B56CDFBFD4300D06092A864886F70D0101010500048180" + "32CEE36532673C2734C908A48B6E017FD695BE69FAC21028B6627466B72688D8" + "60FC65F2F18E5C19FED2301351F247DF90217087C5F88D76CA052287E6A2F47F" + "7DA5AC226B4FC202AB0B5B73A24B5C138247F54466621288F2DA941320C4CE89" + "A503ED3E6F63112798A841E55344BEE84E1366E4CF3788C9788C5E86D1879029").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_SKID_NetFx = ( "3082046006092A864886F70D010702A08204513082044D020103310B30090605" + "2B0E03021A05003082012806092A864886F70D010703A0820119048201153082" + "011106092A864886F70D010703A08201023081FF0201003181CC3081C9020100" + "3032301E311C301A060355040313135253414B65795472616E73666572436170" + "693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D0101" + "0105000481803ECF128C059F49199D3344979BD0EBAC2A5443D4F27775B8CFAC" + "7B1F28AFDDAD86097FF34DFB3ED2D514C325B78074D6D17CA14952EA954E860B" + "D5980F2C629C70AE402D3E9E867246E532E345712DFA33C37EF141E2EBFD10F7" + "249CFD193B313825CB7B297FB204DA755F02384659F51D97AB31F867C7E973C6" + "28B9F6E43018302B06092A864886F70D010701301406082A864886F70D030704" + "089FC5129D8AB0CDDE80086D7E35774EFA334AA08202103082020C30820179A0" + "0302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E03021D05" + "00301E311C301A060355040313135253414B65795472616E7366657243617069" + "31301E170D3135303431353037303030305A170D323530343135303730303030" + "5A301E311C301A060355040313135253414B65795472616E7366657243617069" + "3130819F300D06092A864886F70D010101050003818D0030818902818100AA27" + "2700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671BA95" + "96C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1D44E" + "C86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD910B37" + "DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D0203" + "010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA89ED" + "B2469D7AA120301E311C301A060355040313135253414B65795472616E736665" + "72436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF2336" + "9FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019FA70" + "D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957D653" + "B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB09F29" + "1822E99A4296463181FA3081F702010380146B4A6B92FDED07EE0119F3674A96" + "D1A70D2A588D300906052B0E03021A0500A03F301806092A864886F70D010903" + "310B06092A864886F70D010703302306092A864886F70D0109043116041435DE" + "A4AE3B383A023271BA27D2D50EC021D40800300D06092A864886F70D01010105" + "00048180386A2EB06AB0ED0111EB37214480CD782243C66105948AD8EAB3236A" + "7ECF135F22B6558F3C601140F6BBDF313F7DB98B3E6277ED5C2407D57323348D" + "A97F6A9653C7C219EE1B0E3F85A970FA6CFC00B53E72484F732916E6067E2F0D" + "4D31EFF51CECD46F3EF245FEF8729C4E1F16C0A3054054477D6C787FC7C94D79" + "A24AC54B").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_IssuerSerial_CoreFx = ( "3082048E06092A864886F70D010702A082047F3082047B020103310D300B0609" + "6086480165030402013082012806092A864886F70D010703A082011904820115" + "3082011106092A864886F70D010703A08201023081FF0201003181CC3081C902" + "01003032301E311C301A060355040313135253414B65795472616E7366657243" + "6170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D" + "01010105000481801B7806566B26A92076D5C9F5A06FBC9AB1D53BD63D3B7F97" + "569B683219C4BA0B285F2F3EF533387EDD7E6BE38DFDD1F33EBA8E5001238BD0" + "E75B9A5C5E2504FD78954B372A2E8B183F4CBD2D239CB72D129E112D0476D9A9" + "A00AF0EC700776F4719BC4838DBAC7F06C671F67B977ABDF449B42C98D28035A" + "194CE2B786E8C8A2302B06092A864886F70D010701301406082A864886F70D03" + "070408B4B41A525B6E8F628008767424A015173966A08202103082020C308201" + "79A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D0500301E311C301A060355040313135253414B65795472616E736665724361" + "706931301E170D3135303431353037303030305A170D32353034313530373030" + "30305A301E311C301A060355040313135253414B65795472616E736665724361" + "70693130819F300D06092A864886F70D010101050003818D0030818902818100" + "AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671" + "BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1" + "D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD91" + "0B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D" + "0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA" + "89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E73" + "666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF" + "23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019" + "FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957" + "D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB0" + "9F291822E99A42964631820125308201210201013032301E311C301A06035504" + "0313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B" + "4D3C80AB178A4CCA300B0609608648016503040201A04B301806092A864886F7" + "0D010903310B06092A864886F70D010703302F06092A864886F70D0109043122" + "042018BEF3F24109B4BCD5BF3D5372EA7A0D16AF6DF46DE9BE5C2373DF065381" + "5E13300B06092A864886F70D01010104818016A02798B3CEC42BE258C85A4BED" + "06099339C9E716B8C72A3330923BE4B6A0538A5DCE031CD710589E8281E24074" + "F26AB6B86CEACF78449B82FF1512F511B5A97ABA4403029E2BA1D837D3F9D230" + "45E0EB3CE59E3AF7E52B814EFCBBCFD7A442327C5C408D166D4302AEFF807ECB" + "D107C811DC66EC35FE167408B58FB03B7F84").HexToByteArray(); internal static readonly byte[] SignedCmsOverEnvelopedCms_SKID_CoreFx = ( "3082047006092A864886F70D010702A08204613082045D020103310D300B0609" + "6086480165030402013082012806092A864886F70D010703A082011904820115" + "3082011106092A864886F70D010703A08201023081FF0201003181CC3081C902" + "01003032301E311C301A060355040313135253414B65795472616E7366657243" + "6170693102105D2FFFF863BABC9B4D3C80AB178A4CCA300D06092A864886F70D" + "0101010500048180724D9D5E0D2110B8147589120524B1D1E7019A3F436AD459" + "3DF555413423AE28FCBA01548B20FDCA21901ECF6B54331542CECD4326C7E292" + "54AA563D7F38C2287C146B648E6779FA3843FB0F11A3726265266DF87BAAF04B" + "AA1DD4825B9FFFEBD1DC47414EA4978580A03484B9159E57045018DAA3054704" + "84046F89465169A0302B06092A864886F70D010701301406082A864886F70D03" + "0704087E74D74C2652F5198008930CBA811F9E9E15A08202103082020C308201" + "79A00302010202105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E0302" + "1D0500301E311C301A060355040313135253414B65795472616E736665724361" + "706931301E170D3135303431353037303030305A170D32353034313530373030" + "30305A301E311C301A060355040313135253414B65795472616E736665724361" + "70693130819F300D06092A864886F70D010101050003818D0030818902818100" + "AA272700586C0CC41B05C65C7D846F5A2BC27B03E301C37D9BFF6D75B6EB6671" + "BA9596C5C63BA2B1AF5C318D9CA39E7400D10C238AC72630579211B86570D1A1" + "D44EC86AA8F6C9D2B4E283EA3535923F398A312A23EAEACD8D34FAACA965CD91" + "0B37DA4093EF76C13B337C1AFAB7D1D07E317B41A336BAA4111299F99424408D" + "0203010001A3533051304F0603551D0104483046801015432DB116B35D07E4BA" + "89EDB2469D7AA120301E311C301A060355040313135253414B65795472616E73" + "666572436170693182105D2FFFF863BABC9B4D3C80AB178A4CCA300906052B0E" + "03021D05000381810081E5535D8ECEEF265ACBC82F6C5F8BC9D84319265F3CCF" + "23369FA533C8DC1938952C5931662D9ECD8B1E7B81749E48468167E2FCE3D019" + "FA70D54646975B6DC2A3BA72D5A5274C1866DA6D7A5DF47938E034A075D11957" + "D653B5C78E5291E4401045576F6D4EDA81BEF3C369AF56121E49A083C8D1ADB0" + "9F291822E99A429646318201073082010302010380146B4A6B92FDED07EE0119" + "F3674A96D1A70D2A588D300B0609608648016503040201A04B301806092A8648" + "86F70D010903310B06092A864886F70D010703302F06092A864886F70D010904" + "31220420873B6A3B7CE192922129761C3EDD8D68C4A6B0369F3BF5B3D30B0A9E" + "2336A8F4300B06092A864886F70D0101010481807D31B3260AE00DE3992DDD1E" + "B01FDECA28053F2B87AA723CCD27B92896E3199F7C4B3B4A391C181899E5CBD1" + "4A4BCDDFF6DC6CD10CA118DAA62E32589F066D1669D2948E51B5363B7BEE2BA9" + "351CDE1791D118E552F0C8A4FB58EC7C34F5BAB2D562B415C4B3F673179B8410" + "86A9B0F03ED56DBD4FA9CBB775307C9BB3045F72").HexToByteArray(); // This document signature was generated without sorting the attributes, // it ensures a compatibility fallback in CheckSignature. internal static readonly byte[] DigiCertTimeStampToken = ( "30820EC406092A864886F70D010702A0820EB530820EB1020103310F300D0609" + "608648016503040201050030818A060B2A864886F70D0109100104A07B047930" + "7702010106096086480186FD6C07013031300D06096086480165030402010500" + "04205A3B99F86CE06F5639C3ED7D0E16AE44A5CD58ABA0F6853A2AF389F91B6C" + "7D7F02104E640CDE5C761BFF32FA0ADEA58C5F56180F32303138303731373136" + "313732315A0211457A3006B9483730D09772076C4B74BDF8A0820BBB30820682" + "3082056AA003020102021009C0FC46C8044213B5598BAF284F4E41300D06092A" + "864886F70D01010B05003072310B300906035504061302555331153013060355" + "040A130C446967694365727420496E6331193017060355040B13107777772E64" + "696769636572742E636F6D3131302F0603550403132844696769436572742053" + "48413220417373757265642049442054696D657374616D70696E67204341301E" + "170D3137303130343030303030305A170D3238303131383030303030305A304C" + "310B30090603550406130255533111300F060355040A13084469676943657274" + "312A302806035504031321446967694365727420534841322054696D65737461" + "6D7020526573706F6E64657230820122300D06092A864886F70D010101050003" + "82010F003082010A02820101009E95986A343B731BA87EFCC7BE296989C76826" + "465F3D8D62738781A3A19CF0B75B24375A92D4F459D77689E4DCD527F0D566BC" + "0AEEB42B3167AC58C54A91592B451E0901D664B359EE8D664DFB235ECC100D0B" + "8A67EF52AEA00890C252F7F5A8B56E9B2C7B9DE7B53EFB78CD325018BF40B54C" + "8CBB57F4A04F11456C4242B9E5AFD6DFF4A77C0A68960FD25F2957CEFB1D32FF" + "F411A11322FB12CBEFD753D2EB97CBA2AC1B1D9D58215182C2C2DEEA2B3F2C22" + "84D043EC3B3B3F47C4F656DC453798B46B74B559AF785769C80F090278DDD853" + "C199DB60C49DEAAEAFE07E864A5CA95861A85E748A012868724EA7869DB50252" + "87706648D38EEF8124CCDCD8650203010001A382033830820334300E0603551D" + "0F0101FF040403020780300C0603551D130101FF0402300030160603551D2501" + "01FF040C300A06082B06010505070308308201BF0603551D20048201B6308201" + "B2308201A106096086480186FD6C070130820192302806082B06010505070201" + "161C68747470733A2F2F7777772E64696769636572742E636F6D2F4350533082" + "016406082B06010505070202308201561E8201520041006E0079002000750073" + "00650020006F0066002000740068006900730020004300650072007400690066" + "0069006300610074006500200063006F006E0073007400690074007500740065" + "007300200061006300630065007000740061006E006300650020006F00660020" + "007400680065002000440069006700690043006500720074002000430050002F" + "00430050005300200061006E00640020007400680065002000520065006C0079" + "0069006E0067002000500061007200740079002000410067007200650065006D" + "0065006E00740020007700680069006300680020006C0069006D006900740020" + "006C0069006100620069006C00690074007900200061006E0064002000610072" + "006500200069006E0063006F00720070006F0072006100740065006400200068" + "0065007200650069006E0020006200790020007200650066006500720065006E" + "00630065002E300B06096086480186FD6C0315301F0603551D23041830168014" + "F4B6E1201DFE29AED2E461A5B2A225B2C817356E301D0603551D0E04160414E1" + "A7324AEE0121287D54D5F207926EB4070F3D8730710603551D1F046A30683032" + "A030A02E862C687474703A2F2F63726C332E64696769636572742E636F6D2F73" + "6861322D617373757265642D74732E63726C3032A030A02E862C687474703A2F" + "2F63726C342E64696769636572742E636F6D2F736861322D617373757265642D" + "74732E63726C30818506082B0601050507010104793077302406082B06010505" + "0730018618687474703A2F2F6F6373702E64696769636572742E636F6D304F06" + "082B060105050730028643687474703A2F2F636163657274732E646967696365" + "72742E636F6D2F44696769436572745348413241737375726564494454696D65" + "7374616D70696E6743412E637274300D06092A864886F70D01010B0500038201" + "01001EF0418232AEEDF1B43513DC50C2D597AE22229D0E0EAF33D34CFD7CBF6F" + "0111A79465225CC622A1C889526B9A8C735CD95E3F32DE16604C8B36FD31990A" + "BDC184B78D1DEF8926130556F347CD475BAD84B238AF6A23B545E31E88324680" + "D2B7A69922FDC178CFF58BD80C8C0509EE44E680D56D70CC9F531E27DD2A48DE" + "DA9365AD6E65A399A7C2400E73CC584F8F4528E5BC9C88E628CE605D2D255D8B" + "732EA50D5B51DA9A4EFF50058928DAF278BBD258788D44A7AC3A009178698964" + "04D35D96DF2ABFF9A54C2C93FFE68ADD82ACF1D2B3A2869AC15589566A473FFA" + "D6339543358905785A3A69DA22B80443D36F6835367A143E45E99864860F130C" + "264A3082053130820419A00302010202100AA125D6D6321B7E41E405DA3697C2" + "15300D06092A864886F70D01010B05003065310B300906035504061302555331" + "153013060355040A130C446967694365727420496E6331193017060355040B13" + "107777772E64696769636572742E636F6D312430220603550403131B44696769" + "43657274204173737572656420494420526F6F74204341301E170D3136303130" + "373132303030305A170D3331303130373132303030305A3072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "0313284469676943657274205348413220417373757265642049442054696D65" + "7374616D70696E6720434130820122300D06092A864886F70D01010105000382" + "010F003082010A0282010100BDD032EE4BCD8F7FDDA9BA8299C539542857B623" + "4AC40E07453351107DD0F97D4D687EE7B6A0F48DB388E497BF63219098BF13BC" + "57D3C3E17E08D66A140038F72E1E3BEECCA6F63259FE5F653FE09BEBE3464706" + "1A557E0B277EC0A2F5A0E0DE223F0EFF7E95FBF3A3BA223E18AC11E4F099036D" + "3B857C09D3EE5DC89A0B54E3A809716BE0CF22100F75CF71724E0AADDF403A5C" + "B751E1A17914C64D2423305DBCEC3C606AAC2F07CCFDF0EA47D988505EFD666E" + "56612729898451E682E74650FD942A2CA7E4753EBA980F847F9F3114D6ADD5F2" + "64CB7B1E05D084197217F11706EF3DCDD64DEF0642FDA2532A4F851DC41D3CAF" + "CFDAAC10F5DDACACE956FF930203010001A38201CE308201CA301D0603551D0E" + "04160414F4B6E1201DFE29AED2E461A5B2A225B2C817356E301F0603551D2304" + "183016801445EBA2AFF492CB82312D518BA7A7219DF36DC80F30120603551D13" + "0101FF040830060101FF020100300E0603551D0F0101FF040403020186301306" + "03551D25040C300A06082B06010505070308307906082B06010505070101046D" + "306B302406082B060105050730018618687474703A2F2F6F6373702E64696769" + "636572742E636F6D304306082B060105050730028637687474703A2F2F636163" + "657274732E64696769636572742E636F6D2F4469676943657274417373757265" + "644944526F6F7443412E6372743081810603551D1F047A3078303AA038A03686" + "34687474703A2F2F63726C342E64696769636572742E636F6D2F446967694365" + "7274417373757265644944526F6F7443412E63726C303AA038A0368634687474" + "703A2F2F63726C332E64696769636572742E636F6D2F44696769436572744173" + "73757265644944526F6F7443412E63726C30500603551D20044930473038060A" + "6086480186FD6C000204302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F435053300B06096086480186FD" + "6C0701300D06092A864886F70D01010B05000382010100719512E951875669CD" + "EFDDDA7CAA637AB378CF06374084EF4B84BFCACF0302FDC5A7C30E20422CAF77" + "F32B1F0C215A2AB705341D6AAE99F827A266BF09AA60DF76A43A930FF8B2D1D8" + "7C1962E85E82251EC4BA1C7B2C21E2D65B2C1435430468B2DB7502E072C798D6" + "3C64E51F4810185F8938614D62462487638C91522CAF2989E5781FD60B14A580" + "D7124770B375D59385937EB69267FB536189A8F56B96C0F458690D7CC801B1B9" + "2875B7996385228C61CA79947E59FC8C0FE36FB50126B66CA5EE875121E45860" + "9BBA0C2D2B6DA2C47EBBC4252B4702087C49AE13B6E17C424228C61856CF4134" + "B6665DB6747BF55633222F2236B24BA24A95D8F5A68E523182024D3082024902" + "01013081863072310B300906035504061302555331153013060355040A130C44" + "6967694365727420496E6331193017060355040B13107777772E646967696365" + "72742E636F6D3131302F06035504031328446967694365727420534841322041" + "7373757265642049442054696D657374616D70696E67204341021009C0FC46C8" + "044213B5598BAF284F4E41300D06096086480165030402010500A08198301A06" + "092A864886F70D010903310D060B2A864886F70D0109100104301C06092A8648" + "86F70D010905310F170D3138303731373136313732315A302F06092A864886F7" + "0D01090431220420E66606A88254749C2E5575722F93AA67174FDDDB7703B7E6" + "FAD6B3FE000F3DE2302B060B2A864886F70D010910020C311C301A3018301604" + "14400191475C98891DEBA104AF47091B5EB6D4CBCB300D06092A864886F70D01" + "01010500048201005AF349DE87550378C702ED31AE6DD6D50E6B24298DB2DFD6" + "1396C6FA3E465FE7323ACD65AE157C06BCB993551F33702C6D1F6951AECDE74A" + "969E41A8F0F95188780F990EAF6B129633CDE42FF149501BFAC05C516B6DA9EF" + "E492488013928BA801D66C32EFE7EEDFF22DC96DDA4783674EEE8231E7A3AD8A" + "98A506DABB68D6337D7FFDBD2F7112AF2FEE718CF6E7E5544DB7B4BDCD8191EB" + "C73D568EE4D2A30B8478D676910E3B4EB868010AAF22400198D0593F987C86A9" + "101711B9C6AC5C5776923C699E772B07864755C1AC50F387655C4E67DB356207" + "76252A2F4605B97BD3C299D1CD79929273BB86E7DF9E113C92802380ED6D4041" + "9DA4C01214D4FA24").HexToByteArray(); internal static readonly byte[] RsaPkcs1Sha256WithRsa = ( "3082071B06092A864886F70D010702A082070C30820708020101310F300D0609" + "6086480165030402010500301606092A864886F70D010701A009040700010203" + "040506A08205223082051E30820406A00302010202100D85090F3FACFF0A9008" + "A12A9FB00A54300D06092A864886F70D01010B05003072310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D3131302F060355040313" + "2844696769436572742053484132204173737572656420494420436F64652053" + "69676E696E67204341301E170D3138303832393030303030305A170D31393039" + "30333132303030305A305B310B3009060355040613025553310B300906035504" + "0813025641311330110603550407130A416C6578616E64726961311430120603" + "55040A130B4B6576696E204A6F6E6573311430120603550403130B4B6576696E" + "204A6F6E657330820122300D06092A864886F70D01010105000382010F003082" + "010A0282010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D299" + "1C962D0A22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A35" + "80CC96A11F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F77" + "9CB4979544514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456" + "A8497758D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB" + "0780CD258F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214" + "533B2A47977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200" + "943EFB7D0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A" + "8C461760E6A4F30203010001A38201C5308201C1301F0603551D230418301680" + "145AC4B97B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E04160414" + "33795EB2D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF0404" + "0302078030130603551D25040C300A06082B0601050507030330770603551D1F" + "0470306E3035A033A031862F687474703A2F2F63726C332E6469676963657274" + "2E636F6D2F736861322D617373757265642D63732D67312E63726C3035A033A0" + "31862F687474703A2F2F63726C342E64696769636572742E636F6D2F73686132" + "2D617373757265642D63732D67312E63726C304C0603551D2004453043303706" + "096086480186FD6C0301302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F4350533008060667810C010401" + "30818406082B0601050507010104783076302406082B06010505073001861868" + "7474703A2F2F6F6373702E64696769636572742E636F6D304E06082B06010505" + "0730028642687474703A2F2F636163657274732E64696769636572742E636F6D" + "2F446967694365727453484132417373757265644944436F64655369676E696E" + "6743412E637274300C0603551D130101FF04023000300D06092A864886F70D01" + "010B0500038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD9" + "9BFC9B62E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A7" + "3041686C326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD50414" + "79BDBB6B93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE" + "9934817036338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D9" + "50EE0235B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02" + "A75F2D7EC07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660B" + "B452E35922D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16" + "819DC990F5F45CDE21318201B2308201AE0201013081863072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "03132844696769436572742053484132204173737572656420494420436F6465" + "205369676E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300D06" + "096086480165030402010500300D06092A864886F70D01010B050004820100E2" + "980C5A30EC00729D1CFA826D7A65B43FF6806B5E0ABA23A78E4F1CAA3F6436EF" + "00941C6947A9B8F20D0757B5346CF640AA217F7361BEEFF2BC997FB1D3597BF3" + "D7457BD4A94062FB03660F9D86710BE2FC99876A848251F4965E1B16192714C8" + "F9788C09CCDE83603ADC919297BA496E921B95F3BD9554A873E09912640FCFAA" + "D9DD1441D1851E637031D390C038223AE64B048E806462DDBAC98C156BE2EE47" + "2B78166BDB1612848B535ADC3F0E7BE52991A17F48AFDCCC1698A236BA338930" + "50EBAAC4460DAA35185C16670F597E0E6E0CB0AA83F51AAEF452F3367DD9350A" + "8A49A5A8F79DF8E921303AB5D6646A482F0F59D9980310E1AE3EE8D77CB857").HexToByteArray(); internal static readonly byte[] RsaPkcs1SignedSha1DeclaredSha256WithRsa = ( "3082071306092A864886F70D010702A082070430820700020101310B30090605" + "2B0E03021A0500301606092A864886F70D010701A009040700010203040506A0" + "8205223082051E30820406A00302010202100D85090F3FACFF0A9008A12A9FB0" + "0A54300D06092A864886F70D01010B05003072310B3009060355040613025553" + "31153013060355040A130C446967694365727420496E6331193017060355040B" + "13107777772E64696769636572742E636F6D3131302F06035504031328446967" + "69436572742053484132204173737572656420494420436F6465205369676E69" + "6E67204341301E170D3138303832393030303030305A170D3139303930333132" + "303030305A305B310B3009060355040613025553310B30090603550408130256" + "41311330110603550407130A416C6578616E6472696131143012060355040A13" + "0B4B6576696E204A6F6E6573311430120603550403130B4B6576696E204A6F6E" + "657330820122300D06092A864886F70D01010105000382010F003082010A0282" + "010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D2991C962D0A" + "22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A3580CC96A1" + "1F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F779CB49795" + "44514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456A8497758" + "D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB0780CD25" + "8F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214533B2A47" + "977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200943EFB7D" + "0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A8C461760" + "E6A4F30203010001A38201C5308201C1301F0603551D230418301680145AC4B9" + "7B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E0416041433795EB2" + "D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF040403020780" + "30130603551D25040C300A06082B0601050507030330770603551D1F0470306E" + "3035A033A031862F687474703A2F2F63726C332E64696769636572742E636F6D" + "2F736861322D617373757265642D63732D67312E63726C3035A033A031862F68" + "7474703A2F2F63726C342E64696769636572742E636F6D2F736861322D617373" + "757265642D63732D67312E63726C304C0603551D200445304330370609608648" + "0186FD6C0301302A302806082B06010505070201161C68747470733A2F2F7777" + "772E64696769636572742E636F6D2F4350533008060667810C01040130818406" + "082B0601050507010104783076302406082B060105050730018618687474703A" + "2F2F6F6373702E64696769636572742E636F6D304E06082B0601050507300286" + "42687474703A2F2F636163657274732E64696769636572742E636F6D2F446967" + "694365727453484132417373757265644944436F64655369676E696E6743412E" + "637274300C0603551D130101FF04023000300D06092A864886F70D01010B0500" + "038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD99BFC9B62" + "E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A73041686C" + "326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD5041479BDBB6B" + "93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE99348170" + "36338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D950EE0235" + "B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02A75F2D7E" + "C07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660BB452E359" + "22D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16819DC990" + "F5F45CDE21318201AE308201AA0201013081863072310B300906035504061302" + "555331153013060355040A130C446967694365727420496E6331193017060355" + "040B13107777772E64696769636572742E636F6D3131302F0603550403132844" + "696769436572742053484132204173737572656420494420436F646520536967" + "6E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300906052B0E03" + "021A0500300D06092A864886F70D01010B050004820100EAEEB9E1D4BFB979F1" + "A1C00EE1EC45069366CDD7489A0671F6DC9E3353F7FAEDCE7B87BD467ADFC850" + "877414966E7EB39C33367ABB03B3AA8BB1438BD952484CB807451499CAE8FDC9" + "527304D459D82CA039087560B5D3D0EA03DEA1B9472EFC44CBB55DD9A3C6A5C8" + "DFFD0786D5523F22604B412D6FC5A15E2D6285D7AB76EC216DE859391D129D51" + "6C27348EDAE7DC43335D12242D939CAF05385A118235F5B1E342EC034E70F655" + "793FF2FE037558EC2F45BD2683704F8FFD49B910131F4F2804B4282C5C36E41C" + "9E4E4F93446D44E3106760D265C5C7A849CF03426ACCB294712E51313D5414A7" + "8227AB79F6B18E2A2054E3FA781DAA2998EB33EDDCDA80").HexToByteArray(); internal static readonly byte[] IndefiniteLengthContentDocument = ( "3082265206092A864886F70D010702A08226433082263F020103310F300D0609" + "6086480165030402010500306806092A864886F70D010701A05B248004555665" + "7273696F6E3A310A0A322E31362E3834302E312E3130312E332E342E322E312D" + "486173683A49413134467074344A365A504F5A47506275364A676A524B696930" + "664E584A365A6B78746F744B665733383D0A0A0000A082106D308203C5308202" + "ADA003020102021002AC5C266A0B409B8F0B79F2AE462577300D06092A864886" + "F70D0101050500306C310B300906035504061302555331153013060355040A13" + "0C446967694365727420496E6331193017060355040B13107777772E64696769" + "636572742E636F6D312B30290603550403132244696769436572742048696768" + "204173737572616E636520455620526F6F74204341301E170D30363131313030" + "30303030305A170D3331313131303030303030305A306C310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D312B3029060355040313" + "2244696769436572742048696768204173737572616E636520455620526F6F74" + "20434130820122300D06092A864886F70D01010105000382010F003082010A02" + "82010100C6CCE573E6FBD4BBE52D2D32A6DFE5813FC9CD2549B6712AC3D59434" + "67A20A1CB05F69A640B1C4B7B28FD098A4A941593AD3DC94D63CDB7438A44ACC" + "4D2582F74AA5531238EEF3496D71917E63B6ABA65FC3A484F84F6251BEF8C5EC" + "DB3892E306E508910CC4284155FBCB5A89157E71E835BF4D72093DBE3A38505B" + "77311B8DB3C724459AA7AC6D00145A04B7BA13EB510A984141224E6561878141" + "50A6795C89DE194A57D52EE65D1C532C7E98CD1A0616A46873D03404135CA171" + "D35A7C55DB5E64E13787305604E511B4298012F1793988A202117C2766B788B7" + "78F2CA0AA838AB0A64C2BF665D9584C1A1251E875D1A500B2012CC41BB6E0B51" + "38B84BCB0203010001A3633061300E0603551D0F0101FF040403020186300F06" + "03551D130101FF040530030101FF301D0603551D0E04160414B13EC36903F8BF" + "4701D498261A0802EF63642BC3301F0603551D23041830168014B13EC36903F8" + "BF4701D498261A0802EF63642BC3300D06092A864886F70D0101050500038201" + "01001C1A0697DCD79C9F3C886606085721DB2147F82A67AABF183276401057C1" + "8AF37AD911658E35FA9EFC45B59ED94C314BB891E8432C8EB378CEDBE3537971" + "D6E5219401DA55879A2464F68A66CCDE9C37CDA834B1699B23C89E78222B7043" + "E35547316119EF58C5852F4E30F6A0311623C8E7E2651633CBBF1A1BA03DF8CA" + "5E8B318B6008892D0C065C52B7C4F90A98D1155F9F12BE7C366338BD44A47FE4" + "262B0AC497690DE98CE2C01057B8C876129155F24869D8BC2A025B0F44D42031" + "DBF4BA70265D90609EBC4B17092FB4CB1E4368C90727C1D25CF7EA21B968129C" + "3C9CBF9EFC805C9B63CDEC47AA252767A037F300827D54D7A9F8E92E13A377E8" + "1F4A308205E0308204C8A0030201020210070C57D60A8AB12F9B5F2D5CD2EDA5" + "04300D06092A864886F70D01010B0500306C310B300906035504061302555331" + "153013060355040A130C446967694365727420496E6331193017060355040B13" + "107777772E64696769636572742E636F6D312B30290603550403132244696769" + "4365727420455620436F6465205369676E696E6720434120285348413229301E" + "170D3137303531363030303030305A170D3230303532303132303030305A3081" + "F6311D301B060355040F0C1450726976617465204F7267616E697A6174696F6E" + "31133011060B2B0601040182373C0201031302555331193017060B2B06010401" + "82373C02010213084E657720596F726B3110300E060355040513073531303136" + "3333311E301C06035504091315353435205720456E6420417665204170742031" + "3645310E300C060355041113053130303234310B300906035504061302555331" + "0B3009060355040813024E593111300F060355040713084E657720596F726B31" + "1A3018060355040A13114F72656E204E6F766F746E792C204C4C43311A301806" + "0355040313114F72656E204E6F766F746E792C204C4C4330820122300D06092A" + "864886F70D01010105000382010F003082010A0282010100E253870D0B9B81C7" + "B2449CBD7BA9837EDFE23C79F54CE2C1BFA0F5C92C261AAC4E3D40CD890F8046" + "289C7BCF0525BC0D2E193C28E7AD3ABF87FD35CAB9CBC869CEF8964B80DD77CE" + "E209EFCC42A465FDC1338A478DAA80254D17679548ED78528A13632B66FD0531" + "555E04BCAF14A67AD266CECB03346FAB4757C1AC120FE34C15E4B5BBBDE3E601" + "EF9A8BBE6EE1802EF18E852233130B9DE0995FAACC869D414380B478E5E343AB" + "B2C18DDEC8170EB601301EC178B6CD66FF1E10D81637CB609FECCFBF91666090" + "A30F0D95B3BC204FDFC6314913C20091DBE60DEC88488C6B48E66E71247E11D2" + "7662A2A7106806BE8B95041F46D1375688F0B3C0BE805C750203010001A38201" + "F1308201ED301F0603551D230418301680148FE87EF06D326A000523C770976A" + "3A90FF6BEAD4301D0603551D0E0416041451B49AE070DEBDAE12B71C87F99F4E" + "0E495B30A1302E0603551D1104273025A02306082B06010505070803A0173015" + "0C1355532D4E455720594F524B2D35313031363333300E0603551D0F0101FF04" + "040302078030130603551D25040C300A06082B06010505070303307B0603551D" + "1F047430723037A035A0338631687474703A2F2F63726C332E64696769636572" + "742E636F6D2F4556436F64655369676E696E67534841322D67312E63726C3037" + "A035A0338631687474703A2F2F63726C342E64696769636572742E636F6D2F45" + "56436F64655369676E696E67534841322D67312E63726C304B0603551D200444" + "3042303706096086480186FD6C0302302A302806082B06010505070201161C68" + "747470733A2F2F7777772E64696769636572742E636F6D2F4350533007060567" + "810C0103307E06082B0601050507010104723070302406082B06010505073001" + "8618687474703A2F2F6F6373702E64696769636572742E636F6D304806082B06" + "010505073002863C687474703A2F2F636163657274732E64696769636572742E" + "636F6D2F44696769436572744556436F64655369676E696E6743412D53484132" + "2E637274300C0603551D130101FF04023000300D06092A864886F70D01010B05" + "0003820101000481103296C95A10AE7055ECB980F0A5910F756DB48704BB078C" + "B53E8859EDDF906E4B6207301C8BAE9CE39BE70D6D897EA2F32BD05270B8DC1E" + "44ADB0ECDCCAC7A858295E81E030B9A5CF571CD81536EBE36E4D87A9DD6E0C42" + "3B5E6F3A249C90AFB1418925F806C6B91346EBFDC61C1D392FA0861AE7B5ADF8" + "E0E213BBCCA53F826DA3B7514A80A7148968DC4855F584DBB2AB6E99569C6C89" + "333CFEEA0914F3C77A04E5EE44D7A27370F34FDFF4753762B62D55809C43FD63" + "F37BBB0239CB1B25F1F7C1932D0885F526CC87F589ED40BCEFBBDDD76620AA2D" + "5D373B9EE51F9FD02905EEC71DD5F5419010E5D061643A6A04211FA3165943AE" + "D0FF1FB58D23308206BC308205A4A003020102021003F1B4E15F3A82F1149678" + "B3D7D8475C300D06092A864886F70D01010B0500306C310B3009060355040613" + "02555331153013060355040A130C446967694365727420496E63311930170603" + "55040B13107777772E64696769636572742E636F6D312B302906035504031322" + "44696769436572742048696768204173737572616E636520455620526F6F7420" + "4341301E170D3132303431383132303030305A170D3237303431383132303030" + "305A306C310B300906035504061302555331153013060355040A130C44696769" + "4365727420496E6331193017060355040B13107777772E64696769636572742E" + "636F6D312B302906035504031322446967694365727420455620436F64652053" + "69676E696E672043412028534841322930820122300D06092A864886F70D0101" + "0105000382010F003082010A0282010100A753FA0FB2B513F164CF8480FCAE80" + "35D1B6D7C7A32CAC1A2CACF184AC3A35123A9291BA57E4C4C9F32FA8483CB7D6" + "6EDC9722BA517961AF432F0DB79BB44931AE44583EA4A196A7874F237EC36C65" + "2490553EA1CA237CC542E9C47A62459B7DDE6374CB9E6325F8849A9AAD454FAE" + "7D1FC813CB759BC9E1E18AF80B0C98F4CA3ED045AA7A1EA558933634BE2B2E2B" + "315866B432109F9DF052A1EFE83ED376F2405ADCFA6A3D1B4BAD76B08C5CEE36" + "BA83EA30A84CDEF10B2A584188AE0089AB03D11682202276EB5E54381262E1D2" + "7024DBED1F70D26409802DE2B69DCE1FF2BB21F36CDBD8B3197B8A509FEFEC36" + "0A5C9AB74AD308A03979FDDDBF3D3A09250203010001A3820358308203543012" + "0603551D130101FF040830060101FF020100300E0603551D0F0101FF04040302" + "018630130603551D25040C300A06082B06010505070303307F06082B06010505" + "07010104733071302406082B060105050730018618687474703A2F2F6F637370" + "2E64696769636572742E636F6D304906082B06010505073002863D687474703A" + "2F2F636163657274732E64696769636572742E636F6D2F446967694365727448" + "6967684173737572616E63654556526F6F7443412E63727430818F0603551D1F" + "0481873081843040A03EA03C863A687474703A2F2F63726C332E646967696365" + "72742E636F6D2F4469676943657274486967684173737572616E63654556526F" + "6F7443412E63726C3040A03EA03C863A687474703A2F2F63726C342E64696769" + "636572742E636F6D2F4469676943657274486967684173737572616E63654556" + "526F6F7443412E63726C308201C40603551D20048201BB308201B7308201B306" + "096086480186FD6C0302308201A4303A06082B06010505070201162E68747470" + "3A2F2F7777772E64696769636572742E636F6D2F73736C2D6370732D7265706F" + "7369746F72792E68746D3082016406082B06010505070202308201561E820152" + "0041006E007900200075007300650020006F0066002000740068006900730020" + "0043006500720074006900660069006300610074006500200063006F006E0073" + "007400690074007500740065007300200061006300630065007000740061006E" + "006300650020006F006600200074006800650020004400690067006900430065" + "00720074002000430050002F00430050005300200061006E0064002000740068" + "0065002000520065006C00790069006E00670020005000610072007400790020" + "00410067007200650065006D0065006E00740020007700680069006300680020" + "006C0069006D006900740020006C0069006100620069006C0069007400790020" + "0061006E0064002000610072006500200069006E0063006F00720070006F0072" + "0061007400650064002000680065007200650069006E00200062007900200072" + "00650066006500720065006E00630065002E301D0603551D0E041604148FE87E" + "F06D326A000523C770976A3A90FF6BEAD4301F0603551D23041830168014B13E" + "C36903F8BF4701D498261A0802EF63642BC3300D06092A864886F70D01010B05" + "00038201010019334A0C813337DBAD36C9E4C93ABBB51B2E7AA2E2F44342179E" + "BF4EA14DE1B1DBE981DD9F01F2E488D5E9FE09FD21C1EC5D80D2F0D6C143C2FE" + "772BDBF9D79133CE6CD5B2193BE62ED6C9934F88408ECDE1F57EF10FC6595672" + "E8EB6A41BD1CD546D57C49CA663815C1BFE091707787DCC98D31C90C29A233ED" + "8DE287CD898D3F1BFFD5E01A978B7CDA6DFBA8C6B23A666B7B01B3CDD8A634EC" + "1201AB9558A5C45357A860E6E70212A0B92364A24DBB7C81256421BECFEE4218" + "4397BBA53706AF4DFF26A54D614BEC4641B865CEB8799E08960B818C8A3B8FC7" + "998CA32A6E986D5E61C696B78AB9612D93B8EB0E0443D7F5FEA6F062D4996AA5" + "C1C1F06494803182154C30821548020103801451B49AE070DEBDAE12B71C87F9" + "9F4E0E495B30A1300D06096086480165030402010500A082015B301806092A86" + "4886F70D010903310B06092A864886F70D010701301C06092A864886F70D0109" + "05310F170D3138303632333139303131385A301E060B2A864886F70D01091002" + "10310F300D060B2A864886F70D0109100601302F06092A864886F70D01090431" + "220420F67BA3F4A22E1F7D27A0FF8940FD931FF3D5AAA6BA99B92B6ABA6B63B3" + "93E5DB3081CF060B2A864886F70D010910022F3181BF3081BC3081B93081B630" + "0B0609608648016503040201042017B677DFF2A3A70C935DCABCEAF6595183D6" + "2F8972E77AC688369EDE50D2B2563081843070A46E306C310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D312B3029060355040313" + "22446967694365727420455620436F6465205369676E696E6720434120285348" + "4132290210070C57D60A8AB12F9B5F2D5CD2EDA504300D06092A864886F70D01" + "010B050004820100AA697F9C5F4517BB139B8A7FAEC1BBBBAB53381B4F649EE1" + "9A35E9F5D47ABE0C2FCF881C6DC176E52F8191A43486630939264F42464B865D" + "B46979EF4996CD081CF615F194BBC9F539609000F2A2A6CBD9F88E497F4B907F" + "AEE95B55E73921CCAF89287FDC3F18FA1DB5D13BA7932A0559A9C4194E937611" + "003228D161B2EE40FD5C8BDB0463F90DFC5B0D0ABBBDFE7918BDDA2F5658F8E2" + "BA47362DC677CD8785D0AD76B73CC544411B7B168E471A449FDF8BD356719D56" + "C67E69F81F9534A2DE9D1CDD22717D3D3F84D6CB10C7FC2651945A000A2B7696" + "6A69CBE5D37B513E67E945B29CE2CC09CB2E4C8CDBAF105BCFE0927D14B8CEEF" + "92851AF4476053DCA18212AA308212A6060B2A864886F70D010910020E318212" + "953082129106092A864886F70D010702A08212823082127E020103310F300D06" + "09608648016503040201050030819C060B2A864886F70D0109100104A0818C04" + "818930818602010106096086480186FD6C07013031300D060960864801650304" + "0201050004208A42931DB9A7486014564D4922BE742D01B6ADF152B1421227B7" + "D6FBB943EEC202105B0A3E465D2092EB05B245401BC2594E180F323031383036" + "32333139303132305A02205718795810783FECCC7143D821251F44AEE16A57A1" + "CA24C1B2EF1796CB777AD3A0820F76308203B73082029FA00302010202100CE7" + "E0E517D846FE8FE560FC1BF03039300D06092A864886F70D0101050500306531" + "0B300906035504061302555331153013060355040A130C446967694365727420" + "496E6331193017060355040B13107777772E64696769636572742E636F6D3124" + "30220603550403131B4469676943657274204173737572656420494420526F6F" + "74204341301E170D3036313131303030303030305A170D333131313130303030" + "3030305A3065310B300906035504061302555331153013060355040A130C4469" + "67694365727420496E6331193017060355040B13107777772E64696769636572" + "742E636F6D312430220603550403131B44696769436572742041737375726564" + "20494420526F6F7420434130820122300D06092A864886F70D01010105000382" + "010F003082010A0282010100AD0E15CEE443805CB187F3B760F97112A5AEDC26" + "9488AAF4CEF520392858600CF880DAA9159532613CB5B128848A8ADC9F0A0C83" + "177A8F90AC8AE779535C31842AF60F98323676CCDEDD3CA8A2EF6AFB21F25261" + "DF9F20D71FE2B1D9FE1864D2125B5FF9581835BC47CDA136F96B7FD4B0383EC1" + "1BC38C33D9D82F18FE280FB3A783D6C36E44C061359616FE599C8B766DD7F1A2" + "4B0D2BFF0B72DA9E60D08E9035C678558720A1CFE56D0AC8497C3198336C22E9" + "87D0325AA2BA138211ED39179D993A72A1E6FAA4D9D5173175AE857D22AE3F01" + "4686F62879C8B1DAE45717C47E1C0EB0B492A656B3BDB297EDAAA7F0B7C5A83F" + "9516D0FFA196EB085F18774F0203010001A3633061300E0603551D0F0101FF04" + "0403020186300F0603551D130101FF040530030101FF301D0603551D0E041604" + "1445EBA2AFF492CB82312D518BA7A7219DF36DC80F301F0603551D2304183016" + "801445EBA2AFF492CB82312D518BA7A7219DF36DC80F300D06092A864886F70D" + "01010505000382010100A20EBCDFE2EDF0E372737A6494BFF77266D832E44275" + "62AE87EBF2D5D9DE56B39FCCCE1428B90D97605C124C58E4D33D834945589735" + "691AA847EA56C679AB12D8678184DF7F093C94E6B8262C20BD3DB32889F75FFF" + "22E297841FE965EF87E0DFC16749B35DEBB2092AEB26ED78BE7D3F2BF3B72635" + "6D5F8901B6495B9F01059BAB3D25C1CCB67FC2F16F86C6FA6468EB812D94EB42" + "B7FA8C1EDD62F1BE5067B76CBDF3F11F6B0C3607167F377CA95B6D7AF1124660" + "83D72704BE4BCE97BEC3672A6811DF80E70C3366BF130D146EF37F1F63101EFA" + "8D1B256D6C8FA5B76101B1D2A326A110719DADE2C3F9C39951B72B0708CE2EE6" + "50B2A7FA0A452FA2F0F23082053130820419A00302010202100AA125D6D6321B" + "7E41E405DA3697C215300D06092A864886F70D01010B05003065310B30090603" + "5504061302555331153013060355040A130C446967694365727420496E633119" + "3017060355040B13107777772E64696769636572742E636F6D31243022060355" + "0403131B4469676943657274204173737572656420494420526F6F7420434130" + "1E170D3136303130373132303030305A170D3331303130373132303030305A30" + "72310B300906035504061302555331153013060355040A130C44696769436572" + "7420496E6331193017060355040B13107777772E64696769636572742E636F6D" + "3131302F06035504031328446967694365727420534841322041737375726564" + "2049442054696D657374616D70696E6720434130820122300D06092A864886F7" + "0D01010105000382010F003082010A0282010100BDD032EE4BCD8F7FDDA9BA82" + "99C539542857B6234AC40E07453351107DD0F97D4D687EE7B6A0F48DB388E497" + "BF63219098BF13BC57D3C3E17E08D66A140038F72E1E3BEECCA6F63259FE5F65" + "3FE09BEBE34647061A557E0B277EC0A2F5A0E0DE223F0EFF7E95FBF3A3BA223E" + "18AC11E4F099036D3B857C09D3EE5DC89A0B54E3A809716BE0CF22100F75CF71" + "724E0AADDF403A5CB751E1A17914C64D2423305DBCEC3C606AAC2F07CCFDF0EA" + "47D988505EFD666E56612729898451E682E74650FD942A2CA7E4753EBA980F84" + "7F9F3114D6ADD5F264CB7B1E05D084197217F11706EF3DCDD64DEF0642FDA253" + "2A4F851DC41D3CAFCFDAAC10F5DDACACE956FF930203010001A38201CE308201" + "CA301D0603551D0E04160414F4B6E1201DFE29AED2E461A5B2A225B2C817356E" + "301F0603551D2304183016801445EBA2AFF492CB82312D518BA7A7219DF36DC8" + "0F30120603551D130101FF040830060101FF020100300E0603551D0F0101FF04" + "040302018630130603551D25040C300A06082B06010505070308307906082B06" + "010505070101046D306B302406082B060105050730018618687474703A2F2F6F" + "6373702E64696769636572742E636F6D304306082B0601050507300286376874" + "74703A2F2F636163657274732E64696769636572742E636F6D2F446967694365" + "7274417373757265644944526F6F7443412E6372743081810603551D1F047A30" + "78303AA038A0368634687474703A2F2F63726C342E64696769636572742E636F" + "6D2F4469676943657274417373757265644944526F6F7443412E63726C303AA0" + "38A0368634687474703A2F2F63726C332E64696769636572742E636F6D2F4469" + "676943657274417373757265644944526F6F7443412E63726C30500603551D20" + "044930473038060A6086480186FD6C000204302A302806082B06010505070201" + "161C68747470733A2F2F7777772E64696769636572742E636F6D2F435053300B" + "06096086480186FD6C0701300D06092A864886F70D01010B0500038201010071" + "9512E951875669CDEFDDDA7CAA637AB378CF06374084EF4B84BFCACF0302FDC5" + "A7C30E20422CAF77F32B1F0C215A2AB705341D6AAE99F827A266BF09AA60DF76" + "A43A930FF8B2D1D87C1962E85E82251EC4BA1C7B2C21E2D65B2C1435430468B2" + "DB7502E072C798D63C64E51F4810185F8938614D62462487638C91522CAF2989" + "E5781FD60B14A580D7124770B375D59385937EB69267FB536189A8F56B96C0F4" + "58690D7CC801B1B92875B7996385228C61CA79947E59FC8C0FE36FB50126B66C" + "A5EE875121E458609BBA0C2D2B6DA2C47EBBC4252B4702087C49AE13B6E17C42" + "4228C61856CF4134B6665DB6747BF55633222F2236B24BA24A95D8F5A68E5230" + "8206823082056AA003020102021009C0FC46C8044213B5598BAF284F4E41300D" + "06092A864886F70D01010B05003072310B300906035504061302555331153013" + "060355040A130C446967694365727420496E6331193017060355040B13107777" + "772E64696769636572742E636F6D3131302F0603550403132844696769436572" + "74205348413220417373757265642049442054696D657374616D70696E672043" + "41301E170D3137303130343030303030305A170D323830313138303030303030" + "5A304C310B30090603550406130255533111300F060355040A13084469676943" + "657274312A302806035504031321446967694365727420534841322054696D65" + "7374616D7020526573706F6E64657230820122300D06092A864886F70D010101" + "05000382010F003082010A02820101009E95986A343B731BA87EFCC7BE296989" + "C76826465F3D8D62738781A3A19CF0B75B24375A92D4F459D77689E4DCD527F0" + "D566BC0AEEB42B3167AC58C54A91592B451E0901D664B359EE8D664DFB235ECC" + "100D0B8A67EF52AEA00890C252F7F5A8B56E9B2C7B9DE7B53EFB78CD325018BF" + "40B54C8CBB57F4A04F11456C4242B9E5AFD6DFF4A77C0A68960FD25F2957CEFB" + "1D32FFF411A11322FB12CBEFD753D2EB97CBA2AC1B1D9D58215182C2C2DEEA2B" + "3F2C2284D043EC3B3B3F47C4F656DC453798B46B74B559AF785769C80F090278" + "DDD853C199DB60C49DEAAEAFE07E864A5CA95861A85E748A012868724EA7869D" + "B5025287706648D38EEF8124CCDCD8650203010001A382033830820334300E06" + "03551D0F0101FF040403020780300C0603551D130101FF040230003016060355" + "1D250101FF040C300A06082B06010505070308308201BF0603551D20048201B6" + "308201B2308201A106096086480186FD6C070130820192302806082B06010505" + "070201161C68747470733A2F2F7777772E64696769636572742E636F6D2F4350" + "533082016406082B06010505070202308201561E8201520041006E0079002000" + "75007300650020006F0066002000740068006900730020004300650072007400" + "6900660069006300610074006500200063006F006E0073007400690074007500" + "740065007300200061006300630065007000740061006E006300650020006F00" + "6600200074006800650020004400690067006900430065007200740020004300" + "50002F00430050005300200061006E0064002000740068006500200052006500" + "6C00790069006E00670020005000610072007400790020004100670072006500" + "65006D0065006E00740020007700680069006300680020006C0069006D006900" + "740020006C0069006100620069006C00690074007900200061006E0064002000" + "610072006500200069006E0063006F00720070006F0072006100740065006400" + "2000680065007200650069006E00200062007900200072006500660065007200" + "65006E00630065002E300B06096086480186FD6C0315301F0603551D23041830" + "168014F4B6E1201DFE29AED2E461A5B2A225B2C817356E301D0603551D0E0416" + "0414E1A7324AEE0121287D54D5F207926EB4070F3D8730710603551D1F046A30" + "683032A030A02E862C687474703A2F2F63726C332E64696769636572742E636F" + "6D2F736861322D617373757265642D74732E63726C3032A030A02E862C687474" + "703A2F2F63726C342E64696769636572742E636F6D2F736861322D6173737572" + "65642D74732E63726C30818506082B0601050507010104793077302406082B06" + "0105050730018618687474703A2F2F6F6373702E64696769636572742E636F6D" + "304F06082B060105050730028643687474703A2F2F636163657274732E646967" + "69636572742E636F6D2F44696769436572745348413241737375726564494454" + "696D657374616D70696E6743412E637274300D06092A864886F70D01010B0500" + "03820101001EF0418232AEEDF1B43513DC50C2D597AE22229D0E0EAF33D34CFD" + "7CBF6F0111A79465225CC622A1C889526B9A8C735CD95E3F32DE16604C8B36FD" + "31990ABDC184B78D1DEF8926130556F347CD475BAD84B238AF6A23B545E31E88" + "324680D2B7A69922FDC178CFF58BD80C8C0509EE44E680D56D70CC9F531E27DD" + "2A48DEDA9365AD6E65A399A7C2400E73CC584F8F4528E5BC9C88E628CE605D2D" + "255D8B732EA50D5B51DA9A4EFF50058928DAF278BBD258788D44A7AC3A009178" + "69896404D35D96DF2ABFF9A54C2C93FFE68ADD82ACF1D2B3A2869AC15589566A" + "473FFAD6339543358905785A3A69DA22B80443D36F6835367A143E45E9986486" + "0F130C264A3182024D308202490201013081863072310B300906035504061302" + "555331153013060355040A130C446967694365727420496E6331193017060355" + "040B13107777772E64696769636572742E636F6D3131302F0603550403132844" + "69676943657274205348413220417373757265642049442054696D657374616D" + "70696E67204341021009C0FC46C8044213B5598BAF284F4E41300D0609608648" + "0165030402010500A08198301A06092A864886F70D010903310D060B2A864886" + "F70D0109100104301C06092A864886F70D010905310F170D3138303632333139" + "303132305A302F06092A864886F70D01090431220420DAE824F466CED9AD07AC" + "66897D7489E25E678911AA3E85BBBAB76F93DF77FFCA302B060B2A864886F70D" + "010910020C311C301A301830160414400191475C98891DEBA104AF47091B5EB6" + "D4CBCB300D06092A864886F70D010101050004820100451DCB791B5E31865B9F" + "697B8A790C4DB1867261B10EDCEB65F8AD03350D8D25D89012E8A9C46D3DA436" + "04F222C645A8C4C7658D0C5C31A473A09FE314D049A886001CAC3C2C5B106BD7" + "1D02785A3BD02E4171E70A9AA1C7EC5BDB7D1B5A2F3A5F6EF92EE3296CB8FC52" + "D7ABF3ADB91F2BF30A2D0DE9713CFE5CF203B6D3F0F51897DCB075E8AAB8CB96" + "1F9505656CA73C8935E29A71C09BE3AA0BA1326FA295B6686771D6431BB2DAB3" + "8DECE164DE7487945C09DC0BF525086256C4D22CC71C70DD886BDD2EEF609631" + "771EF1E49426819679F9C080815B27AD93090D56DBF566D585693B27B5FDA70B" + "18401534B87B522B7B0AA98E3F31DFDD64FDA0DE9471").HexToByteArray(); internal static readonly byte[] MD5WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D010104301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D010104300B06092A864886F70D010101048201005C" + "5174F8B1C6EF0A555CDBA272DF76BB798CB4170D361E4238C3A260748598B7C9" + "561605640BCAFC23C66C45A99E54A25854C5379CE2D26DECABDB6C6AE1FDC79E" + "1BBFA5833640BD8C96AF66CD3379B83B8A53660FB2FA6C1BD8ACE986741FF73A" + "14C437B7AF8617854A8F9484D84E684255EB7C37CBCA51BBC81D8D7E9A6287A0" + "409AC5AE0FA7D6411F7B25BDFC49EC91BD664630741ECCB0C6F02FFC5B9256A3" + "8AC30FDB4A7C2253E372858DF5D2333BBE29CEBCE24A0FABB9E62B0E631CAB2F" + "7A9137FE16A0448BE17ACF55F630CD6A522D94A42D6AB79C82C9AAB0DE7284C5" + "F8F16BF845A7619AE6DEE8016D42EA13189B51E50440F18F52475453B6F899").HexToByteArray(); internal static readonly byte[] SHA1WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D010105301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D010105300B06092A864886F70D010101048201002A" + "1EAADFA508990F3395BCCBCB5ECB9CDFF236B94306481C3F7EB6C0C0189FEDC0" + "3AF8DA8BB0474F7D10DD87A81661D8A703FF7D695A45BCC25D8185CF9C5EF39B" + "C0D582ABD3392B19D9A29BC4629FC401A97B2135C73F2D356B369EA18D864C3E" + "2CE77EAF0B1B71244D3D5FE442E6C92E2A0FB24EFF7EC8FD5EBB248870FDBDC5" + "FA8F458DB3C2159234BCF1FCDBCCB232CDEF7A7208C51A7DD4AC5AD01613B603" + "B11E5E1D7509286B92C701C4538D44DC3487656F9E25BA8C5CF6FBD7F532B749" + "0FBBBC5F4FC9BA6FFCB3910E85295C9C7DD36CF5AC3B3A1C425FAD84EA99CBE0" + "962CE8F7AAED44AA202273A3B5A2A7D8D98978642EE321703F9AB8768BECD2").HexToByteArray(); internal static readonly byte[] SHA256WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010B301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010B300B06092A864886F70D0101010482010054" + "5BAEC400A8F0EC436BDCE64B2FB22E8332C17538C9BBB72FCCF7C1F539A859A3" + "7E96754CA81AE81B24F937E1601681EB2315E632A76162B87C33403534DC64F0" + "E7DC8999BA05E7E030505B538124BB13FEC099F16372AE61DB75464DDE663ACE" + "10F136A6DA45CD988866B3630DEC1288AFA0B1864B93EE2B0713BA6C745A6775" + "061F19A1960218564478A814054EF844A6EF2C0ABFA5A854E60E1F275D7FB42A" + "0A4844DFB480AE88ABC83401DB59B333612AD2AAC6F5BB24FC09460D22499257" + "43F59476A8EC6E9E7E6C423F6574034B371F4562F347D10981141D9C7C36F47F" + "54882AD0FE5C78487C1F96785BD6BEBB958F5C140F86DFCE6F1E03B0AAE8C5").HexToByteArray(); internal static readonly byte[] SHA384WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010C301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010C300B06092A864886F70D0101010482010066" + "7739542DAC383580DD47E88B092FA77F8C7C2AF3C71E1E532D0CE6CA91FA27CF" + "A30F89AE9ACB3BD2ED666D8C7BE83FADEBC22847A8D12465AA5009967365E089" + "C1177FC71F80EF8EFFC0EC109368517EFEE26C989AAD2C7DA4C9DB52E9349F84" + "2EB3CFEA3E66338565715124D0980E6B27619B9F1CB8B1FA84946E034CDBDE43" + "18241EFC89D5E90F9B4434E4452827C00D01803C9E40B1E98D97E822AE549B32" + "6E547F8E8176DC3BAB9C9B2B9A87AC7EC5E0B2E5135C6FC9EC2B8ACC8F9D152D" + "A729967FAE63AEA42730A49E2740C9064DAA8F981E27DAB42D142FACE3D0261D" + "45C46FA632B0D7FFFC6F9EAC26E5EFC765D01A9C739C08D10775536488BF0D").HexToByteArray(); internal static readonly byte[] SHA512WithRSADigestAlgorithm = ( "308204BB06092A864886F70D010702A08204AC308204A8020101310D300B0609" + "2A864886F70D01010D301206092A864886F70D010701A0050403010203A08203" + "223082031E30820206A003020102020900DCE4D72A7F3CA58E300D06092A8648" + "86F70D01010B050030243122302006035504030C195253413230343853686132" + "35364B65795472616E7366657231301E170D3139303130333230343133345A17" + "0D3238313233313230343133345A30243122302006035504030C195253413230" + "34385368613235364B65795472616E736665723130820122300D06092A864886" + "F70D01010105000382010F003082010A0282010100BF8495EF84C91EB42AE919" + "6C52AA2C6E22A258C4D76E09E93980D81FAFE6977FE1A3C8B4E9CA414405A1A4" + "DB6D549A4849189D568AA639F10FA556F55377C8FDE8EC33CCDC833C4C5B8B36" + "275E8F1899443871B7363F204A28268BD9E890FDD488B17BC49890F78FAB5D8A" + "5927B69655760D400A30E0EE87DD38B4168DF6814596E0EFAAFB2F9CC134664B" + "B8629E65AA107847B4416BD57F0B701C30E9A160AA589646E981815D9823201A" + "E0EE601208C51C08D3E50B1FAB1560802916E678310C03E3CFF3BCC039F98D5B" + "254E2BAF027AE9F78FAEF72C2D93075ECA64B5AD3E92348068C4DCB8CAD0BAD9" + "54A7D04FCE3AFF94EF8CF282095DB75A25A4114F8F0203010001A3533051301D" + "0603551D0E04160414FEDFD2558B95E705584A50008ED0D1683AEE840E301F06" + "03551D23041830168014FEDFD2558B95E705584A50008ED0D1683AEE840E300F" + "0603551D130101FF040530030101FF300D06092A864886F70D01010B05000382" + "01010031C46689DB724A1A8D268EAA7139EFCF8A31496F15F325A19349547114" + "D7992EAD5FA0BD6FFD5539B1639F0CF8F975C5E9EBED8A048289C782EC7E0342" + "F339F53E811CC6A6864173502388875964F0C50D84ABA9228DD2E3DDD3339374" + "B76A6826F4F848A403ADDA2E095974232B084C8672B12C18D675D81ED8FA4B15" + "A1C7ABC73F9CCB5BC25716EEB9D2C97F8EBCB9D4824FB23C7FBC78E1D3B9B1B3" + "749F6C0981B2B6CC81DC723AA5CC589346DCECA222C78F68FE80563E12282F7D" + "F936A161163F86A9EADBA2E180A906DE73AEBEEA0775F6AB9AE97C71F26E187E" + "3D8CB50C8137663C99D440877D5A5E17DF9785976E9031DD96134A07899281B6" + "B64E3F3182015830820154020101303130243122302006035504030C19525341" + "323034385368613235364B65795472616E7366657231020900DCE4D72A7F3CA5" + "8E300B06092A864886F70D01010D300B06092A864886F70D0101010482010045" + "B324E7BE9FD3B1279018B01CD177A55A47A5C811CA693ED6BB32C8A243B1404D" + "89DC4EAA348453CB07BF8B1A11DE1BAF6397502C41D384790C0A285D69C17006" + "4F49D5735045EAAFAE43998D2660C6D15AEA1433FDFB7C4A995BBA4231AEB66B" + "81E29A035973CD148906A2FA16D6E551174D232E9DD738FE18D09E21517753A3" + "DF2687B83E0F8B70912F68FCF12311593637A362A3525BE875172BB402D998AE" + "D54F085DA892DD967FFE8906E23C0EF7E1C2ED89BB3986871BA997E725876535" + "119CFE807690BC067BA5781231E68A61CDE4D66AA67CD31981CF92275FD3485C" + "01CBA2BA29AED480F7AD26B361B39EE3622D1A705238E5C1A8BE2BBE921804").HexToByteArray(); internal static readonly byte[] SHA256ECDSAWithRsaSha256DigestIdentifier = ( "3082023006092A864886F70D010702A08202213082021D020101310D300B0609" + "2A864886F70D01010B301206092A864886F70D010701A0050403010203A08201" + "5C308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4DC830" + "0A06082A8648CE3D04030230153113301106035504030C0A4543445341205465" + "7374301E170D3135303530313030333730335A170D3136303530313030353730" + "335A30153113301106035504030C0A454344534120546573743059301306072A" + "8648CE3D020106082A8648CE3D030107034200047590F69CA114E92927E034C9" + "97B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA32496FDA" + "C84E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D0F01" + "01FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5CCFB8" + "220CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E19F1" + "AE4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CBDF43" + "4FDD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E318194" + "308191020101302930153113301106035504030C0A4543445341205465737402" + "1035428F3B3C5107AD49E776D6E74C4DC8300B06092A864886F70D01010B300A" + "06082A8648CE3D0403020448304602210087FAF07C8B9259F453A8EF63A1F2E9" + "36D6845255FE1109D84592E23E8E384611022100C8BA4D440C8AD0753CC43966" + "0CBB1A3FA93E7C1F8427BAB27150EB15F92D2928").HexToByteArray(); internal static readonly byte[] SHA256withRSADigestAndSHA256WithRSASignatureAlgorithm = ( "3082071B06092A864886F70D010702A082070C30820708020101310F300D0609" + "2A864886F70D01010B0500301606092A864886F70D010701A009040700010203" + "040506A08205223082051E30820406A00302010202100D85090F3FACFF0A9008" + "A12A9FB00A54300D06092A864886F70D01010B05003072310B30090603550406" + "1302555331153013060355040A130C446967694365727420496E633119301706" + "0355040B13107777772E64696769636572742E636F6D3131302F060355040313" + "2844696769436572742053484132204173737572656420494420436F64652053" + "69676E696E67204341301E170D3138303832393030303030305A170D31393039" + "30333132303030305A305B310B3009060355040613025553310B300906035504" + "0813025641311330110603550407130A416C6578616E64726961311430120603" + "55040A130B4B6576696E204A6F6E6573311430120603550403130B4B6576696E" + "204A6F6E657330820122300D06092A864886F70D01010105000382010F003082" + "010A0282010100F1F4542FF6CA57FBC44986EC816F07D1FD50BFD477C412D299" + "1C962D0A22194A4296BCD0751F47CE4932F73871277CE3CDD2C78157599C7A35" + "80CC96A11F7031E3A798F4BAA93988F0E4077D30316252B24337DB26914E1F77" + "9CB4979544514B0234E5388E936B195B91863B258F0C8951454D3668F0C4D456" + "A8497758D21C433626E46F2CFF5A7CC7945F788948998E5F8786E1E990E240BB" + "0780CD258F57761AFB5D42AD8E3D703C3126861E83F191ECE9F0B83221F96214" + "533B2A47977F43715FE501FBC4A4040839DD3EBCA8B67259A7DD0EA9EFAE2200" + "943EFB7D0404B8978B49A445849B5F6898B06269F427F30DBC8DB2FD7963943A" + "8C461760E6A4F30203010001A38201C5308201C1301F0603551D230418301680" + "145AC4B97B2A0AA3A5EA7103C060F92DF665750E58301D0603551D0E04160414" + "33795EB2D84BFAA3F96E5930F64EC6A94C6FD36A300E0603551D0F0101FF0404" + "0302078030130603551D25040C300A06082B0601050507030330770603551D1F" + "0470306E3035A033A031862F687474703A2F2F63726C332E6469676963657274" + "2E636F6D2F736861322D617373757265642D63732D67312E63726C3035A033A0" + "31862F687474703A2F2F63726C342E64696769636572742E636F6D2F73686132" + "2D617373757265642D63732D67312E63726C304C0603551D2004453043303706" + "096086480186FD6C0301302A302806082B06010505070201161C68747470733A" + "2F2F7777772E64696769636572742E636F6D2F4350533008060667810C010401" + "30818406082B0601050507010104783076302406082B06010505073001861868" + "7474703A2F2F6F6373702E64696769636572742E636F6D304E06082B06010505" + "0730028642687474703A2F2F636163657274732E64696769636572742E636F6D" + "2F446967694365727453484132417373757265644944436F64655369676E696E" + "6743412E637274300C0603551D130101FF04023000300D06092A864886F70D01" + "010B0500038201010045B9D9868E494BD02635D0E42DDE80B37A865C389CFDD9" + "9BFC9B62E2C169A73B5EABF282607439EFF5C61630886DEB63415B53683446A7" + "3041686C326BA35FF0029FEF603D7C80FA0177A4DE35013529B01F759FD50414" + "79BDBB6B93B18144CB14E431BC144146848EF8ADB0E28952EAD1BB49E8547FFE" + "9934817036338B20C4E0B9D7C6A4E5BE3D57157F21904A5C864946313EA6B7D9" + "50EE0235B5D2CD01490AD2B2A1AB5F66EC8986D64A1D9D239C131E09E5CA1C02" + "A75F2D7EC07E4C858856A6A58AB94DEAC8B3D3A5BBF492EE2463B156E6A0660B" + "B452E35922D00456F0DEE0ED15A8BF8FFF31008756B14EEE0AC14BCF19A3CD16" + "819DC990F5F45CDE21318201B2308201AE0201013081863072310B3009060355" + "04061302555331153013060355040A130C446967694365727420496E63311930" + "17060355040B13107777772E64696769636572742E636F6D3131302F06035504" + "03132844696769436572742053484132204173737572656420494420436F6465" + "205369676E696E6720434102100D85090F3FACFF0A9008A12A9FB00A54300D06" + "092A864886F70D01010B0500300D06092A864886F70D01010B050004820100E2" + "980C5A30EC00729D1CFA826D7A65B43FF6806B5E0ABA23A78E4F1CAA3F6436EF" + "00941C6947A9B8F20D0757B5346CF640AA217F7361BEEFF2BC997FB1D3597BF3" + "D7457BD4A94062FB03660F9D86710BE2FC99876A848251F4965E1B16192714C8" + "F9788C09CCDE83603ADC919297BA496E921B95F3BD9554A873E09912640FCFAA" + "D9DD1441D1851E637031D390C038223AE64B048E806462DDBAC98C156BE2EE47" + "2B78166BDB1612848B535ADC3F0E7BE52991A17F48AFDCCC1698A236BA338930" + "50EBAAC4460DAA35185C16670F597E0E6E0CB0AA83F51AAEF452F3367DD9350A" + "8A49A5A8F79DF8E921303AB5D6646A482F0F59D9980310E1AE3EE8D77CB857").HexToByteArray(); internal static readonly byte[] TstWithAttributeCertificate = ( "308212E306092A864886F70D010702A08212D4308212D0020103310F300D0609" + "608648016503040201050030820159060B2A864886F70D0109100104A0820148" + "0482014430820140020101060A2B0601040184590A03013031300D0609608648" + "01650304020105000420C61245B435391DCDD1EFF021681FA2A46E69410A9E23" + "09F1B1736BB7C2BB504402066148B8B838B11813323032313130303730343230" + "30372E3037345A3004800201F4A081D8A481D53081D2310B3009060355040613" + "025553311330110603550408130A57617368696E67746F6E3110300E06035504" + "0713075265646D6F6E64311E301C060355040A13154D6963726F736F66742043" + "6F72706F726174696F6E312D302B060355040B13244D6963726F736F66742049" + "72656C616E64204F7065726174696F6E73204C696D6974656431263024060355" + "040B131D5468616C6573205453532045534E3A303834322D344245362D433239" + "41312530230603550403131C4D6963726F736F66742054696D652D5374616D70" + "2053657276696365A0820E4A308204F9308203E1A00302010202133300000139" + "CCE8E8438BF034E1000000000139300D06092A864886F70D01010B0500307C31" + "0B3009060355040613025553311330110603550408130A57617368696E67746F" + "6E3110300E060355040713075265646D6F6E64311E301C060355040A13154D69" + "63726F736F667420436F72706F726174696F6E312630240603550403131D4D69" + "63726F736F66742054696D652D5374616D70205043412032303130301E170D32" + "30313031353137323832315A170D3232303131323137323832315A3081D2310B" + "3009060355040613025553311330110603550408130A57617368696E67746F6E" + "3110300E060355040713075265646D6F6E64311E301C060355040A13154D6963" + "726F736F667420436F72706F726174696F6E312D302B060355040B13244D6963" + "726F736F6674204972656C616E64204F7065726174696F6E73204C696D697465" + "6431263024060355040B131D5468616C6573205453532045534E3A303834322D" + "344245362D43323941312530230603550403131C4D6963726F736F6674205469" + "6D652D5374616D70205365727669636530820122300D06092A864886F70D0101" + "0105000382010F003082010A0282010100DA13F98CE3259325A18EB32A06FCA2" + "78F85A1F98374F7F50C1DBBA1EA02759C2E5CFDFD92A80BF405CF8E606F469DD" + "7822FA856859B627AA3EBE185B7F8A1024E1C34DC8D95C12904DB413FF0E8B09" + "6BDD0979C5425D9AF2711DE3612613BAF145598ABA66C7A04295F90C1874673B" + "D2AE4EF0CD9892A27F4AD72B16116D9A117172F559FA08386B3CEF13CEFEB282" + "33615EB3A8CD8A58EFD34B2F597A88B95F84286D5E802AEC091F4F32499DA540" + "15F39DDF2BC03CF2EBE058A895E29BE6FE57EEC4DFBE356FA710F5F98E340A47" + "2E1906AA8D3BFC1D783641AAA8EF7BF210235ED5684292A32AEEB2C57CECB294" + "278F4AE57EC57F1F2496FE5FA2CF1ECA4F0203010001A382011B30820117301D" + "0603551D0E04160414999E9B867254C299DA928AB19F46F6502D060CE9301F06" + "03551D23041830168014D5633A5C8A3190F3437B7C461BC533685A856D553056" + "0603551D1F044F304D304BA049A0478645687474703A2F2F63726C2E6D696372" + "6F736F66742E636F6D2F706B692F63726C2F70726F64756374732F4D69635469" + "6D5374615043415F323031302D30372D30312E63726C305A06082B0601050507" + "0101044E304C304A06082B06010505073002863E687474703A2F2F7777772E6D" + "6963726F736F66742E636F6D2F706B692F63657274732F4D696354696D537461" + "5043415F323031302D30372D30312E637274300C0603551D130101FF04023000" + "30130603551D25040C300A06082B06010505070308300D06092A864886F70D01" + "010B05000382010100585C286AF3FF371A85CDC15AED438288BF100DB126FBBA" + "F6118893A16D20F1D758C8AE566B514077FCA7243D6AC9CFD9C71F473FDD32A9" + "7293FABCF8835C08B1049694A09BDD71B821586C584084B26DA28CDFDFC687E6" + "B63667158DF5BB831249C97E21A22BA43EF2490235699B5A3D83C51C0417C21F" + "0708C5EC43E160381D8A52B3E3CEAEC21828B28AF51AE0D68A56231A830DAB79" + "6BC0322463FF37294A49868AE5A6205D908344B159027F3C842E67BD0B7B5A99" + "9B4C497C6B519C17E96ADFDDD498100AB2DFA3C9649AE2C13C21BF38C87AA0FC" + "78ACD4521DEE7C4DBF1231006DA6C1842A36FAD528CA74FA4C026D8DD8AF6B88" + "3B3FBDFF550AD270C73082067130820459A003020102020A6109812A00000000" + "0002300D06092A864886F70D01010B0500308188310B30090603550406130255" + "53311330110603550408130A57617368696E67746F6E3110300E060355040713" + "075265646D6F6E64311E301C060355040A13154D6963726F736F667420436F72" + "706F726174696F6E31323030060355040313294D6963726F736F667420526F6F" + "7420436572746966696361746520417574686F726974792032303130301E170D" + "3130303730313231333635355A170D3235303730313231343635355A307C310B" + "3009060355040613025553311330110603550408130A57617368696E67746F6E" + "3110300E060355040713075265646D6F6E64311E301C060355040A13154D6963" + "726F736F667420436F72706F726174696F6E312630240603550403131D4D6963" + "726F736F66742054696D652D5374616D7020504341203230313030820122300D" + "06092A864886F70D01010105000382010F003082010A0282010100A91D0DBC77" + "118A3A20ECFC1397F5FA7F69946B745410D5A50A008285FBED7C684B2C5FC5C3" + "E561C276B73E662B5BF015532704311F411B1A951DCE09138E7C613059B13044" + "0FF160888454430CD74DB83808B342DD93ACD67330572682A3450DD0EAF54781" + "CDBF246032586046F258478632841E746167915F8154B1CF934C92C1C4A65DD1" + "61136E28C61AF98680BBDF61FC46C1271D246712721A218AAF4B64895062B15D" + "FD771F3DF05775ACBD8A424D4051D10F9C063E677FF566C00396447EEFD04BFD" + "6EE59ACAB1A8F27A2A0A31F0DA4E0691B6880835E8781CB0E999CD3CE72F44BA" + "A7F4DC64BDA401C120099378CDFCBCC0C9445D5E169C01054F224D0203010001" + "A38201E6308201E2301006092B06010401823715010403020100301D0603551D" + "0E04160414D5633A5C8A3190F3437B7C461BC533685A856D55301906092B0601" + "040182371402040C1E0A00530075006200430041300B0603551D0F0404030201" + "86300F0603551D130101FF040530030101FF301F0603551D23041830168014D5" + "F656CB8FE8A25C6268D13D94905BD7CE9A18C430560603551D1F044F304D304B" + "A049A0478645687474703A2F2F63726C2E6D6963726F736F66742E636F6D2F70" + "6B692F63726C2F70726F64756374732F4D6963526F6F4365724175745F323031" + "302D30362D32332E63726C305A06082B06010505070101044E304C304A06082B" + "06010505073002863E687474703A2F2F7777772E6D6963726F736F66742E636F" + "6D2F706B692F63657274732F4D6963526F6F4365724175745F323031302D3036" + "2D32332E6372743081A00603551D200101FF04819530819230818F06092B0601" + "040182372E03308181303D06082B060105050702011631687474703A2F2F7777" + "772E6D6963726F736F66742E636F6D2F504B492F646F63732F4350532F646566" + "61756C742E68746D304006082B0601050507020230341E32201D004C00650067" + "0061006C005F0050006F006C006900630079005F00530074006100740065006D" + "0065006E0074002E201D300D06092A864886F70D01010B0500038202010007E6" + "88510DE2C6E0983F8171033D9DA3A1216FB3EBA6CCF531BECF05E2A9FEFA576D" + "1930B3C2C566C96ADFF5E7F078BDC7A89E25E3F9BCED6B5457082B51824412FB" + "B9538CCCF460128A76CC4040419BDC5C17FF5CF95E17359824564B74EF4210C8" + "AFBF7FC67FF2377D5A3F1CF299794A915200AF380F17F52F798165D9A9B56BE4" + "C7CEF6CA7A006F4B304424223CCFED03A5968F5929BCB6FD04E1709F324A27FD" + "55AF2FFEB6E58E33BB625F9ADB5740E9F1CE9966908CFF6A627FDDC54A0B9126" + "E239EC194A71639D7B216DC39CA3A23CFA7F7D966A9078A66DD2E19CF91DFC38" + "D894F4C6A50A9686A4BD9E1AAE044283B8B5809B223820B525E564ECF7F4BF7E" + "6359250F7A2E395776A271AA068A0F8916BA61A711CB9AD80E479A80C5D0CDA7" + "D0EF7D83F0E13B7109DF5D7498220861DAB0501E6FBDF1E100DFE73107A4933A" + "F7654778E8F8A848ABF7DE727E616B6F77A981CBA709AC39BBECC6CBD882B472" + "CD1DF4B885011E80FB1B892A5439B25BDAC80D55997A87733B08E6982DEA8DE0" + "332E1229F5C02F542721F7C8AC4EDA28B8B1A9DB96B2A742A2C9CF19414DE086" + "F92A9AA3116630D3BB74324BDF637BF5998A2F1BC721AF59B5AEDC443C975071" + "D7A1D2C555E369DE57C1D1DE30C0FDCCE64DFB0DBF5D4FE99D1E19382FBCCF58" + "052EEF0DA05035DAEF09271CD5B37E351E08BADA36DBD35F8FDE74884912A182" + "02D43082023D02010130820100A181D8A481D53081D2310B3009060355040613" + "025553311330110603550408130A57617368696E67746F6E3110300E06035504" + "0713075265646D6F6E64311E301C060355040A13154D6963726F736F66742043" + "6F72706F726174696F6E312D302B060355040B13244D6963726F736F66742049" + "72656C616E64204F7065726174696F6E73204C696D6974656431263024060355" + "040B131D5468616C6573205453532045534E3A303834322D344245362D433239" + "41312530230603550403131C4D6963726F736F66742054696D652D5374616D70" + "2053657276696365A2230A0101300706052B0E03021A0315000D4D94FE1BDE96" + "848D743F1DEE4A04C6B3658C07A08183308180A47E307C310B30090603550406" + "13025553311330110603550408130A57617368696E67746F6E3110300E060355" + "040713075265646D6F6E64311E301C060355040A13154D6963726F736F667420" + "436F72706F726174696F6E312630240603550403131D4D6963726F736F667420" + "54696D652D5374616D70205043412032303130300D06092A864886F70D010105" + "0500020500E5084E973022180F32303231313030373030333433315A180F3230" + "3231313030383030333433315A3074303A060A2B0601040184590A0401312C30" + "2A300A020500E5084E97020100300702010002021DE630070201000202113630" + "0A020500E509A0170201003036060A2B0601040184590A040231283026300C06" + "0A2B0601040184590A0302A00A3008020100020307A120A10A30080201000203" + "0186A0300D06092A864886F70D0101050500038181002AE0DF2A01AAE13A86C0" + "2DD8ECA787327C8F04A7C13D47256E65C60676B8372EE46362CD35391B6B898E" + "DC1884082AAA7CF9B1CF40BE2C30146D0080ACB225C50B7C1FE94694732EDEEB" + "9EDE73DB7D8C0762CBDFABD3ACCC82DD3858AA16C3ED185A40A39E9676772099" + "346E3362621286651B06D9AD26D574F967F6C7EC335A3182030D308203090201" + "01308193307C310B3009060355040613025553311330110603550408130A5761" + "7368696E67746F6E3110300E060355040713075265646D6F6E64311E301C0603" + "55040A13154D6963726F736F667420436F72706F726174696F6E312630240603" + "550403131D4D6963726F736F66742054696D652D5374616D7020504341203230" + "313002133300000139CCE8E8438BF034E1000000000139300D06096086480165" + "030402010500A082014A301A06092A864886F70D010903310D060B2A864886F7" + "0D0109100104302F06092A864886F70D01090431220420EA37C01965AB5A8B08" + "C2A59F8EF2008C2B60F78E7F0385E2DD18A07C63433EF43081FA060B2A864886" + "F70D010910022F3181EA3081E73081E43081BD04203CA18EE438A3D7247B3142" + "B1E28105AE7C6A5527F39A7A9F26A6D4A0070FFC9F308198308180A47E307C31" + "0B3009060355040613025553311330110603550408130A57617368696E67746F" + "6E3110300E060355040713075265646D6F6E64311E301C060355040A13154D69" + "63726F736F667420436F72706F726174696F6E312630240603550403131D4D69" + "63726F736F66742054696D652D5374616D702050434120323031300213330000" + "0139CCE8E8438BF034E1000000000139302204204A6E54AC16FAF6985726E0CB" + "5480381C41888386AB1D1BECC241E6BCFCBDD45B300D06092A864886F70D0101" + "0B0500048201006957F018A5C13CC539EB266EC2725998F4AC0ED50CE1CAA696" + "CAE377977F45FB8030136A4038B49F7E5A6ADCF72FA3901C26B52815621F52A2" + "EB2ACFC423087ECD954F34C341342E31BDF30443CAC4F1297AB0181467B90604" + "DDCF11F9F8930290614E8AA9D868E56971E4F83427819F8A1A11ED87AD1D5469" + "7AFFE60A8D7B7877CBB1D09F46397769B9D0F8EB605DBFE8F05C47A3F8BC1F65" + "F9F63553F187194B35E971FEFFB00C9127BDFD0F7FCF2424BE2A108AC5C532EA" + "6AB46C76047604BA7DF071EE0137B73F4D9DF616095C8F1CA9EB925B6D4C6ABC" + "FFEB73A81903169C6B487B316AFC951F696831A4B29B9ABCEA7EBCD243A553D2" + "F8B44FDA1B0AC0").HexToByteArray(); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/xdrerror.xdr
<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes"> <ElementType name="e1" dt:type="int"/> <ElementTypes name="e2" dt:type="number"/> <ElementType name="E1" content="eltOnly"> <element type="e1"/> <element type="e3"/> </ElementType> </Schema>
<Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes"> <ElementType name="e1" dt:type="int"/> <ElementTypes name="e2" dt:type="number"/> <ElementType name="E1" content="eltOnly"> <element type="e1"/> <element type="e3"/> </ElementType> </Schema>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/JitBlue/Runtime_54100/Runtime_54100.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; public class Runtime_54100 { // The test ends up containing an empty try block and we do not find a // non-empty block from which a treeNode can be extracted to use it for // creating zero-init refPositions. static ushort[][] s_23 = new ushort[][]{new ushort[]{0}}; static short s_32; static short s_33; static int s_45; public static int Main() { ushort[] vr4 = s_23[0]; return (int)M45(); } [MethodImpl(MethodImplOptions.NoInlining)] static ushort M45() { short var0; try { var0 = s_32; } finally { var0 = s_33; int var1 = s_45; ulong vr8 = default(ulong); var0 = (short)((sbyte)vr8 - var0); try { M46(); } finally { M46(); } System.Console.WriteLine(var1); } return 100; } static ulong M46() { return default(ulong); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; public class Runtime_54100 { // The test ends up containing an empty try block and we do not find a // non-empty block from which a treeNode can be extracted to use it for // creating zero-init refPositions. static ushort[][] s_23 = new ushort[][]{new ushort[]{0}}; static short s_32; static short s_33; static int s_45; public static int Main() { ushort[] vr4 = s_23[0]; return (int)M45(); } [MethodImpl(MethodImplOptions.NoInlining)] static ushort M45() { short var0; try { var0 = s_32; } finally { var0 = s_33; int var1 = s_45; ulong vr8 = default(ulong); var0 = (short)((sbyte)vr8 - var0); try { M46(); } finally { M46(); } System.Console.WriteLine(var1); } return 100; } static ulong M46() { return default(ulong); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApiV2/with-param.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl exobj" xmlns:exobj="urn-myobject"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <out> <xsl:call-template name="book"> <xsl:with-param name="titles" select="exobj:ReturnNodeSet('/books/book')/title"/> </xsl:call-template> </out> </xsl:template> <xsl:template name="book"> <xsl:param name="titles"/> <xsl:copy-of select="$titles"/> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl exobj" xmlns:exobj="urn-myobject"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <out> <xsl:call-template name="book"> <xsl:with-param name="titles" select="exobj:ReturnNodeSet('/books/book')/title"/> </xsl:call-template> </out> </xsl:template> <xsl:template name="book"> <xsl:param name="titles"/> <xsl:copy-of select="$titles"/> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./.git/logs/refs/remotes/origin/HEAD
0000000000000000000000000000000000000000 d14587922635ecf583733051106cc147f6173e06 jupyter <[email protected]> 1705184398 +0000 clone: from https://github.com/dotnet/runtime.git
0000000000000000000000000000000000000000 d14587922635ecf583733051106cc147f6173e06 jupyter <[email protected]> 1705184398 +0000 clone: from https://github.com/dotnet/runtime.git
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Globalization; using System.Numerics; using System.Security.Cryptography.X509Certificates; using System.Xml; namespace System.Security.Cryptography.Xml { public class KeyInfoX509Data : KeyInfoClause { // An array of certificates representing the certificate chain private ArrayList _certificates; // An array of issuer serial structs private ArrayList _issuerSerials; // An array of SKIs private ArrayList _subjectKeyIds; // An array of subject names private ArrayList _subjectNames; // A raw byte data representing a certificate revocation list private byte[] _CRL; // // public constructors // public KeyInfoX509Data() { } public KeyInfoX509Data(byte[] rgbCert) { X509Certificate2 certificate = new X509Certificate2(rgbCert); AddCertificate(certificate); } public KeyInfoX509Data(X509Certificate cert) { AddCertificate(cert); } public KeyInfoX509Data(X509Certificate cert!!, X509IncludeOption includeOption) { X509Certificate2 certificate = new X509Certificate2(cert); X509ChainElementCollection elements; X509Chain chain; switch (includeOption) { case X509IncludeOption.ExcludeRoot: // Build the certificate chain chain = new X509Chain(); chain.Build(certificate); // Can't honor the option if we only have a partial chain. if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(SR.Cryptography_Partial_Chain); } elements = (X509ChainElementCollection)chain.ChainElements; for (int index = 0; index < (Utils.IsSelfSigned(chain) ? 1 : elements.Count - 1); index++) { AddCertificate(elements[index].Certificate); } break; case X509IncludeOption.EndCertOnly: AddCertificate(certificate); break; case X509IncludeOption.WholeChain: // Build the certificate chain chain = new X509Chain(); chain.Build(certificate); // Can't honor the option if we only have a partial chain. if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(SR.Cryptography_Partial_Chain); } elements = (X509ChainElementCollection)chain.ChainElements; foreach (X509ChainElement element in elements) { AddCertificate(element.Certificate); } break; } } // // public properties // public ArrayList Certificates { get { return _certificates; } } public void AddCertificate(X509Certificate certificate!!) { if (_certificates == null) _certificates = new ArrayList(); X509Certificate2 x509 = new X509Certificate2(certificate); _certificates.Add(x509); } public ArrayList SubjectKeyIds { get { return _subjectKeyIds; } } public void AddSubjectKeyId(byte[] subjectKeyId) { if (_subjectKeyIds == null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(subjectKeyId); } public void AddSubjectKeyId(string subjectKeyId) { if (_subjectKeyIds == null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId)); } public ArrayList SubjectNames { get { return _subjectNames; } } public void AddSubjectName(string subjectName) { if (_subjectNames == null) _subjectNames = new ArrayList(); _subjectNames.Add(subjectName); } public ArrayList IssuerSerials { get { return _issuerSerials; } } public void AddIssuerSerial(string issuerName, string serialNumber) { if (string.IsNullOrEmpty(issuerName)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName)); if (string.IsNullOrEmpty(serialNumber)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(serialNumber)); BigInteger h; if (!BigInteger.TryParse(serialNumber, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out h)) throw new ArgumentException(SR.Cryptography_Xml_InvalidX509IssuerSerialNumber, nameof(serialNumber)); if (_issuerSerials == null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, h.ToString())); } // When we load an X509Data from Xml, we know the serial number is in decimal representation. internal void InternalAddIssuerSerial(string issuerName, string serialNumber) { if (_issuerSerials == null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber)); } public byte[] CRL { get { return _CRL; } set { _CRL = value; } } // // private methods // private void Clear() { _CRL = null; if (_subjectKeyIds != null) _subjectKeyIds.Clear(); if (_subjectNames != null) _subjectNames.Clear(); if (_issuerSerials != null) _issuerSerials.Clear(); if (_certificates != null) _certificates.Clear(); } // // public methods // public override XmlElement GetXml() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal override XmlElement GetXml(XmlDocument xmlDocument) { XmlElement x509DataElement = xmlDocument.CreateElement("X509Data", SignedXml.XmlDsigNamespaceUrl); if (_issuerSerials != null) { foreach (X509IssuerSerial issuerSerial in _issuerSerials) { XmlElement issuerSerialElement = xmlDocument.CreateElement("X509IssuerSerial", SignedXml.XmlDsigNamespaceUrl); XmlElement issuerNameElement = xmlDocument.CreateElement("X509IssuerName", SignedXml.XmlDsigNamespaceUrl); issuerNameElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.IssuerName)); issuerSerialElement.AppendChild(issuerNameElement); XmlElement serialNumberElement = xmlDocument.CreateElement("X509SerialNumber", SignedXml.XmlDsigNamespaceUrl); serialNumberElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.SerialNumber)); issuerSerialElement.AppendChild(serialNumberElement); x509DataElement.AppendChild(issuerSerialElement); } } if (_subjectKeyIds != null) { foreach (byte[] subjectKeyId in _subjectKeyIds) { XmlElement subjectKeyIdElement = xmlDocument.CreateElement("X509SKI", SignedXml.XmlDsigNamespaceUrl); subjectKeyIdElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(subjectKeyId))); x509DataElement.AppendChild(subjectKeyIdElement); } } if (_subjectNames != null) { foreach (string subjectName in _subjectNames) { XmlElement subjectNameElement = xmlDocument.CreateElement("X509SubjectName", SignedXml.XmlDsigNamespaceUrl); subjectNameElement.AppendChild(xmlDocument.CreateTextNode(subjectName)); x509DataElement.AppendChild(subjectNameElement); } } if (_certificates != null) { foreach (X509Certificate certificate in _certificates) { XmlElement x509Element = xmlDocument.CreateElement("X509Certificate", SignedXml.XmlDsigNamespaceUrl); x509Element.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(certificate.GetRawCertData()))); x509DataElement.AppendChild(x509Element); } } if (_CRL != null) { XmlElement crlElement = xmlDocument.CreateElement("X509CRL", SignedXml.XmlDsigNamespaceUrl); crlElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(_CRL))); x509DataElement.AppendChild(crlElement); } return x509DataElement; } public override void LoadXml(XmlElement element!!) { XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList x509IssuerSerialNodes = element.SelectNodes("ds:X509IssuerSerial", nsm); XmlNodeList x509SKINodes = element.SelectNodes("ds:X509SKI", nsm); XmlNodeList x509SubjectNameNodes = element.SelectNodes("ds:X509SubjectName", nsm); XmlNodeList x509CertificateNodes = element.SelectNodes("ds:X509Certificate", nsm); XmlNodeList x509CRLNodes = element.SelectNodes("ds:X509CRL", nsm); if ((x509CRLNodes.Count == 0 && x509IssuerSerialNodes.Count == 0 && x509SKINodes.Count == 0 && x509SubjectNameNodes.Count == 0 && x509CertificateNodes.Count == 0)) // Bad X509Data tag, or Empty tag throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "X509Data"); // Flush anything in the lists Clear(); if (x509CRLNodes.Count != 0) _CRL = Convert.FromBase64String(Utils.DiscardWhiteSpaces(x509CRLNodes.Item(0).InnerText)); foreach (XmlNode issuerSerialNode in x509IssuerSerialNodes) { XmlNode x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm); XmlNode x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm); if (x509IssuerNameNode == null || x509SerialNumberNode == null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "IssuerSerial"); InternalAddIssuerSerial(x509IssuerNameNode.InnerText.Trim(), x509SerialNumberNode.InnerText.Trim()); } foreach (XmlNode node in x509SKINodes) { AddSubjectKeyId(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText))); } foreach (XmlNode node in x509SubjectNameNodes) { AddSubjectName(node.InnerText.Trim()); } foreach (XmlNode node in x509CertificateNodes) { AddCertificate(new X509Certificate2(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText)))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Globalization; using System.Numerics; using System.Security.Cryptography.X509Certificates; using System.Xml; namespace System.Security.Cryptography.Xml { public class KeyInfoX509Data : KeyInfoClause { // An array of certificates representing the certificate chain private ArrayList _certificates; // An array of issuer serial structs private ArrayList _issuerSerials; // An array of SKIs private ArrayList _subjectKeyIds; // An array of subject names private ArrayList _subjectNames; // A raw byte data representing a certificate revocation list private byte[] _CRL; // // public constructors // public KeyInfoX509Data() { } public KeyInfoX509Data(byte[] rgbCert) { X509Certificate2 certificate = new X509Certificate2(rgbCert); AddCertificate(certificate); } public KeyInfoX509Data(X509Certificate cert) { AddCertificate(cert); } public KeyInfoX509Data(X509Certificate cert!!, X509IncludeOption includeOption) { X509Certificate2 certificate = new X509Certificate2(cert); X509ChainElementCollection elements; X509Chain chain; switch (includeOption) { case X509IncludeOption.ExcludeRoot: // Build the certificate chain chain = new X509Chain(); chain.Build(certificate); // Can't honor the option if we only have a partial chain. if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(SR.Cryptography_Partial_Chain); } elements = (X509ChainElementCollection)chain.ChainElements; for (int index = 0; index < (Utils.IsSelfSigned(chain) ? 1 : elements.Count - 1); index++) { AddCertificate(elements[index].Certificate); } break; case X509IncludeOption.EndCertOnly: AddCertificate(certificate); break; case X509IncludeOption.WholeChain: // Build the certificate chain chain = new X509Chain(); chain.Build(certificate); // Can't honor the option if we only have a partial chain. if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(SR.Cryptography_Partial_Chain); } elements = (X509ChainElementCollection)chain.ChainElements; foreach (X509ChainElement element in elements) { AddCertificate(element.Certificate); } break; } } // // public properties // public ArrayList Certificates { get { return _certificates; } } public void AddCertificate(X509Certificate certificate!!) { if (_certificates == null) _certificates = new ArrayList(); X509Certificate2 x509 = new X509Certificate2(certificate); _certificates.Add(x509); } public ArrayList SubjectKeyIds { get { return _subjectKeyIds; } } public void AddSubjectKeyId(byte[] subjectKeyId) { if (_subjectKeyIds == null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(subjectKeyId); } public void AddSubjectKeyId(string subjectKeyId) { if (_subjectKeyIds == null) _subjectKeyIds = new ArrayList(); _subjectKeyIds.Add(Utils.DecodeHexString(subjectKeyId)); } public ArrayList SubjectNames { get { return _subjectNames; } } public void AddSubjectName(string subjectName) { if (_subjectNames == null) _subjectNames = new ArrayList(); _subjectNames.Add(subjectName); } public ArrayList IssuerSerials { get { return _issuerSerials; } } public void AddIssuerSerial(string issuerName, string serialNumber) { if (string.IsNullOrEmpty(issuerName)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName)); if (string.IsNullOrEmpty(serialNumber)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(serialNumber)); BigInteger h; if (!BigInteger.TryParse(serialNumber, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out h)) throw new ArgumentException(SR.Cryptography_Xml_InvalidX509IssuerSerialNumber, nameof(serialNumber)); if (_issuerSerials == null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, h.ToString())); } // When we load an X509Data from Xml, we know the serial number is in decimal representation. internal void InternalAddIssuerSerial(string issuerName, string serialNumber) { if (_issuerSerials == null) _issuerSerials = new ArrayList(); _issuerSerials.Add(Utils.CreateX509IssuerSerial(issuerName, serialNumber)); } public byte[] CRL { get { return _CRL; } set { _CRL = value; } } // // private methods // private void Clear() { _CRL = null; if (_subjectKeyIds != null) _subjectKeyIds.Clear(); if (_subjectNames != null) _subjectNames.Clear(); if (_issuerSerials != null) _issuerSerials.Clear(); if (_certificates != null) _certificates.Clear(); } // // public methods // public override XmlElement GetXml() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; return GetXml(xmlDocument); } internal override XmlElement GetXml(XmlDocument xmlDocument) { XmlElement x509DataElement = xmlDocument.CreateElement("X509Data", SignedXml.XmlDsigNamespaceUrl); if (_issuerSerials != null) { foreach (X509IssuerSerial issuerSerial in _issuerSerials) { XmlElement issuerSerialElement = xmlDocument.CreateElement("X509IssuerSerial", SignedXml.XmlDsigNamespaceUrl); XmlElement issuerNameElement = xmlDocument.CreateElement("X509IssuerName", SignedXml.XmlDsigNamespaceUrl); issuerNameElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.IssuerName)); issuerSerialElement.AppendChild(issuerNameElement); XmlElement serialNumberElement = xmlDocument.CreateElement("X509SerialNumber", SignedXml.XmlDsigNamespaceUrl); serialNumberElement.AppendChild(xmlDocument.CreateTextNode(issuerSerial.SerialNumber)); issuerSerialElement.AppendChild(serialNumberElement); x509DataElement.AppendChild(issuerSerialElement); } } if (_subjectKeyIds != null) { foreach (byte[] subjectKeyId in _subjectKeyIds) { XmlElement subjectKeyIdElement = xmlDocument.CreateElement("X509SKI", SignedXml.XmlDsigNamespaceUrl); subjectKeyIdElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(subjectKeyId))); x509DataElement.AppendChild(subjectKeyIdElement); } } if (_subjectNames != null) { foreach (string subjectName in _subjectNames) { XmlElement subjectNameElement = xmlDocument.CreateElement("X509SubjectName", SignedXml.XmlDsigNamespaceUrl); subjectNameElement.AppendChild(xmlDocument.CreateTextNode(subjectName)); x509DataElement.AppendChild(subjectNameElement); } } if (_certificates != null) { foreach (X509Certificate certificate in _certificates) { XmlElement x509Element = xmlDocument.CreateElement("X509Certificate", SignedXml.XmlDsigNamespaceUrl); x509Element.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(certificate.GetRawCertData()))); x509DataElement.AppendChild(x509Element); } } if (_CRL != null) { XmlElement crlElement = xmlDocument.CreateElement("X509CRL", SignedXml.XmlDsigNamespaceUrl); crlElement.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(_CRL))); x509DataElement.AppendChild(crlElement); } return x509DataElement; } public override void LoadXml(XmlElement element!!) { XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList x509IssuerSerialNodes = element.SelectNodes("ds:X509IssuerSerial", nsm); XmlNodeList x509SKINodes = element.SelectNodes("ds:X509SKI", nsm); XmlNodeList x509SubjectNameNodes = element.SelectNodes("ds:X509SubjectName", nsm); XmlNodeList x509CertificateNodes = element.SelectNodes("ds:X509Certificate", nsm); XmlNodeList x509CRLNodes = element.SelectNodes("ds:X509CRL", nsm); if ((x509CRLNodes.Count == 0 && x509IssuerSerialNodes.Count == 0 && x509SKINodes.Count == 0 && x509SubjectNameNodes.Count == 0 && x509CertificateNodes.Count == 0)) // Bad X509Data tag, or Empty tag throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "X509Data"); // Flush anything in the lists Clear(); if (x509CRLNodes.Count != 0) _CRL = Convert.FromBase64String(Utils.DiscardWhiteSpaces(x509CRLNodes.Item(0).InnerText)); foreach (XmlNode issuerSerialNode in x509IssuerSerialNodes) { XmlNode x509IssuerNameNode = issuerSerialNode.SelectSingleNode("ds:X509IssuerName", nsm); XmlNode x509SerialNumberNode = issuerSerialNode.SelectSingleNode("ds:X509SerialNumber", nsm); if (x509IssuerNameNode == null || x509SerialNumberNode == null) throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "IssuerSerial"); InternalAddIssuerSerial(x509IssuerNameNode.InnerText.Trim(), x509SerialNumberNode.InnerText.Trim()); } foreach (XmlNode node in x509SKINodes) { AddSubjectKeyId(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText))); } foreach (XmlNode node in x509SubjectNameNodes) { AddSubjectName(node.InnerText.Trim()); } foreach (XmlNode node in x509CertificateNodes) { AddCertificate(new X509Certificate2(Convert.FromBase64String(Utils.DiscardWhiteSpaces(node.InnerText)))); } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/pal/src/libunwind/include/win/sys/stat.h
// This is an incomplete & imprecice implementation of the Posix // standard file by the same name // Since this is only intended for VC++ compilers // use #pragma once instead of guard macros #pragma once #ifdef _MSC_VER // Only for cross compilation to windows #include <sys/types.h> #define S_IFMT 00170000 #define S_IFDIR 0040000 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) struct stat { unsigned short st_dev; unsigned short st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; unsigned short st_rdev; unsigned short st_size; time_t st_atime; time_t st_mtime; time_t st_ctime; }; int stat(const char *path, struct stat *buf); int fstat(int fd, struct stat *buf); #endif // _MSC_VER
// This is an incomplete & imprecice implementation of the Posix // standard file by the same name // Since this is only intended for VC++ compilers // use #pragma once instead of guard macros #pragma once #ifdef _MSC_VER // Only for cross compilation to windows #include <sys/types.h> #define S_IFMT 00170000 #define S_IFDIR 0040000 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) struct stat { unsigned short st_dev; unsigned short st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; unsigned short st_rdev; unsigned short st_size; time_t st_atime; time_t st_mtime; time_t st_ctime; }; int stat(const char *path, struct stat *buf); int fstat(int fd, struct stat *buf); #endif // _MSC_VER
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest372/Generated372.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated372 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct422`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass0,class BaseClass0>, class IBase2`2<class BaseClass0,class BaseClass1> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct422::Method7.3475<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "MyStruct422::Method7.MI.3477<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod833() cil managed noinlining { ldstr "MyStruct422::ClassMethod833.3478()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated372 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.T.T<T0,T1,(valuetype MyStruct422`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.T.T<T0,T1,(valuetype MyStruct422`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.T<T1,(valuetype MyStruct422`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.T<T1,(valuetype MyStruct422`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.A<(valuetype MyStruct422`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.A<(valuetype MyStruct422`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.B<(valuetype MyStruct422`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.B<(valuetype MyStruct422`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.T<T1,(valuetype MyStruct422`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.T<T1,(valuetype MyStruct422`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.A<(valuetype MyStruct422`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.A<(valuetype MyStruct422`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.B<(valuetype MyStruct422`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.B<(valuetype MyStruct422`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated372::MethodCallingTest() call void Generated372::ConstrainedCallsTest() call void Generated372::StructConstrainedInterfaceCallsTest() call void Generated372::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated372 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct422`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass0,class BaseClass0>, class IBase2`2<class BaseClass0,class BaseClass1> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct422::Method7.3475<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "MyStruct422::Method7.MI.3477<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod833() cil managed noinlining { ldstr "MyStruct422::ClassMethod833.3478()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated372 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.T.T<T0,T1,(valuetype MyStruct422`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.T.T<T0,T1,(valuetype MyStruct422`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.T<T1,(valuetype MyStruct422`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.T<T1,(valuetype MyStruct422`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.A<(valuetype MyStruct422`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.A<(valuetype MyStruct422`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.A.B<(valuetype MyStruct422`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.A.B<(valuetype MyStruct422`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.T<T1,(valuetype MyStruct422`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.T<T1,(valuetype MyStruct422`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.A<(valuetype MyStruct422`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.A<(valuetype MyStruct422`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct422.B.B<(valuetype MyStruct422`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct422.B.B<(valuetype MyStruct422`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct422`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ClassMethod833() ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type MyStruct422" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_6 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_7 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_7 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_8 ldstr "MyStruct422::Method7.3475<System.Object>()#" call void Generated372::M.IBase2.A.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.IBase2.A.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.A<valuetype MyStruct422`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.A.B<valuetype MyStruct422`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.T<class BaseClass0,valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.A<valuetype MyStruct422`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.T<class BaseClass1,valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct422::Method7.3475<System.Object>()#" + "MyStruct422::Method7.MI.3477<System.Object>()#" call void Generated372::M.MyStruct422.B.B<valuetype MyStruct422`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct422`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct422`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct422`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct422`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ClassMethod833() calli default string(object) ldstr "MyStruct422::ClassMethod833.3478()" ldstr "valuetype MyStruct422`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct422`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.3475<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct422`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct422::Method7.MI.3477<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct422`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated372::MethodCallingTest() call void Generated372::ConstrainedCallsTest() call void Generated372::StructConstrainedInterfaceCallsTest() call void Generated372::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Linq.Expressions/tests/Dynamic/BindingRestrictionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; namespace System.Dynamic.Tests { public class BindingRestrictionsTests { // Considers itself equal to all of its kind, hence distinguishing equality and reference equality in tests. private class Egalitarian : IEquatable<Egalitarian> { public bool Equals(Egalitarian other) => true; public override bool Equals(object obj) => obj is Egalitarian; public override int GetHashCode() => 1; } [Fact] public void EmptyAllowsAll() { Expression exp = BindingRestrictions.Empty.ToExpression(); Assert.IsType<ConstantExpression>(exp); Assert.Equal(typeof(bool), exp.Type); Assert.Equal((object)true, ((ConstantExpression)exp).Value); // The above are implementation details that could reasonably change without error. // The below must still hold so that empty binding restrictions still allows everything. Assert.True(Expression.Lambda<Func<bool>>(exp).Compile()()); } [Fact] public void MergeWithEmptyReturnsSame() { BindingRestrictions isTrueBool = BindingRestrictions.GetTypeRestriction( Expression.Constant(true), typeof(bool)); Assert.Same(isTrueBool, isTrueBool.Merge(BindingRestrictions.Empty)); Assert.Same(isTrueBool, BindingRestrictions.Empty.Merge(isTrueBool)); } [Fact] public void MergeWithSelfReturnsNotSame() { BindingRestrictions isTrueBool = BindingRestrictions.GetTypeRestriction( Expression.Constant(true), typeof(bool)); Assert.NotSame(isTrueBool, isTrueBool.Merge(isTrueBool)); } [Fact] public void MergeWithSelfHasSameExpression() { Expression exp = Expression.Constant(true); BindingRestrictions allowAll = BindingRestrictions.GetExpressionRestriction(exp); BindingRestrictions doubled = allowAll.Merge(allowAll); Assert.Same(exp, doubled.ToExpression()); } [Fact] public void MergeNull() { AssertExtensions.Throws<ArgumentNullException>("restrictions", () => BindingRestrictions.Empty.Merge(null)); } [Fact] public void ExpressionRestrictionFromNull() { AssertExtensions.Throws<ArgumentNullException>("expression", () => BindingRestrictions.GetExpressionRestriction(null)); } [Fact] public void ExpressionRestrictionFromNonBooleanExpression() { AssertExtensions.Throws<ArgumentException>( "expression", () => BindingRestrictions.GetExpressionRestriction(Expression.Empty())); AssertExtensions.Throws<ArgumentException>( "expression", () => BindingRestrictions.GetExpressionRestriction(Expression.Constant(""))); } [Fact] public void InstanceRestrictionFromNull() { AssertExtensions.Throws<ArgumentNullException>( "expression", () => BindingRestrictions.GetInstanceRestriction(null, new object())); } [Fact] public void CombineRestrictionsFromNull() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(null)); } [Fact] public void CombineRestrictionsFromEmpty() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(Array.Empty<DynamicMetaObject>())); } [Fact] public void CombineRestrictionsFromAllNull() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(new DynamicMetaObject[10])); } [Fact] public void CustomRestrictionsEqualIfExpressionSame() { Expression exp = Expression.Constant(false); BindingRestrictions x = BindingRestrictions.GetExpressionRestriction(exp); BindingRestrictions y = BindingRestrictions.GetExpressionRestriction(exp); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void CustomRestrictionsNotEqualIfExpressionsNotSame() { BindingRestrictions x = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); BindingRestrictions y = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); Assert.NotEqual(x, y); } [Fact] public void CustomRestrictionsNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); Assert.False(br.Equals(null)); } [Fact] public void MergeCombines() { foreach (bool x in new[] {false, true}) foreach (bool y in new[] {false, true}) { BindingRestrictions bX = BindingRestrictions.GetExpressionRestriction(Expression.Constant(x)); BindingRestrictions bY = BindingRestrictions.GetExpressionRestriction(Expression.Constant(y)); BindingRestrictions merged = bX.Merge(bY); Assert.Equal(x & y, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); } } [Fact] public void MergeCombinesDeeper() { foreach (bool w in new[] {false, true}) { BindingRestrictions bW = BindingRestrictions.GetExpressionRestriction(Expression.Constant(w)); foreach (bool x in new[] {false, true}) { BindingRestrictions bX = BindingRestrictions.GetExpressionRestriction(Expression.Constant(x)); foreach (bool y in new[] {false, true}) { BindingRestrictions bY = BindingRestrictions.GetExpressionRestriction(Expression.Constant(y)); BindingRestrictions merged = bW.Merge(bX).Merge(bY); Assert.Equal(w & x & y, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); foreach (bool z in new[] {false, true}) { BindingRestrictions bZ = BindingRestrictions.GetExpressionRestriction( Expression.Constant(z)); merged = bW.Merge(bX).Merge(bY).Merge(bZ); Assert.Equal( w & x & y & z, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); } } } } } [Fact] public void InstanceRestrictionRequiresIdentity() { Egalitarian instance = new Egalitarian(); Expression exp = Expression.Constant(instance); BindingRestrictions sameInstance = BindingRestrictions.GetInstanceRestriction(exp, instance); Assert.True(Expression.Lambda<Func<bool>>(sameInstance.ToExpression()).Compile()()); BindingRestrictions diffInstance = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.False(Expression.Lambda<Func<bool>>(diffInstance.ToExpression()).Compile()()); BindingRestrictions noInstance = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.False(Expression.Lambda<Func<bool>>(noInstance.ToExpression()).Compile()()); } [Fact] public void InstanceRestrictionForNull() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions hasNull = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.True(Expression.Lambda<Func<bool>>(hasNull.ToExpression()).Compile()()); BindingRestrictions hasInst = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.False(Expression.Lambda<Func<bool>>(hasInst.ToExpression()).Compile()()); } [Fact] public void InstanceRestrictionEqualsIfAllSame() { Expression exp = Expression.Default(typeof(Egalitarian)); Egalitarian inst = new Egalitarian(); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction(exp, inst); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction(exp, inst); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); x = BindingRestrictions.GetInstanceRestriction(exp, null); y = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void InstanceRestrictionNotEqualIfDifferentInstance() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.NotEqual(x, y); } [Fact] public void InstanceRestrictionNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), null); Assert.False(br.Equals(null)); } [Fact] public void InstanceRestrictionNotEqualIfDifferentExpression() { Egalitarian inst = new Egalitarian(); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), inst); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), inst); Assert.NotEqual(x, y); } private static IEnumerable<object> SomeObjects() { yield return ""; yield return 0; yield return new Uri("https://example.net/"); yield return DateTime.MaxValue; } public static IEnumerable<object[]> ObjectsAsArguments => SomeObjects().Select(o => new[] {o}); public static IEnumerable<object[]> ObjectsAndWrongTypes() => from obj in SomeObjects() from typeObj in SomeObjects() where obj.GetType() != typeObj.GetType() select new[] {obj, typeObj.GetType()}; [Theory, MemberData(nameof(ObjectsAsArguments))] public void TypeRestrictionTrueForMatchType(object obj) { BindingRestrictions isType = BindingRestrictions.GetTypeRestriction(Expression.Constant(obj), obj.GetType()); Assert.True(Expression.Lambda<Func<bool>>(isType.ToExpression()).Compile()()); } [Theory, MemberData(nameof(ObjectsAndWrongTypes))] public void TypeRestrictionFalseForOtherType(object obj, Type type) { BindingRestrictions isType = BindingRestrictions.GetTypeRestriction(Expression.Constant(obj), type); Assert.False(Expression.Lambda<Func<bool>>(isType.ToExpression()).Compile()()); } [Fact] public void TypeRestrictionEqualIfSameTypeAndExpression() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetTypeRestriction(exp, typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction( exp, typeof(Egalitarian).MakeArrayType().GetElementType()); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void TypeRestrictionNotEqualIfDifferentType() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetTypeRestriction(exp, typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction(exp, typeof(string)); Assert.NotEqual(x, y); } [Fact] public void TypeRestrictionNotEqualIfDifferentExpression() { BindingRestrictions x = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); Assert.NotEqual(x, y); } [Fact] public void TypeRestrictionNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); Assert.False(br.Equals(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; namespace System.Dynamic.Tests { public class BindingRestrictionsTests { // Considers itself equal to all of its kind, hence distinguishing equality and reference equality in tests. private class Egalitarian : IEquatable<Egalitarian> { public bool Equals(Egalitarian other) => true; public override bool Equals(object obj) => obj is Egalitarian; public override int GetHashCode() => 1; } [Fact] public void EmptyAllowsAll() { Expression exp = BindingRestrictions.Empty.ToExpression(); Assert.IsType<ConstantExpression>(exp); Assert.Equal(typeof(bool), exp.Type); Assert.Equal((object)true, ((ConstantExpression)exp).Value); // The above are implementation details that could reasonably change without error. // The below must still hold so that empty binding restrictions still allows everything. Assert.True(Expression.Lambda<Func<bool>>(exp).Compile()()); } [Fact] public void MergeWithEmptyReturnsSame() { BindingRestrictions isTrueBool = BindingRestrictions.GetTypeRestriction( Expression.Constant(true), typeof(bool)); Assert.Same(isTrueBool, isTrueBool.Merge(BindingRestrictions.Empty)); Assert.Same(isTrueBool, BindingRestrictions.Empty.Merge(isTrueBool)); } [Fact] public void MergeWithSelfReturnsNotSame() { BindingRestrictions isTrueBool = BindingRestrictions.GetTypeRestriction( Expression.Constant(true), typeof(bool)); Assert.NotSame(isTrueBool, isTrueBool.Merge(isTrueBool)); } [Fact] public void MergeWithSelfHasSameExpression() { Expression exp = Expression.Constant(true); BindingRestrictions allowAll = BindingRestrictions.GetExpressionRestriction(exp); BindingRestrictions doubled = allowAll.Merge(allowAll); Assert.Same(exp, doubled.ToExpression()); } [Fact] public void MergeNull() { AssertExtensions.Throws<ArgumentNullException>("restrictions", () => BindingRestrictions.Empty.Merge(null)); } [Fact] public void ExpressionRestrictionFromNull() { AssertExtensions.Throws<ArgumentNullException>("expression", () => BindingRestrictions.GetExpressionRestriction(null)); } [Fact] public void ExpressionRestrictionFromNonBooleanExpression() { AssertExtensions.Throws<ArgumentException>( "expression", () => BindingRestrictions.GetExpressionRestriction(Expression.Empty())); AssertExtensions.Throws<ArgumentException>( "expression", () => BindingRestrictions.GetExpressionRestriction(Expression.Constant(""))); } [Fact] public void InstanceRestrictionFromNull() { AssertExtensions.Throws<ArgumentNullException>( "expression", () => BindingRestrictions.GetInstanceRestriction(null, new object())); } [Fact] public void CombineRestrictionsFromNull() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(null)); } [Fact] public void CombineRestrictionsFromEmpty() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(Array.Empty<DynamicMetaObject>())); } [Fact] public void CombineRestrictionsFromAllNull() { Assert.Same(BindingRestrictions.Empty, BindingRestrictions.Combine(new DynamicMetaObject[10])); } [Fact] public void CustomRestrictionsEqualIfExpressionSame() { Expression exp = Expression.Constant(false); BindingRestrictions x = BindingRestrictions.GetExpressionRestriction(exp); BindingRestrictions y = BindingRestrictions.GetExpressionRestriction(exp); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void CustomRestrictionsNotEqualIfExpressionsNotSame() { BindingRestrictions x = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); BindingRestrictions y = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); Assert.NotEqual(x, y); } [Fact] public void CustomRestrictionsNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetExpressionRestriction(Expression.Constant(false)); Assert.False(br.Equals(null)); } [Fact] public void MergeCombines() { foreach (bool x in new[] {false, true}) foreach (bool y in new[] {false, true}) { BindingRestrictions bX = BindingRestrictions.GetExpressionRestriction(Expression.Constant(x)); BindingRestrictions bY = BindingRestrictions.GetExpressionRestriction(Expression.Constant(y)); BindingRestrictions merged = bX.Merge(bY); Assert.Equal(x & y, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); } } [Fact] public void MergeCombinesDeeper() { foreach (bool w in new[] {false, true}) { BindingRestrictions bW = BindingRestrictions.GetExpressionRestriction(Expression.Constant(w)); foreach (bool x in new[] {false, true}) { BindingRestrictions bX = BindingRestrictions.GetExpressionRestriction(Expression.Constant(x)); foreach (bool y in new[] {false, true}) { BindingRestrictions bY = BindingRestrictions.GetExpressionRestriction(Expression.Constant(y)); BindingRestrictions merged = bW.Merge(bX).Merge(bY); Assert.Equal(w & x & y, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); foreach (bool z in new[] {false, true}) { BindingRestrictions bZ = BindingRestrictions.GetExpressionRestriction( Expression.Constant(z)); merged = bW.Merge(bX).Merge(bY).Merge(bZ); Assert.Equal( w & x & y & z, Expression.Lambda<Func<bool>>(merged.ToExpression()).Compile()()); } } } } } [Fact] public void InstanceRestrictionRequiresIdentity() { Egalitarian instance = new Egalitarian(); Expression exp = Expression.Constant(instance); BindingRestrictions sameInstance = BindingRestrictions.GetInstanceRestriction(exp, instance); Assert.True(Expression.Lambda<Func<bool>>(sameInstance.ToExpression()).Compile()()); BindingRestrictions diffInstance = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.False(Expression.Lambda<Func<bool>>(diffInstance.ToExpression()).Compile()()); BindingRestrictions noInstance = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.False(Expression.Lambda<Func<bool>>(noInstance.ToExpression()).Compile()()); } [Fact] public void InstanceRestrictionForNull() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions hasNull = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.True(Expression.Lambda<Func<bool>>(hasNull.ToExpression()).Compile()()); BindingRestrictions hasInst = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.False(Expression.Lambda<Func<bool>>(hasInst.ToExpression()).Compile()()); } [Fact] public void InstanceRestrictionEqualsIfAllSame() { Expression exp = Expression.Default(typeof(Egalitarian)); Egalitarian inst = new Egalitarian(); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction(exp, inst); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction(exp, inst); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); x = BindingRestrictions.GetInstanceRestriction(exp, null); y = BindingRestrictions.GetInstanceRestriction(exp, null); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void InstanceRestrictionNotEqualIfDifferentInstance() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction(exp, new Egalitarian()); Assert.NotEqual(x, y); } [Fact] public void InstanceRestrictionNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), null); Assert.False(br.Equals(null)); } [Fact] public void InstanceRestrictionNotEqualIfDifferentExpression() { Egalitarian inst = new Egalitarian(); BindingRestrictions x = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), inst); BindingRestrictions y = BindingRestrictions.GetInstanceRestriction( Expression.Default(typeof(Egalitarian)), inst); Assert.NotEqual(x, y); } private static IEnumerable<object> SomeObjects() { yield return ""; yield return 0; yield return new Uri("https://example.net/"); yield return DateTime.MaxValue; } public static IEnumerable<object[]> ObjectsAsArguments => SomeObjects().Select(o => new[] {o}); public static IEnumerable<object[]> ObjectsAndWrongTypes() => from obj in SomeObjects() from typeObj in SomeObjects() where obj.GetType() != typeObj.GetType() select new[] {obj, typeObj.GetType()}; [Theory, MemberData(nameof(ObjectsAsArguments))] public void TypeRestrictionTrueForMatchType(object obj) { BindingRestrictions isType = BindingRestrictions.GetTypeRestriction(Expression.Constant(obj), obj.GetType()); Assert.True(Expression.Lambda<Func<bool>>(isType.ToExpression()).Compile()()); } [Theory, MemberData(nameof(ObjectsAndWrongTypes))] public void TypeRestrictionFalseForOtherType(object obj, Type type) { BindingRestrictions isType = BindingRestrictions.GetTypeRestriction(Expression.Constant(obj), type); Assert.False(Expression.Lambda<Func<bool>>(isType.ToExpression()).Compile()()); } [Fact] public void TypeRestrictionEqualIfSameTypeAndExpression() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetTypeRestriction(exp, typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction( exp, typeof(Egalitarian).MakeArrayType().GetElementType()); Assert.Equal(x, y); Assert.Equal(x.GetHashCode(), y.GetHashCode()); } [Fact] public void TypeRestrictionNotEqualIfDifferentType() { Expression exp = Expression.Default(typeof(Egalitarian)); BindingRestrictions x = BindingRestrictions.GetTypeRestriction(exp, typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction(exp, typeof(string)); Assert.NotEqual(x, y); } [Fact] public void TypeRestrictionNotEqualIfDifferentExpression() { BindingRestrictions x = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); BindingRestrictions y = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); Assert.NotEqual(x, y); } [Fact] public void TypeRestrictionNotEqualNull() { BindingRestrictions br = BindingRestrictions.GetTypeRestriction( Expression.Default(typeof(Egalitarian)), typeof(Egalitarian)); Assert.False(br.Equals(null)); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/nativeaot/Runtime/arm/CallDescrWorker.S
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .syntax unified .thumb #include <AsmOffsets.inc> // generated by the build from AsmOffsets.cpp #include <unixasmmacros.inc> // TODO: Implement Arm support NESTED_ENTRY RhCallDescrWorker, _TEXT, NoHandler LOCAL_LABEL(ReturnFromCallDescrThunk): EXPORT_POINTER_TO_ADDRESS PointerToReturnFromCallDescrThunk // UNIXTODO: Implement this function EMIT_BREAKPOINT NESTED_END RhCallDescrWorker, _TEXT
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .syntax unified .thumb #include <AsmOffsets.inc> // generated by the build from AsmOffsets.cpp #include <unixasmmacros.inc> // TODO: Implement Arm support NESTED_ENTRY RhCallDescrWorker, _TEXT, NoHandler LOCAL_LABEL(ReturnFromCallDescrThunk): EXPORT_POINTER_TO_ADDRESS PointerToReturnFromCallDescrThunk // UNIXTODO: Implement this function EMIT_BREAKPOINT NESTED_END RhCallDescrWorker, _TEXT
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CastingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class CastingTests { private TestTypeSystemContext _context; private ModuleDesc _testModule; public CastingTests() { _context = new TestTypeSystemContext(TargetArchitecture.X64); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; } [Fact] public void TestCastingInHierarchy() { TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc uintType = _context.GetWellKnownType(WellKnownType.UInt32); Assert.True(stringType.CanCastTo(objectType)); Assert.True(objectType.CanCastTo(objectType)); Assert.True(intType.CanCastTo(objectType)); Assert.False(objectType.CanCastTo(stringType)); Assert.False(intType.CanCastTo(uintType)); Assert.False(uintType.CanCastTo(intType)); } [Fact] public void TestInterfaceCasting() { TypeDesc iFooType = _testModule.GetType("Casting", "IFoo"); TypeDesc classImplementingIFooType = _testModule.GetType("Casting", "ClassImplementingIFoo"); TypeDesc classImplementingIFooIndirectlyType = _testModule.GetType("Casting", "ClassImplementingIFooIndirectly"); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); Assert.True(classImplementingIFooType.CanCastTo(iFooType)); Assert.True(classImplementingIFooIndirectlyType.CanCastTo(iFooType)); Assert.True(iFooType.CanCastTo(objectType)); Assert.False(objectType.CanCastTo(iFooType)); } [Fact] public void TestSameSizeArrayTypeCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc uintType = _context.GetWellKnownType(WellKnownType.UInt32); TypeDesc byteType = _context.GetWellKnownType(WellKnownType.Byte); TypeDesc sbyteType = _context.GetWellKnownType(WellKnownType.SByte); TypeDesc intPtrType = _context.GetWellKnownType(WellKnownType.IntPtr); TypeDesc ulongType = _context.GetWellKnownType(WellKnownType.UInt64); TypeDesc doubleType = _context.GetWellKnownType(WellKnownType.Double); TypeDesc boolType = _context.GetWellKnownType(WellKnownType.Boolean); TypeDesc intBasedEnumType = _testModule.GetType("Casting", "IntBasedEnum"); TypeDesc uintBasedEnumType = _testModule.GetType("Casting", "UIntBasedEnum"); TypeDesc shortBasedEnumType = _testModule.GetType("Casting", "ShortBasedEnum"); Assert.True(intType.MakeArrayType().CanCastTo(uintType.MakeArrayType())); Assert.True(intType.MakeArrayType().CanCastTo(uintType.MakeArrayType(1))); Assert.False(intType.CanCastTo(uintType)); Assert.True(byteType.MakeArrayType().CanCastTo(sbyteType.MakeArrayType())); Assert.False(byteType.CanCastTo(sbyteType)); Assert.False(intPtrType.MakeArrayType().CanCastTo(ulongType.MakeArrayType())); Assert.False(intPtrType.CanCastTo(ulongType)); // These are same size, but not allowed to cast Assert.False(doubleType.MakeArrayType().CanCastTo(ulongType.MakeArrayType())); Assert.False(boolType.MakeArrayType().CanCastTo(byteType.MakeArrayType())); Assert.True(intBasedEnumType.MakeArrayType().CanCastTo(uintType.MakeArrayType())); Assert.True(intBasedEnumType.MakeArrayType().CanCastTo(uintBasedEnumType.MakeArrayType())); Assert.False(shortBasedEnumType.MakeArrayType().CanCastTo(intType.MakeArrayType())); } [Fact] public void TestArrayInterfaceCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); MetadataType iListType = _context.SystemModule.GetType("System.Collections", "IList"); MetadataType iListOfTType = _context.SystemModule.GetType("System.Collections.Generic", "IList`1"); InstantiatedType iListOfIntType = iListOfTType.MakeInstantiatedType(intType); TypeDesc intSzArrayType = intType.MakeArrayType(); TypeDesc intArrayType = intType.MakeArrayType(1); Assert.True(intSzArrayType.CanCastTo(iListOfIntType)); Assert.True(intSzArrayType.CanCastTo(iListType)); Assert.False(intArrayType.CanCastTo(iListOfIntType)); Assert.True(intArrayType.CanCastTo(iListType)); } [Fact] public void TestArrayCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc arrayType = _context.GetWellKnownType(WellKnownType.Array); TypeDesc intSzArrayType = intType.MakeArrayType(); TypeDesc intArray1Type = intType.MakeArrayType(1); TypeDesc intArray2Type = intType.MakeArrayType(2); TypeDesc stringSzArrayType = stringType.MakeArrayType(); TypeDesc objectSzArrayType = objectType.MakeArrayType(); Assert.True(intSzArrayType.CanCastTo(intArray1Type)); Assert.False(intArray1Type.CanCastTo(intSzArrayType)); Assert.False(intArray1Type.CanCastTo(intArray2Type)); Assert.True(intSzArrayType.CanCastTo(arrayType)); Assert.True(intArray1Type.CanCastTo(arrayType)); Assert.True(stringSzArrayType.CanCastTo(objectSzArrayType)); Assert.False(intSzArrayType.CanCastTo(objectSzArrayType)); } [Fact] public void TestGenericParameterCasting() { TypeDesc paramWithNoConstraint = _testModule.GetType("Casting", "ClassWithNoConstraint`1").Instantiation[0]; TypeDesc paramWithValueTypeConstraint = _testModule.GetType("Casting", "ClassWithValueTypeConstraint`1").Instantiation[0]; TypeDesc paramWithInterfaceConstraint = _testModule.GetType("Casting", "ClassWithInterfaceConstraint`1").Instantiation[0]; TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc valueTypeType = _context.GetWellKnownType(WellKnownType.ValueType); TypeDesc iFooType = _testModule.GetType("Casting", "IFoo"); TypeDesc classImplementingIFooType = _testModule.GetType("Casting", "ClassImplementingIFoo"); TypeDesc classImplementingIFooIndirectlyType = _testModule.GetType("Casting", "ClassImplementingIFooIndirectly"); Assert.True(paramWithNoConstraint.CanCastTo(objectType)); Assert.False(paramWithNoConstraint.CanCastTo(valueTypeType)); Assert.False(paramWithNoConstraint.CanCastTo(iFooType)); Assert.False(paramWithNoConstraint.CanCastTo(classImplementingIFooType)); Assert.True(paramWithValueTypeConstraint.CanCastTo(objectType)); Assert.True(paramWithValueTypeConstraint.CanCastTo(valueTypeType)); Assert.False(paramWithValueTypeConstraint.CanCastTo(iFooType)); Assert.False(paramWithValueTypeConstraint.CanCastTo(classImplementingIFooType)); Assert.True(paramWithInterfaceConstraint.CanCastTo(objectType)); Assert.False(paramWithInterfaceConstraint.CanCastTo(valueTypeType)); Assert.True(paramWithInterfaceConstraint.CanCastTo(iFooType)); Assert.False(paramWithInterfaceConstraint.CanCastTo(classImplementingIFooType)); } [Fact] public void TestVariantCasting() { TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc exceptionType = _context.GetWellKnownType(WellKnownType.Exception); TypeDesc stringSzArrayType = stringType.MakeArrayType(); MetadataType iEnumerableOfTType = _context.SystemModule.GetType("System.Collections.Generic", "IEnumerable`1"); InstantiatedType iEnumerableOfObjectType = iEnumerableOfTType.MakeInstantiatedType(objectType); InstantiatedType iEnumerableOfExceptionType = iEnumerableOfTType.MakeInstantiatedType(exceptionType); Assert.True(stringSzArrayType.CanCastTo(iEnumerableOfObjectType)); Assert.False(stringSzArrayType.CanCastTo(iEnumerableOfExceptionType)); MetadataType iContravariantOfTType = _testModule.GetType("Casting", "IContravariant`1"); InstantiatedType iContravariantOfObjectType = iContravariantOfTType.MakeInstantiatedType(objectType); InstantiatedType iEnumerableOfStringType = iEnumerableOfTType.MakeInstantiatedType(stringType); Assert.True(iContravariantOfObjectType.CanCastTo(objectType)); Assert.True(iEnumerableOfStringType.CanCastTo(objectType)); } [Fact] public void TestNullableCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); MetadataType nullableType = (MetadataType)_context.GetWellKnownType(WellKnownType.Nullable); TypeDesc nullableOfIntType = nullableType.MakeInstantiatedType(intType); Assert.True(intType.CanCastTo(nullableOfIntType)); } [Fact] public void TestGenericParameterArrayCasting() { TypeDesc baseArrayType = _testModule.GetType("Casting", "Base").MakeArrayType(); TypeDesc iFooArrayType = _testModule.GetType("Casting", "IFoo").MakeArrayType(); TypeDesc paramArrayWithBaseClassConstraint = _testModule.GetType("Casting", "ClassWithBaseClassConstraint`1").Instantiation[0].MakeArrayType(); TypeDesc paramArrayWithInterfaceConstraint = _testModule.GetType("Casting", "ClassWithInterfaceConstraint`1").Instantiation[0].MakeArrayType(); Assert.True(paramArrayWithBaseClassConstraint.CanCastTo(baseArrayType)); Assert.False(paramArrayWithInterfaceConstraint.CanCastTo(iFooArrayType)); } [Fact] public void TestRecursiveCanCast() { // Tests the stack overflow protection in CanCastTo TypeDesc classWithRecursiveImplementation = _testModule.GetType("Casting", "ClassWithRecursiveImplementation"); MetadataType iContravariantOfTType = (MetadataType)_testModule.GetType("Casting", "IContravariant`1"); TypeDesc testType = iContravariantOfTType.MakeInstantiatedType(classWithRecursiveImplementation); Assert.False(classWithRecursiveImplementation.CanCastTo(testType)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; using Xunit; namespace TypeSystemTests { public class CastingTests { private TestTypeSystemContext _context; private ModuleDesc _testModule; public CastingTests() { _context = new TestTypeSystemContext(TargetArchitecture.X64); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); _testModule = systemModule; } [Fact] public void TestCastingInHierarchy() { TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc uintType = _context.GetWellKnownType(WellKnownType.UInt32); Assert.True(stringType.CanCastTo(objectType)); Assert.True(objectType.CanCastTo(objectType)); Assert.True(intType.CanCastTo(objectType)); Assert.False(objectType.CanCastTo(stringType)); Assert.False(intType.CanCastTo(uintType)); Assert.False(uintType.CanCastTo(intType)); } [Fact] public void TestInterfaceCasting() { TypeDesc iFooType = _testModule.GetType("Casting", "IFoo"); TypeDesc classImplementingIFooType = _testModule.GetType("Casting", "ClassImplementingIFoo"); TypeDesc classImplementingIFooIndirectlyType = _testModule.GetType("Casting", "ClassImplementingIFooIndirectly"); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); Assert.True(classImplementingIFooType.CanCastTo(iFooType)); Assert.True(classImplementingIFooIndirectlyType.CanCastTo(iFooType)); Assert.True(iFooType.CanCastTo(objectType)); Assert.False(objectType.CanCastTo(iFooType)); } [Fact] public void TestSameSizeArrayTypeCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc uintType = _context.GetWellKnownType(WellKnownType.UInt32); TypeDesc byteType = _context.GetWellKnownType(WellKnownType.Byte); TypeDesc sbyteType = _context.GetWellKnownType(WellKnownType.SByte); TypeDesc intPtrType = _context.GetWellKnownType(WellKnownType.IntPtr); TypeDesc ulongType = _context.GetWellKnownType(WellKnownType.UInt64); TypeDesc doubleType = _context.GetWellKnownType(WellKnownType.Double); TypeDesc boolType = _context.GetWellKnownType(WellKnownType.Boolean); TypeDesc intBasedEnumType = _testModule.GetType("Casting", "IntBasedEnum"); TypeDesc uintBasedEnumType = _testModule.GetType("Casting", "UIntBasedEnum"); TypeDesc shortBasedEnumType = _testModule.GetType("Casting", "ShortBasedEnum"); Assert.True(intType.MakeArrayType().CanCastTo(uintType.MakeArrayType())); Assert.True(intType.MakeArrayType().CanCastTo(uintType.MakeArrayType(1))); Assert.False(intType.CanCastTo(uintType)); Assert.True(byteType.MakeArrayType().CanCastTo(sbyteType.MakeArrayType())); Assert.False(byteType.CanCastTo(sbyteType)); Assert.False(intPtrType.MakeArrayType().CanCastTo(ulongType.MakeArrayType())); Assert.False(intPtrType.CanCastTo(ulongType)); // These are same size, but not allowed to cast Assert.False(doubleType.MakeArrayType().CanCastTo(ulongType.MakeArrayType())); Assert.False(boolType.MakeArrayType().CanCastTo(byteType.MakeArrayType())); Assert.True(intBasedEnumType.MakeArrayType().CanCastTo(uintType.MakeArrayType())); Assert.True(intBasedEnumType.MakeArrayType().CanCastTo(uintBasedEnumType.MakeArrayType())); Assert.False(shortBasedEnumType.MakeArrayType().CanCastTo(intType.MakeArrayType())); } [Fact] public void TestArrayInterfaceCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); MetadataType iListType = _context.SystemModule.GetType("System.Collections", "IList"); MetadataType iListOfTType = _context.SystemModule.GetType("System.Collections.Generic", "IList`1"); InstantiatedType iListOfIntType = iListOfTType.MakeInstantiatedType(intType); TypeDesc intSzArrayType = intType.MakeArrayType(); TypeDesc intArrayType = intType.MakeArrayType(1); Assert.True(intSzArrayType.CanCastTo(iListOfIntType)); Assert.True(intSzArrayType.CanCastTo(iListType)); Assert.False(intArrayType.CanCastTo(iListOfIntType)); Assert.True(intArrayType.CanCastTo(iListType)); } [Fact] public void TestArrayCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc arrayType = _context.GetWellKnownType(WellKnownType.Array); TypeDesc intSzArrayType = intType.MakeArrayType(); TypeDesc intArray1Type = intType.MakeArrayType(1); TypeDesc intArray2Type = intType.MakeArrayType(2); TypeDesc stringSzArrayType = stringType.MakeArrayType(); TypeDesc objectSzArrayType = objectType.MakeArrayType(); Assert.True(intSzArrayType.CanCastTo(intArray1Type)); Assert.False(intArray1Type.CanCastTo(intSzArrayType)); Assert.False(intArray1Type.CanCastTo(intArray2Type)); Assert.True(intSzArrayType.CanCastTo(arrayType)); Assert.True(intArray1Type.CanCastTo(arrayType)); Assert.True(stringSzArrayType.CanCastTo(objectSzArrayType)); Assert.False(intSzArrayType.CanCastTo(objectSzArrayType)); } [Fact] public void TestGenericParameterCasting() { TypeDesc paramWithNoConstraint = _testModule.GetType("Casting", "ClassWithNoConstraint`1").Instantiation[0]; TypeDesc paramWithValueTypeConstraint = _testModule.GetType("Casting", "ClassWithValueTypeConstraint`1").Instantiation[0]; TypeDesc paramWithInterfaceConstraint = _testModule.GetType("Casting", "ClassWithInterfaceConstraint`1").Instantiation[0]; TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc valueTypeType = _context.GetWellKnownType(WellKnownType.ValueType); TypeDesc iFooType = _testModule.GetType("Casting", "IFoo"); TypeDesc classImplementingIFooType = _testModule.GetType("Casting", "ClassImplementingIFoo"); TypeDesc classImplementingIFooIndirectlyType = _testModule.GetType("Casting", "ClassImplementingIFooIndirectly"); Assert.True(paramWithNoConstraint.CanCastTo(objectType)); Assert.False(paramWithNoConstraint.CanCastTo(valueTypeType)); Assert.False(paramWithNoConstraint.CanCastTo(iFooType)); Assert.False(paramWithNoConstraint.CanCastTo(classImplementingIFooType)); Assert.True(paramWithValueTypeConstraint.CanCastTo(objectType)); Assert.True(paramWithValueTypeConstraint.CanCastTo(valueTypeType)); Assert.False(paramWithValueTypeConstraint.CanCastTo(iFooType)); Assert.False(paramWithValueTypeConstraint.CanCastTo(classImplementingIFooType)); Assert.True(paramWithInterfaceConstraint.CanCastTo(objectType)); Assert.False(paramWithInterfaceConstraint.CanCastTo(valueTypeType)); Assert.True(paramWithInterfaceConstraint.CanCastTo(iFooType)); Assert.False(paramWithInterfaceConstraint.CanCastTo(classImplementingIFooType)); } [Fact] public void TestVariantCasting() { TypeDesc stringType = _context.GetWellKnownType(WellKnownType.String); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); TypeDesc exceptionType = _context.GetWellKnownType(WellKnownType.Exception); TypeDesc stringSzArrayType = stringType.MakeArrayType(); MetadataType iEnumerableOfTType = _context.SystemModule.GetType("System.Collections.Generic", "IEnumerable`1"); InstantiatedType iEnumerableOfObjectType = iEnumerableOfTType.MakeInstantiatedType(objectType); InstantiatedType iEnumerableOfExceptionType = iEnumerableOfTType.MakeInstantiatedType(exceptionType); Assert.True(stringSzArrayType.CanCastTo(iEnumerableOfObjectType)); Assert.False(stringSzArrayType.CanCastTo(iEnumerableOfExceptionType)); MetadataType iContravariantOfTType = _testModule.GetType("Casting", "IContravariant`1"); InstantiatedType iContravariantOfObjectType = iContravariantOfTType.MakeInstantiatedType(objectType); InstantiatedType iEnumerableOfStringType = iEnumerableOfTType.MakeInstantiatedType(stringType); Assert.True(iContravariantOfObjectType.CanCastTo(objectType)); Assert.True(iEnumerableOfStringType.CanCastTo(objectType)); } [Fact] public void TestNullableCasting() { TypeDesc intType = _context.GetWellKnownType(WellKnownType.Int32); MetadataType nullableType = (MetadataType)_context.GetWellKnownType(WellKnownType.Nullable); TypeDesc nullableOfIntType = nullableType.MakeInstantiatedType(intType); Assert.True(intType.CanCastTo(nullableOfIntType)); } [Fact] public void TestGenericParameterArrayCasting() { TypeDesc baseArrayType = _testModule.GetType("Casting", "Base").MakeArrayType(); TypeDesc iFooArrayType = _testModule.GetType("Casting", "IFoo").MakeArrayType(); TypeDesc paramArrayWithBaseClassConstraint = _testModule.GetType("Casting", "ClassWithBaseClassConstraint`1").Instantiation[0].MakeArrayType(); TypeDesc paramArrayWithInterfaceConstraint = _testModule.GetType("Casting", "ClassWithInterfaceConstraint`1").Instantiation[0].MakeArrayType(); Assert.True(paramArrayWithBaseClassConstraint.CanCastTo(baseArrayType)); Assert.False(paramArrayWithInterfaceConstraint.CanCastTo(iFooArrayType)); } [Fact] public void TestRecursiveCanCast() { // Tests the stack overflow protection in CanCastTo TypeDesc classWithRecursiveImplementation = _testModule.GetType("Casting", "ClassWithRecursiveImplementation"); MetadataType iContravariantOfTType = (MetadataType)_testModule.GetType("Casting", "IContravariant`1"); TypeDesc testType = iContravariantOfTType.MakeInstantiatedType(classWithRecursiveImplementation); Assert.False(classWithRecursiveImplementation.CanCastTo(testType)); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/myObjectLongNS.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="http://www.miocrosoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/"> <xsl:template match="/"> <result> 1.<xsl:value-of select="myObj:Fn1()"/> 2.<xsl:value-of select="myObj:Fn2()"/> 3.<xsl:value-of select="myObj:Fn3()"/> </result> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="http://www.miocrosoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/"> <xsl:template match="/"> <result> 1.<xsl:value-of select="myObj:Fn1()"/> 2.<xsl:value-of select="myObj:Fn2()"/> 3.<xsl:value-of select="myObj:Fn3()"/> </result> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Generics/Constraints/Call_instance01_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Call_instance01.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Call_instance01.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/vm/classnames.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef __CLASSNAMES_H__ #define __CLASSNAMES_H__ #include "namespace.h" // These system class names are not assembly qualified. #define g_AppDomainClassName "System.AppDomain" #define g_ArgIteratorName "ArgIterator" #define g_ArrayClassName "System.Array" #define g_NullableName "Nullable`1" #define g_ByReferenceName "ByReference`1" #define g_CollectionsEnumerableItfName "System.Collections.IEnumerable" #define g_CollectionsEnumeratorClassName "System.Collections.IEnumerator" #define g_CollectionsCollectionItfName "System.Collections.ICollection" #define g_CollectionsGenericCollectionItfName "System.Collections.Generic.ICollection`1" #define g_CollectionsGenericReadOnlyCollectionItfName "System.Collections.Generic.IReadOnlyCollection`1" #ifdef FEATURE_COMINTEROP #define g_CorelibAsmName "System.Private.CoreLib" #define g_SystemAsmName "System" #define g_SystemRuntimeAsmName "System.Runtime" #define g_DrawingAsmName "System.Drawing" #define g_ObjectModelAsmName "System.ObjectModel" #define g_ColorClassName "System.Drawing.Color" #define g_ColorTranslatorClassName "System.Drawing.ColorTranslator" #define g_ComObjectName "__ComObject" #endif // FEATURE_COMINTEROP #define g_DateClassName "System.DateTime" #define g_DateTimeOffsetClassName "System.DateTimeOffset" #define g_DecimalClassName "System.Decimal" #define g_Vector64ClassName "System.Runtime.Intrinsics.Vector64`1" #define g_Vector64Name "Vector64`1" #define g_Vector128ClassName "System.Runtime.Intrinsics.Vector128`1" #define g_Vector128Name "Vector128`1" #define g_Vector256ClassName "System.Runtime.Intrinsics.Vector256`1" #define g_Vector256Name "Vector256`1" #define g_EnumeratorToEnumClassName "System.Runtime.InteropServices.CustomMarshalers.EnumeratorToEnumVariantMarshaler" #define g_ExceptionClassName "System.Exception" #define g_ExecutionEngineExceptionClassName "System.ExecutionEngineException" #define g_ThreadStaticAttributeClassName "System.ThreadStaticAttribute" #define g_TypeIdentifierAttributeClassName "System.Runtime.InteropServices.TypeIdentifierAttribute" #define g_ObjectClassName "System.Object" #define g_ObjectName "Object" #define g_OutOfMemoryExceptionClassName "System.OutOfMemoryException" #define g_ReflectionClassName "System.RuntimeType" #define g_ReflectionConstructorName "System.Reflection.RuntimeConstructorInfo" #define g_ReflectionEventInfoName "System.Reflection.EventInfo" #define g_ReflectionEventName "System.Reflection.RuntimeEventInfo" #define g_CMExpandoToDispatchExMarshaler "System.Runtime.InteropServices.CustomMarshalers.ExpandoToDispatchExMarshaler" #define g_CMExpandoViewOfDispatchEx "System.Runtime.InteropServices.CustomMarshalers.ExpandoViewOfDispatchEx" #define g_ReflectionFieldName "System.Reflection.RuntimeFieldInfo" #define g_ReflectionMemberInfoName "System.Reflection.MemberInfo" #define g_MethodBaseName "System.Reflection.MethodBase" #define g_ReflectionFieldInfoName "System.Reflection.FieldInfo" #define g_ReflectionPropertyInfoName "System.Reflection.PropertyInfo" #define g_ReflectionConstructorInfoName "System.Reflection.ConstructorInfo" #define g_ReflectionMethodInfoName "System.Reflection.MethodInfo" #define g_ReflectionMethodName "System.Reflection.RuntimeMethodInfo" #define g_ReflectionMethodInterfaceName "System.IRuntimeMethodInfo" #define g_ReflectionAssemblyName "System.Reflection.RuntimeAssembly" #define g_ReflectionModuleName "System.Reflection.RuntimeModule" #define g_ReflectionParamInfoName "System.Reflection.ParameterInfo" #define g_ReflectionParamName "System.Reflection.RuntimeParameterInfo" #define g_ReflectionPropInfoName "System.Reflection.RuntimePropertyInfo" #define g_ReflectionReflectItfName "System.Reflection.IReflect" #define g_RuntimeArgumentHandleName "RuntimeArgumentHandle" #define g_RuntimeFieldHandleClassName "System.RuntimeFieldHandle" #define g_RuntimeFieldHandleInternalName "RuntimeFieldHandleInternal" #define g_RuntimeMethodHandleClassName "System.RuntimeMethodHandle" #define g_RuntimeMethodHandleInternalName "RuntimeMethodHandleInternal" #define g_RuntimeTypeHandleClassName "System.RuntimeTypeHandle" #define g_StackOverflowExceptionClassName "System.StackOverflowException" #define g_StringBufferClassName "System.Text.StringBuilder" #define g_StringBufferName "StringBuilder" #define g_StringClassName "System.String" #define g_StringName "String" #define g_ThreadClassName "System.Threading.Thread" #define g_TypeClassName "System.Type" #define g_VariantClassName "System.Variant" #define g_GuidClassName "System.Guid" #define g_CompilerServicesFixedAddressValueTypeAttribute "System.Runtime.CompilerServices.FixedAddressValueTypeAttribute" #define g_CompilerServicesUnsafeValueTypeAttribute "System.Runtime.CompilerServices.UnsafeValueTypeAttribute" #define g_CompilerServicesIsByRefLikeAttribute "System.Runtime.CompilerServices.IsByRefLikeAttribute" #define g_CompilerServicesIntrinsicAttribute "System.Runtime.CompilerServices.IntrinsicAttribute" #define g_UnmanagedFunctionPointerAttribute "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute" #define g_DefaultDllImportSearchPathsAttribute "System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute" #define g_UnmanagedCallersOnlyAttribute "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute" #define g_FixedBufferAttribute "System.Runtime.CompilerServices.FixedBufferAttribute" #define g_CompilerServicesTypeDependencyAttribute "System.Runtime.CompilerServices.TypeDependencyAttribute" #define g_ReferenceAssemblyAttribute "System.Runtime.CompilerServices.ReferenceAssemblyAttribute" #define g_CriticalFinalizerObjectName "CriticalFinalizerObject" #define g_DisableRuntimeMarshallingAttribute "System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute" #endif //!__CLASSNAMES_H__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #ifndef __CLASSNAMES_H__ #define __CLASSNAMES_H__ #include "namespace.h" // These system class names are not assembly qualified. #define g_AppDomainClassName "System.AppDomain" #define g_ArgIteratorName "ArgIterator" #define g_ArrayClassName "System.Array" #define g_NullableName "Nullable`1" #define g_ByReferenceName "ByReference`1" #define g_CollectionsEnumerableItfName "System.Collections.IEnumerable" #define g_CollectionsEnumeratorClassName "System.Collections.IEnumerator" #define g_CollectionsCollectionItfName "System.Collections.ICollection" #define g_CollectionsGenericCollectionItfName "System.Collections.Generic.ICollection`1" #define g_CollectionsGenericReadOnlyCollectionItfName "System.Collections.Generic.IReadOnlyCollection`1" #ifdef FEATURE_COMINTEROP #define g_CorelibAsmName "System.Private.CoreLib" #define g_SystemAsmName "System" #define g_SystemRuntimeAsmName "System.Runtime" #define g_DrawingAsmName "System.Drawing" #define g_ObjectModelAsmName "System.ObjectModel" #define g_ColorClassName "System.Drawing.Color" #define g_ColorTranslatorClassName "System.Drawing.ColorTranslator" #define g_ComObjectName "__ComObject" #endif // FEATURE_COMINTEROP #define g_DateClassName "System.DateTime" #define g_DateTimeOffsetClassName "System.DateTimeOffset" #define g_DecimalClassName "System.Decimal" #define g_Vector64ClassName "System.Runtime.Intrinsics.Vector64`1" #define g_Vector64Name "Vector64`1" #define g_Vector128ClassName "System.Runtime.Intrinsics.Vector128`1" #define g_Vector128Name "Vector128`1" #define g_Vector256ClassName "System.Runtime.Intrinsics.Vector256`1" #define g_Vector256Name "Vector256`1" #define g_EnumeratorToEnumClassName "System.Runtime.InteropServices.CustomMarshalers.EnumeratorToEnumVariantMarshaler" #define g_ExceptionClassName "System.Exception" #define g_ExecutionEngineExceptionClassName "System.ExecutionEngineException" #define g_ThreadStaticAttributeClassName "System.ThreadStaticAttribute" #define g_TypeIdentifierAttributeClassName "System.Runtime.InteropServices.TypeIdentifierAttribute" #define g_ObjectClassName "System.Object" #define g_ObjectName "Object" #define g_OutOfMemoryExceptionClassName "System.OutOfMemoryException" #define g_ReflectionClassName "System.RuntimeType" #define g_ReflectionConstructorName "System.Reflection.RuntimeConstructorInfo" #define g_ReflectionEventInfoName "System.Reflection.EventInfo" #define g_ReflectionEventName "System.Reflection.RuntimeEventInfo" #define g_CMExpandoToDispatchExMarshaler "System.Runtime.InteropServices.CustomMarshalers.ExpandoToDispatchExMarshaler" #define g_CMExpandoViewOfDispatchEx "System.Runtime.InteropServices.CustomMarshalers.ExpandoViewOfDispatchEx" #define g_ReflectionFieldName "System.Reflection.RuntimeFieldInfo" #define g_ReflectionMemberInfoName "System.Reflection.MemberInfo" #define g_MethodBaseName "System.Reflection.MethodBase" #define g_ReflectionFieldInfoName "System.Reflection.FieldInfo" #define g_ReflectionPropertyInfoName "System.Reflection.PropertyInfo" #define g_ReflectionConstructorInfoName "System.Reflection.ConstructorInfo" #define g_ReflectionMethodInfoName "System.Reflection.MethodInfo" #define g_ReflectionMethodName "System.Reflection.RuntimeMethodInfo" #define g_ReflectionMethodInterfaceName "System.IRuntimeMethodInfo" #define g_ReflectionAssemblyName "System.Reflection.RuntimeAssembly" #define g_ReflectionModuleName "System.Reflection.RuntimeModule" #define g_ReflectionParamInfoName "System.Reflection.ParameterInfo" #define g_ReflectionParamName "System.Reflection.RuntimeParameterInfo" #define g_ReflectionPropInfoName "System.Reflection.RuntimePropertyInfo" #define g_ReflectionReflectItfName "System.Reflection.IReflect" #define g_RuntimeArgumentHandleName "RuntimeArgumentHandle" #define g_RuntimeFieldHandleClassName "System.RuntimeFieldHandle" #define g_RuntimeFieldHandleInternalName "RuntimeFieldHandleInternal" #define g_RuntimeMethodHandleClassName "System.RuntimeMethodHandle" #define g_RuntimeMethodHandleInternalName "RuntimeMethodHandleInternal" #define g_RuntimeTypeHandleClassName "System.RuntimeTypeHandle" #define g_StackOverflowExceptionClassName "System.StackOverflowException" #define g_StringBufferClassName "System.Text.StringBuilder" #define g_StringBufferName "StringBuilder" #define g_StringClassName "System.String" #define g_StringName "String" #define g_ThreadClassName "System.Threading.Thread" #define g_TypeClassName "System.Type" #define g_VariantClassName "System.Variant" #define g_GuidClassName "System.Guid" #define g_CompilerServicesFixedAddressValueTypeAttribute "System.Runtime.CompilerServices.FixedAddressValueTypeAttribute" #define g_CompilerServicesUnsafeValueTypeAttribute "System.Runtime.CompilerServices.UnsafeValueTypeAttribute" #define g_CompilerServicesIsByRefLikeAttribute "System.Runtime.CompilerServices.IsByRefLikeAttribute" #define g_CompilerServicesIntrinsicAttribute "System.Runtime.CompilerServices.IntrinsicAttribute" #define g_UnmanagedFunctionPointerAttribute "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute" #define g_DefaultDllImportSearchPathsAttribute "System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute" #define g_UnmanagedCallersOnlyAttribute "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute" #define g_FixedBufferAttribute "System.Runtime.CompilerServices.FixedBufferAttribute" #define g_CompilerServicesTypeDependencyAttribute "System.Runtime.CompilerServices.TypeDependencyAttribute" #define g_ReferenceAssemblyAttribute "System.Runtime.CompilerServices.ReferenceAssemblyAttribute" #define g_CriticalFinalizerObjectName "CriticalFinalizerObject" #define g_DisableRuntimeMarshallingAttribute "System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute" #endif //!__CLASSNAMES_H__
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightAndInsert.Vector64.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightAndInsert_Vector64_Int32() { var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 testClass) { var result = AdvSimd.ShiftRightAndInsert(_fld1, _fld2, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte Imm = 16; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightAndInsert( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightAndInsert), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightAndInsert), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightAndInsert( _clsVar1, _clsVar2, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightAndInsert(op1, op2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightAndInsert(op1, op2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); var result = AdvSimd.ShiftRightAndInsert(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightAndInsert(_fld1, _fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightAndInsert(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector64<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightAndInsert(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightAndInsert)}<Int32>(Vector64<Int32>, Vector64<Int32>, 16): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightAndInsert_Vector64_Int32() { var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 testClass) { var result = AdvSimd.ShiftRightAndInsert(_fld1, _fld2, 16); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte Imm = 16; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightAndInsert( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightAndInsert), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightAndInsert), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), (byte)16 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightAndInsert( _clsVar1, _clsVar2, 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightAndInsert(op1, op2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightAndInsert(op1, op2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); var result = AdvSimd.ShiftRightAndInsert(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightAndInsert_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightAndInsert(_fld1, _fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightAndInsert(test._fld1, test._fld2, 16); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightAndInsert( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), 16 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector64<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightAndInsert(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightAndInsert)}<Int32>(Vector64<Int32>, Vector64<Int32>, 16): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/BitwiseSelect.Vector128.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseSelect_Vector128_Int32() { var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 testClass) { var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseSelect( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), AdvSimd.LoadVector128((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) fixed (Vector128<Int32>* pFld3 = &test._fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), AdvSimd.LoadVector128((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.BitwiseSelect(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseSelect)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void BitwiseSelect_Vector128_Int32() { var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 testClass) { var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.BitwiseSelect( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.BitwiseSelect), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.BitwiseSelect( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), AdvSimd.LoadVector128((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.BitwiseSelect(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__BitwiseSelect_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) fixed (Vector128<Int32>* pFld3 = &test._fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.BitwiseSelect(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.BitwiseSelect( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), AdvSimd.LoadVector128((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.BitwiseSelect(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseSelect)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.ComponentModel.EventBasedAsync/tests/BackgroundWorkerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync.Tests { public class BackgroundWorkerTests { private const int TimeoutShort = 300; private const int TimeoutLong = 30000; [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestBackgroundWorkerBasic() { var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const int expectedResult = 42; const int expectedReportCallsCount = 5; int actualReportCallsCount = 0; var worker = new BackgroundWorker() { WorkerReportsProgress = true }; var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount); var workerCompletedEvent = new ManualResetEventSlim(false); worker.DoWork += (sender, e) => { for (int i = 0; i < expectedReportCallsCount; i++) { worker.ReportProgress(i); progressBarrier.SignalAndWait(); } e.Result = expectedResult; }; worker.RunWorkerCompleted += (sender, e) => { try { Assert.Equal(expectedResult, (int)e.Result); Assert.False(worker.IsBusy); } finally { workerCompletedEvent.Set(); } }; worker.ProgressChanged += (sender, e) => { progressBarrier.SignalAndWait(); }; worker.RunWorkerAsync(); // wait for signal from WhenRunWorkerCompleted Assert.True(workerCompletedEvent.Wait(TimeoutLong)); Assert.False(worker.IsBusy); Assert.Equal(expectedReportCallsCount, actualReportCallsCount); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task RunWorkerAsync_NoOnWorkHandler_SetsResultToNull() { var tcs = new TaskCompletionSource(); var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; backgroundWorker.RunWorkerCompleted += (sender, e) => { Assert.Null(e.Result); Assert.False(backgroundWorker.IsBusy); tcs.SetResult(); }; backgroundWorker.RunWorkerAsync(); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(10)); // Usually takes 100th of a sec } #region TestCancelAsync private ManualResetEventSlim manualResetEvent3; [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestCancelAsync() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoWorkExpectCancel; bw.WorkerSupportsCancellation = true; manualResetEvent3 = new ManualResetEventSlim(false); bw.RunWorkerAsync("Message"); bw.CancelAsync(); bool ret = manualResetEvent3.Wait(TimeoutLong); Assert.True(ret); // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false // if it is completed already, we don't check cancellation if (bw.IsBusy) // not complete { if (!bw.CancellationPending) { for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } } // Check again if (bw.IsBusy) Assert.True(bw.CancellationPending, "Cancellation in Main thread"); } } private void DoWorkExpectCancel(object sender, DoWorkEventArgs e) { Assert.Equal("Message", e.Argument); var bw = sender as BackgroundWorker; if (bw.CancellationPending) { manualResetEvent3.Set(); return; } // we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } Assert.True(bw.CancellationPending, "Cancellation in Worker thread"); // signal no matter what, even if it's not cancelled by now manualResetEvent3.Set(); } #endregion [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestThrowExceptionInDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const string expectedArgument = "Exception"; const string expectedExceptionMsg = "Exception from DoWork"; var bw = new BackgroundWorker(); var workerCompletedEvent = new ManualResetEventSlim(false); bw.DoWork += (sender, e) => { Assert.Same(bw, sender); Assert.Same(expectedArgument, e.Argument); throw new TestException(expectedExceptionMsg); }; bw.RunWorkerCompleted += (sender, e) => { try { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => e.Result); Assert.True(ex.InnerException is TestException); Assert.Equal(expectedExceptionMsg, ex.InnerException.Message); } finally { workerCompletedEvent.Set(); } }; bw.RunWorkerAsync(expectedArgument); Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void CtorTest() { var bw = new BackgroundWorker(); Assert.False(bw.IsBusy); Assert.False(bw.WorkerReportsProgress); Assert.False(bw.WorkerSupportsCancellation); Assert.False(bw.CancellationPending); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void RunWorkerAsyncTwice() { var bw = new BackgroundWorker(); var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); try { Assert.True(bw.IsBusy); Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync()); } finally { barrier.SignalAndWait(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestCancelInsideDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); var bw = new BackgroundWorker() { WorkerSupportsCancellation = true }; var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); if (bw.CancellationPending) { e.Cancel = true; } }; bw.RunWorkerCompleted += (sender, e) => { Assert.True(e.Cancelled); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); bw.CancelAsync(); barrier.SignalAndWait(); Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void TestCancelAsyncWithoutCancellationSupport() { var bw = new BackgroundWorker() { WorkerSupportsCancellation = false }; Assert.Throws<InvalidOperationException>(() => bw.CancelAsync()); } [Fact] public void TestReportProgressSync() { var bw = new BackgroundWorker() { WorkerReportsProgress = true }; var expectedProgress = new int[] { 1, 2, 3, 4, 5 }; var actualProgress = new List<int>(); bw.ProgressChanged += (sender, e) => { actualProgress.Add(e.ProgressPercentage); }; foreach (int i in expectedProgress) { bw.ReportProgress(i); } Assert.Equal(expectedProgress, actualProgress); } [Fact] public void ReportProgress_NoProgressHandle_Nop() { var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; foreach (int i in new int[] { 1, 2, 3, 4, 5 }) { backgroundWorker.ReportProgress(i); } } [Fact] public void TestReportProgressWithWorkerReportsProgressFalse() { var bw = new BackgroundWorker() { WorkerReportsProgress = false }; Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42)); } [Fact] public void DisposeTwiceShouldNotThrow() { var bw = new BackgroundWorker(); bw.Dispose(); bw.Dispose(); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))] public void TestFinalization() { // BackgroundWorker has a finalizer that exists purely for backwards compatibility // with existing code that may override Dispose to clean up native resources. // https://github.com/dotnet/corefx/pull/752 ManualResetEventSlim mres = SetEventWhenFinalizedBackgroundWorker.CreateAndThrowAway(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(mres.Wait(10000)); } private sealed class SetEventWhenFinalizedBackgroundWorker : BackgroundWorker { private ManualResetEventSlim _setWhenFinalized; internal static ManualResetEventSlim CreateAndThrowAway() { var mres = new ManualResetEventSlim(); new SetEventWhenFinalizedBackgroundWorker() { _setWhenFinalized = mres }; return mres; } protected override void Dispose(bool disposing) { _setWhenFinalized.Set(); } } private static void Wait(int milliseconds) { Task.Delay(milliseconds).Wait(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync.Tests { public class BackgroundWorkerTests { private const int TimeoutShort = 300; private const int TimeoutLong = 30000; [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestBackgroundWorkerBasic() { var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const int expectedResult = 42; const int expectedReportCallsCount = 5; int actualReportCallsCount = 0; var worker = new BackgroundWorker() { WorkerReportsProgress = true }; var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount); var workerCompletedEvent = new ManualResetEventSlim(false); worker.DoWork += (sender, e) => { for (int i = 0; i < expectedReportCallsCount; i++) { worker.ReportProgress(i); progressBarrier.SignalAndWait(); } e.Result = expectedResult; }; worker.RunWorkerCompleted += (sender, e) => { try { Assert.Equal(expectedResult, (int)e.Result); Assert.False(worker.IsBusy); } finally { workerCompletedEvent.Set(); } }; worker.ProgressChanged += (sender, e) => { progressBarrier.SignalAndWait(); }; worker.RunWorkerAsync(); // wait for signal from WhenRunWorkerCompleted Assert.True(workerCompletedEvent.Wait(TimeoutLong)); Assert.False(worker.IsBusy); Assert.Equal(expectedReportCallsCount, actualReportCallsCount); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task RunWorkerAsync_NoOnWorkHandler_SetsResultToNull() { var tcs = new TaskCompletionSource(); var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; backgroundWorker.RunWorkerCompleted += (sender, e) => { Assert.Null(e.Result); Assert.False(backgroundWorker.IsBusy); tcs.SetResult(); }; backgroundWorker.RunWorkerAsync(); await tcs.Task.WaitAsync(TimeSpan.FromSeconds(10)); // Usually takes 100th of a sec } #region TestCancelAsync private ManualResetEventSlim manualResetEvent3; [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestCancelAsync() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoWorkExpectCancel; bw.WorkerSupportsCancellation = true; manualResetEvent3 = new ManualResetEventSlim(false); bw.RunWorkerAsync("Message"); bw.CancelAsync(); bool ret = manualResetEvent3.Wait(TimeoutLong); Assert.True(ret); // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false // if it is completed already, we don't check cancellation if (bw.IsBusy) // not complete { if (!bw.CancellationPending) { for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } } // Check again if (bw.IsBusy) Assert.True(bw.CancellationPending, "Cancellation in Main thread"); } } private void DoWorkExpectCancel(object sender, DoWorkEventArgs e) { Assert.Equal("Message", e.Argument); var bw = sender as BackgroundWorker; if (bw.CancellationPending) { manualResetEvent3.Set(); return; } // we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } Assert.True(bw.CancellationPending, "Cancellation in Worker thread"); // signal no matter what, even if it's not cancelled by now manualResetEvent3.Set(); } #endregion [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestThrowExceptionInDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const string expectedArgument = "Exception"; const string expectedExceptionMsg = "Exception from DoWork"; var bw = new BackgroundWorker(); var workerCompletedEvent = new ManualResetEventSlim(false); bw.DoWork += (sender, e) => { Assert.Same(bw, sender); Assert.Same(expectedArgument, e.Argument); throw new TestException(expectedExceptionMsg); }; bw.RunWorkerCompleted += (sender, e) => { try { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => e.Result); Assert.True(ex.InnerException is TestException); Assert.Equal(expectedExceptionMsg, ex.InnerException.Message); } finally { workerCompletedEvent.Set(); } }; bw.RunWorkerAsync(expectedArgument); Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void CtorTest() { var bw = new BackgroundWorker(); Assert.False(bw.IsBusy); Assert.False(bw.WorkerReportsProgress); Assert.False(bw.WorkerSupportsCancellation); Assert.False(bw.CancellationPending); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void RunWorkerAsyncTwice() { var bw = new BackgroundWorker(); var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); try { Assert.True(bw.IsBusy); Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync()); } finally { barrier.SignalAndWait(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void TestCancelInsideDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); var bw = new BackgroundWorker() { WorkerSupportsCancellation = true }; var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); if (bw.CancellationPending) { e.Cancel = true; } }; bw.RunWorkerCompleted += (sender, e) => { Assert.True(e.Cancelled); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); bw.CancelAsync(); barrier.SignalAndWait(); Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void TestCancelAsyncWithoutCancellationSupport() { var bw = new BackgroundWorker() { WorkerSupportsCancellation = false }; Assert.Throws<InvalidOperationException>(() => bw.CancelAsync()); } [Fact] public void TestReportProgressSync() { var bw = new BackgroundWorker() { WorkerReportsProgress = true }; var expectedProgress = new int[] { 1, 2, 3, 4, 5 }; var actualProgress = new List<int>(); bw.ProgressChanged += (sender, e) => { actualProgress.Add(e.ProgressPercentage); }; foreach (int i in expectedProgress) { bw.ReportProgress(i); } Assert.Equal(expectedProgress, actualProgress); } [Fact] public void ReportProgress_NoProgressHandle_Nop() { var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; foreach (int i in new int[] { 1, 2, 3, 4, 5 }) { backgroundWorker.ReportProgress(i); } } [Fact] public void TestReportProgressWithWorkerReportsProgressFalse() { var bw = new BackgroundWorker() { WorkerReportsProgress = false }; Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42)); } [Fact] public void DisposeTwiceShouldNotThrow() { var bw = new BackgroundWorker(); bw.Dispose(); bw.Dispose(); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))] public void TestFinalization() { // BackgroundWorker has a finalizer that exists purely for backwards compatibility // with existing code that may override Dispose to clean up native resources. // https://github.com/dotnet/corefx/pull/752 ManualResetEventSlim mres = SetEventWhenFinalizedBackgroundWorker.CreateAndThrowAway(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(mres.Wait(10000)); } private sealed class SetEventWhenFinalizedBackgroundWorker : BackgroundWorker { private ManualResetEventSlim _setWhenFinalized; internal static ManualResetEventSlim CreateAndThrowAway() { var mres = new ManualResetEventSlim(); new SetEventWhenFinalizedBackgroundWorker() { _setWhenFinalized = mres }; return mres; } protected override void Dispose(bool disposing) { _setWhenFinalized.Set(); } } private static void Wait(int milliseconds) { Task.Delay(milliseconds).Wait(); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/content-xhtml-escaped.xml
<!-- Description: xhtml content value containing only escaped html produces a warning Expect: NotInline{parent:entry,element:content} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Some &lt;b&gt;bold&lt;/b&gt; text.</div></content> </entry> </feed>
<!-- Description: xhtml content value containing only escaped html produces a warning Expect: NotInline{parent:entry,element:content} --> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://contoso.com/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>Author Name</name> </author> <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> <entry> <title>Atom-Powered Robots Run Amok</title> <link href="http://contoso.com/2003/12/13/atom03"/> <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> <updated>2003-12-13T18:30:02Z</updated> <summary>Some text.</summary> <content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">Some &lt;b&gt;bold&lt;/b&gt; text.</div></content> </entry> </feed>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Methodical/Invoke/SEH/catchfinally_ind_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="catchfinally_ind.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="catchfinally_ind.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/JitBlue/GitHub_16210/GitHub_16210_3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public struct float4 { public float4(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } public float x; public float y; public float z; public float w; } class X { [MethodImpl(MethodImplOptions.NoInlining)] public static float P(int i) { var test = new float4(5, 4, 3, 2); ref float p = ref test.x; Console.WriteLine(p); return Unsafe.Add(ref p, i); } public static int Main() { float v0 = P(0); float v1 = P(1); float v2 = P(2); float v3 = P(3); Console.WriteLine($"v0={v0} v1={v1} v2={v2} v3={v3}"); bool ok = (v0 == 5 && v1 == 4 && v2 == 3 && v3 == 2); return (ok ? 100 : 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; public struct float4 { public float4(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } public float x; public float y; public float z; public float w; } class X { [MethodImpl(MethodImplOptions.NoInlining)] public static float P(int i) { var test = new float4(5, 4, 3, 2); ref float p = ref test.x; Console.WriteLine(p); return Unsafe.Add(ref p, i); } public static int Main() { float v0 = P(0); float v1 = P(1); float v2 = P(2); float v3 = P(3); Console.WriteLine($"v0={v0} v1={v1} v2={v2} v3={v3}"); bool ok = (v0 == 5 && v1 == 4 && v2 == 3 && v3 == 2); return (ok ? 100 : 0); } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/sft47.xsl
<xsl:stylesheet version= '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' > <xsl:template match="/"> <xsl:for-each select="//foo"> <xsl:value-of select="."/> </xsl:for-each> </xsl:template> </xsl:stylesheet>
<xsl:stylesheet version= '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' > <xsl:template match="/"> <xsl:for-each select="//foo"> <xsl:value-of select="."/> </xsl:for-each> </xsl:template> </xsl:stylesheet>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Globalization.Calendars/tests/KoreanCalendar/KoreanCalendarGetDayOfYear.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class KoreanCalendarGetDayOfYear { private static readonly RandomDataGenerator s_randomDataGenerator = new RandomDataGenerator(); public static IEnumerable<object[]> GetDayOfYear_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { DateTime.MaxValue }; yield return new object[] { new DateTime(2000, 2, 20) }; yield return new object[] { s_randomDataGenerator.GetDateTime(-55) }; } [Theory] [MemberData(nameof(GetDayOfYear_TestData))] public void GetDayOfYear(DateTime time) { Assert.Equal(new GregorianCalendar().GetDayOfYear(time), new KoreanCalendar().GetDayOfYear(time)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class KoreanCalendarGetDayOfYear { private static readonly RandomDataGenerator s_randomDataGenerator = new RandomDataGenerator(); public static IEnumerable<object[]> GetDayOfYear_TestData() { yield return new object[] { DateTime.MinValue }; yield return new object[] { DateTime.MaxValue }; yield return new object[] { new DateTime(2000, 2, 20) }; yield return new object[] { s_randomDataGenerator.GetDateTime(-55) }; } [Theory] [MemberData(nameof(GetDayOfYear_TestData))] public void GetDayOfYear(DateTime time) { Assert.Equal(new GregorianCalendar().GetDayOfYear(time), new KoreanCalendar().GetDayOfYear(time)); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackFrameExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics { public static partial class StackFrameExtensions { public static bool HasNativeImage(this StackFrame stackFrame) { return stackFrame.GetNativeImageBase() != IntPtr.Zero; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "StackFrame.GetMethod is used to establish if method is available.")] public static bool HasMethod(this StackFrame stackFrame) { return stackFrame.GetMethod() != null; } public static bool HasILOffset(this StackFrame stackFrame) { return stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN; } public static bool HasSource(this StackFrame stackFrame) { return stackFrame.GetFileName() != null; } public static IntPtr GetNativeIP(this StackFrame stackFrame) { return IntPtr.Zero; } public static IntPtr GetNativeImageBase(this StackFrame stackFrame) { return IntPtr.Zero; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics { public static partial class StackFrameExtensions { public static bool HasNativeImage(this StackFrame stackFrame) { return stackFrame.GetNativeImageBase() != IntPtr.Zero; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "StackFrame.GetMethod is used to establish if method is available.")] public static bool HasMethod(this StackFrame stackFrame) { return stackFrame.GetMethod() != null; } public static bool HasILOffset(this StackFrame stackFrame) { return stackFrame.GetILOffset() != StackFrame.OFFSET_UNKNOWN; } public static bool HasSource(this StackFrame stackFrame) { return stackFrame.GetFileName() != null; } public static IntPtr GetNativeIP(this StackFrame stackFrame) { return IntPtr.Zero; } public static IntPtr GetNativeImageBase(this StackFrame stackFrame) { return IntPtr.Zero; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/CompareEqual.Vector64.UInt16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void CompareEqual_Vector64_UInt16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 testClass) { var result = AdvSimd.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 testClass) { fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.CompareEqual( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = AdvSimd.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); var result = AdvSimd.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt16> op1, Vector64<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.CompareEqual(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareEqual)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void CompareEqual_Vector64_UInt16() { var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt16> _fld1; public Vector64<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 testClass) { var result = AdvSimd.CompareEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareEqual_Vector64_UInt16 testClass) { fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector64<UInt16> _clsVar1; private static Vector64<UInt16> _clsVar2; private Vector64<UInt16> _fld1; private Vector64<UInt16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareEqual_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleBinaryOpTest__CompareEqual_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.CompareEqual( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.CompareEqual), new Type[] { typeof(Vector64<UInt16>), typeof(Vector64<UInt16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var result = AdvSimd.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.CompareEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); var result = AdvSimd.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareEqual_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) { var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.CompareEqual( AdvSimd.LoadVector64((UInt16*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<UInt16> op1, Vector64<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.CompareEqual(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.CompareEqual)}<UInt16>(Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/MultiplyScalar.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyScalarDouble() { var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyScalarDouble testClass) { var result = Sse2.MultiplyScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MultiplyScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.MultiplyScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.MultiplyScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.MultiplyScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); var result = Sse2.MultiplyScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.MultiplyScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.MultiplyScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] * right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MultiplyScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MultiplyScalarDouble() { var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyScalarDouble testClass) { var result = Sse2.MultiplyScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MultiplyScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.MultiplyScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.MultiplyScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MultiplyScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.MultiplyScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MultiplyScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); var result = Sse2.MultiplyScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.MultiplyScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.MultiplyScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.MultiplyScalar( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] * right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MultiplyScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Net.Quic/tests/FunctionalTests/QuicTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Net.Quic.Implementations; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using System.Diagnostics.Tracing; using System.Net.Sockets; namespace System.Net.Quic.Tests { public abstract class QuicTestBase<T> where T : IQuicImplProviderFactory, new() { private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); private static readonly IQuicImplProviderFactory s_factory = new T(); public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider(); public static bool IsSupported => ImplementationProvider.IsSupported; public static bool IsMockProvider => typeof(T) == typeof(MockProviderFactory); public static bool IsMsQuicProvider => typeof(T) == typeof(MsQuicProviderFactory); public static SslApplicationProtocol ApplicationProtocol { get; } = new SslApplicationProtocol("quictest"); public X509Certificate2 ServerCertificate = System.Net.Test.Common.Configuration.Certificates.GetServerCertificate(); public X509Certificate2 ClientCertificate = System.Net.Test.Common.Configuration.Certificates.GetClientCertificate(); public ITestOutputHelper _output; public const int PassingTestTimeoutMilliseconds = 4 * 60 * 1000; public static TimeSpan PassingTestTimeout => TimeSpan.FromMilliseconds(PassingTestTimeoutMilliseconds); public QuicTestBase(ITestOutputHelper output) { _output = output; } public bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) { Assert.Equal(ServerCertificate.GetCertHash(), certificate?.GetCertHash()); return true; } public SslServerAuthenticationOptions GetSslServerAuthenticationOptions() { return new SslServerAuthenticationOptions() { ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol }, ServerCertificate = ServerCertificate }; } public SslClientAuthenticationOptions GetSslClientAuthenticationOptions() { return new SslClientAuthenticationOptions() { ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol }, RemoteCertificateValidationCallback = RemoteCertificateValidationCallback, TargetHost = "localhost" }; } public QuicClientConnectionOptions CreateQuicClientOptions() { return new QuicClientConnectionOptions() { ClientAuthenticationOptions = GetSslClientAuthenticationOptions() }; } internal QuicConnection CreateQuicConnection(IPEndPoint endpoint) { return new QuicConnection(ImplementationProvider, endpoint, GetSslClientAuthenticationOptions()); } internal QuicConnection CreateQuicConnection(QuicClientConnectionOptions clientOptions) { return new QuicConnection(ImplementationProvider, clientOptions); } internal QuicListenerOptions CreateQuicListenerOptions() { return new QuicListenerOptions() { ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0), ServerAuthenticationOptions = GetSslServerAuthenticationOptions() }; } internal QuicListener CreateQuicListener(int maxUnidirectionalStreams = 100, int maxBidirectionalStreams = 100) { var options = CreateQuicListenerOptions(); options.MaxUnidirectionalStreams = maxUnidirectionalStreams; options.MaxBidirectionalStreams = maxBidirectionalStreams; return CreateQuicListener(options); } internal QuicListener CreateQuicListener(IPEndPoint endpoint) { var options = new QuicListenerOptions() { ListenEndPoint = endpoint, ServerAuthenticationOptions = GetSslServerAuthenticationOptions() }; return CreateQuicListener(options); } private QuicListener CreateQuicListener(QuicListenerOptions options) => new QuicListener(ImplementationProvider, options); internal Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicListener listener) => CreateConnectedQuicConnection(null, listener); internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions, QuicListenerOptions listenerOptions) { using (QuicListener listener = CreateQuicListener(listenerOptions)) { clientOptions ??= new QuicClientConnectionOptions() { ClientAuthenticationOptions = GetSslClientAuthenticationOptions() }; clientOptions.RemoteEndPoint = listener.ListenEndPoint; return await CreateConnectedQuicConnection(clientOptions, listener); } } internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions = null, QuicListener? listener = null) { int retry = 3; int delay = 25; bool disposeListener = false; if (listener == null) { listener = CreateQuicListener(); disposeListener = true; } clientOptions ??= CreateQuicClientOptions(); if (clientOptions.RemoteEndPoint == null) { clientOptions.RemoteEndPoint = listener.ListenEndPoint; } QuicConnection clientConnection = null; ValueTask<QuicConnection> serverTask = listener.AcceptConnectionAsync(); while (retry > 0) { clientConnection = CreateQuicConnection(clientOptions); retry--; try { await clientConnection.ConnectAsync().ConfigureAwait(false); break; } catch (QuicException ex) when (ex.HResult == (int)SocketError.ConnectionRefused) { _output.WriteLine($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}"); await Task.Delay(delay); delay *= 2; if (retry == 0) { Debug.Fail($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}"); throw ex; } } } QuicConnection serverConnection = await serverTask.ConfigureAwait(false); if (disposeListener) { listener.Dispose(); } Assert.True(serverConnection.Connected); Assert.True(clientConnection.Connected); return (clientConnection, serverTask.Result); } internal async Task PingPong(QuicConnection client, QuicConnection server) { using QuicStream clientStream = client.OpenBidirectionalStream(); ValueTask t = clientStream.WriteAsync(s_ping); using QuicStream serverStream = await server.AcceptStreamAsync(); byte[] buffer = new byte[s_ping.Length]; int remains = s_ping.Length; while (remains > 0) { int readLength = await serverStream.ReadAsync(buffer, buffer.Length - remains, remains); Assert.True(readLength > 0); remains -= readLength; } Assert.Equal(s_ping, buffer); await t; t = serverStream.WriteAsync(s_pong); remains = s_pong.Length; while (remains > 0) { int readLength = await clientStream.ReadAsync(buffer, buffer.Length - remains, remains); Assert.True(readLength > 0); remains -= readLength; } Assert.Equal(s_pong, buffer); await t; } internal async Task RunClientServer(Func<QuicConnection, Task> clientFunction, Func<QuicConnection, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds, QuicListenerOptions listenerOptions = null) { const long ClientCloseErrorCode = 11111; const long ServerCloseErrorCode = 22222; using QuicListener listener = CreateQuicListener(listenerOptions ?? CreateQuicListenerOptions()); using var serverFinished = new SemaphoreSlim(0); using var clientFinished = new SemaphoreSlim(0); for (int i = 0; i < iterations; ++i) { (QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(listener); using (clientConnection) using (serverConnection) { await new[] { Task.Run(async () => { await serverFunction(serverConnection); serverFinished.Release(); await clientFinished.WaitAsync(); }), Task.Run(async () => { await clientFunction(clientConnection); clientFinished.Release(); await serverFinished.WaitAsync(); }) }.WhenAllOrAnyFailed(millisecondsTimeout); await serverConnection.CloseAsync(ServerCloseErrorCode); await clientConnection.CloseAsync(ClientCloseErrorCode); } } } internal async Task RunStreamClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, bool bidi, int iterations, int millisecondsTimeout) { byte[] buffer = new byte[1] { 42 }; await RunClientServer( clientFunction: async connection => { await using QuicStream stream = bidi ? connection.OpenBidirectionalStream() : connection.OpenUnidirectionalStream(); // Open(Bi|Uni)directionalStream only allocates ID. We will force stream opening // by Writing there and receiving data on the other side. await stream.WriteAsync(buffer); await clientFunction(stream); stream.Shutdown(); await stream.ShutdownCompleted(); }, serverFunction: async connection => { await using QuicStream stream = await connection.AcceptStreamAsync(); Assert.Equal(1, await stream.ReadAsync(buffer)); await serverFunction(stream); stream.Shutdown(); await stream.ShutdownCompleted(); }, iterations, millisecondsTimeout ); } internal Task RunBidirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds) => RunStreamClientServer(clientFunction, serverFunction, bidi: true, iterations, millisecondsTimeout); internal Task RunUnirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds) => RunStreamClientServer(clientFunction, serverFunction, bidi: false, iterations, millisecondsTimeout); internal static async Task<int> ReadAll(QuicStream stream, byte[] buffer) { Memory<byte> memory = buffer; int bytesRead = 0; while (true) { int res = await stream.ReadAsync(memory); if (res == 0) { break; } bytesRead += res; memory = memory[res..]; } return bytesRead; } internal static async Task<int> WriteForever(QuicStream stream) { Memory<byte> buffer = new byte[] { 123 }; while (true) { await stream.WriteAsync(buffer); } } } public interface IQuicImplProviderFactory { QuicImplementationProvider GetProvider(); } public sealed class MsQuicProviderFactory : IQuicImplProviderFactory { public QuicImplementationProvider GetProvider() => QuicImplementationProviders.MsQuic; } public sealed class MockProviderFactory : IQuicImplProviderFactory { public QuicImplementationProvider GetProvider() => QuicImplementationProviders.Mock; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Net.Quic.Implementations; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using System.Diagnostics.Tracing; using System.Net.Sockets; namespace System.Net.Quic.Tests { public abstract class QuicTestBase<T> where T : IQuicImplProviderFactory, new() { private static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING"); private static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG"); private static readonly IQuicImplProviderFactory s_factory = new T(); public static QuicImplementationProvider ImplementationProvider { get; } = s_factory.GetProvider(); public static bool IsSupported => ImplementationProvider.IsSupported; public static bool IsMockProvider => typeof(T) == typeof(MockProviderFactory); public static bool IsMsQuicProvider => typeof(T) == typeof(MsQuicProviderFactory); public static SslApplicationProtocol ApplicationProtocol { get; } = new SslApplicationProtocol("quictest"); public X509Certificate2 ServerCertificate = System.Net.Test.Common.Configuration.Certificates.GetServerCertificate(); public X509Certificate2 ClientCertificate = System.Net.Test.Common.Configuration.Certificates.GetClientCertificate(); public ITestOutputHelper _output; public const int PassingTestTimeoutMilliseconds = 4 * 60 * 1000; public static TimeSpan PassingTestTimeout => TimeSpan.FromMilliseconds(PassingTestTimeoutMilliseconds); public QuicTestBase(ITestOutputHelper output) { _output = output; } public bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) { Assert.Equal(ServerCertificate.GetCertHash(), certificate?.GetCertHash()); return true; } public SslServerAuthenticationOptions GetSslServerAuthenticationOptions() { return new SslServerAuthenticationOptions() { ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol }, ServerCertificate = ServerCertificate }; } public SslClientAuthenticationOptions GetSslClientAuthenticationOptions() { return new SslClientAuthenticationOptions() { ApplicationProtocols = new List<SslApplicationProtocol>() { ApplicationProtocol }, RemoteCertificateValidationCallback = RemoteCertificateValidationCallback, TargetHost = "localhost" }; } public QuicClientConnectionOptions CreateQuicClientOptions() { return new QuicClientConnectionOptions() { ClientAuthenticationOptions = GetSslClientAuthenticationOptions() }; } internal QuicConnection CreateQuicConnection(IPEndPoint endpoint) { return new QuicConnection(ImplementationProvider, endpoint, GetSslClientAuthenticationOptions()); } internal QuicConnection CreateQuicConnection(QuicClientConnectionOptions clientOptions) { return new QuicConnection(ImplementationProvider, clientOptions); } internal QuicListenerOptions CreateQuicListenerOptions() { return new QuicListenerOptions() { ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0), ServerAuthenticationOptions = GetSslServerAuthenticationOptions() }; } internal QuicListener CreateQuicListener(int maxUnidirectionalStreams = 100, int maxBidirectionalStreams = 100) { var options = CreateQuicListenerOptions(); options.MaxUnidirectionalStreams = maxUnidirectionalStreams; options.MaxBidirectionalStreams = maxBidirectionalStreams; return CreateQuicListener(options); } internal QuicListener CreateQuicListener(IPEndPoint endpoint) { var options = new QuicListenerOptions() { ListenEndPoint = endpoint, ServerAuthenticationOptions = GetSslServerAuthenticationOptions() }; return CreateQuicListener(options); } private QuicListener CreateQuicListener(QuicListenerOptions options) => new QuicListener(ImplementationProvider, options); internal Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicListener listener) => CreateConnectedQuicConnection(null, listener); internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions, QuicListenerOptions listenerOptions) { using (QuicListener listener = CreateQuicListener(listenerOptions)) { clientOptions ??= new QuicClientConnectionOptions() { ClientAuthenticationOptions = GetSslClientAuthenticationOptions() }; clientOptions.RemoteEndPoint = listener.ListenEndPoint; return await CreateConnectedQuicConnection(clientOptions, listener); } } internal async Task<(QuicConnection, QuicConnection)> CreateConnectedQuicConnection(QuicClientConnectionOptions? clientOptions = null, QuicListener? listener = null) { int retry = 3; int delay = 25; bool disposeListener = false; if (listener == null) { listener = CreateQuicListener(); disposeListener = true; } clientOptions ??= CreateQuicClientOptions(); if (clientOptions.RemoteEndPoint == null) { clientOptions.RemoteEndPoint = listener.ListenEndPoint; } QuicConnection clientConnection = null; ValueTask<QuicConnection> serverTask = listener.AcceptConnectionAsync(); while (retry > 0) { clientConnection = CreateQuicConnection(clientOptions); retry--; try { await clientConnection.ConnectAsync().ConfigureAwait(false); break; } catch (QuicException ex) when (ex.HResult == (int)SocketError.ConnectionRefused) { _output.WriteLine($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}"); await Task.Delay(delay); delay *= 2; if (retry == 0) { Debug.Fail($"ConnectAsync to {clientConnection.RemoteEndPoint} failed with {ex.Message}"); throw ex; } } } QuicConnection serverConnection = await serverTask.ConfigureAwait(false); if (disposeListener) { listener.Dispose(); } Assert.True(serverConnection.Connected); Assert.True(clientConnection.Connected); return (clientConnection, serverTask.Result); } internal async Task PingPong(QuicConnection client, QuicConnection server) { using QuicStream clientStream = client.OpenBidirectionalStream(); ValueTask t = clientStream.WriteAsync(s_ping); using QuicStream serverStream = await server.AcceptStreamAsync(); byte[] buffer = new byte[s_ping.Length]; int remains = s_ping.Length; while (remains > 0) { int readLength = await serverStream.ReadAsync(buffer, buffer.Length - remains, remains); Assert.True(readLength > 0); remains -= readLength; } Assert.Equal(s_ping, buffer); await t; t = serverStream.WriteAsync(s_pong); remains = s_pong.Length; while (remains > 0) { int readLength = await clientStream.ReadAsync(buffer, buffer.Length - remains, remains); Assert.True(readLength > 0); remains -= readLength; } Assert.Equal(s_pong, buffer); await t; } internal async Task RunClientServer(Func<QuicConnection, Task> clientFunction, Func<QuicConnection, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds, QuicListenerOptions listenerOptions = null) { const long ClientCloseErrorCode = 11111; const long ServerCloseErrorCode = 22222; using QuicListener listener = CreateQuicListener(listenerOptions ?? CreateQuicListenerOptions()); using var serverFinished = new SemaphoreSlim(0); using var clientFinished = new SemaphoreSlim(0); for (int i = 0; i < iterations; ++i) { (QuicConnection clientConnection, QuicConnection serverConnection) = await CreateConnectedQuicConnection(listener); using (clientConnection) using (serverConnection) { await new[] { Task.Run(async () => { await serverFunction(serverConnection); serverFinished.Release(); await clientFinished.WaitAsync(); }), Task.Run(async () => { await clientFunction(clientConnection); clientFinished.Release(); await serverFinished.WaitAsync(); }) }.WhenAllOrAnyFailed(millisecondsTimeout); await serverConnection.CloseAsync(ServerCloseErrorCode); await clientConnection.CloseAsync(ClientCloseErrorCode); } } } internal async Task RunStreamClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, bool bidi, int iterations, int millisecondsTimeout) { byte[] buffer = new byte[1] { 42 }; await RunClientServer( clientFunction: async connection => { await using QuicStream stream = bidi ? connection.OpenBidirectionalStream() : connection.OpenUnidirectionalStream(); // Open(Bi|Uni)directionalStream only allocates ID. We will force stream opening // by Writing there and receiving data on the other side. await stream.WriteAsync(buffer); await clientFunction(stream); stream.Shutdown(); await stream.ShutdownCompleted(); }, serverFunction: async connection => { await using QuicStream stream = await connection.AcceptStreamAsync(); Assert.Equal(1, await stream.ReadAsync(buffer)); await serverFunction(stream); stream.Shutdown(); await stream.ShutdownCompleted(); }, iterations, millisecondsTimeout ); } internal Task RunBidirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds) => RunStreamClientServer(clientFunction, serverFunction, bidi: true, iterations, millisecondsTimeout); internal Task RunUnirectionalClientServer(Func<QuicStream, Task> clientFunction, Func<QuicStream, Task> serverFunction, int iterations = 1, int millisecondsTimeout = PassingTestTimeoutMilliseconds) => RunStreamClientServer(clientFunction, serverFunction, bidi: false, iterations, millisecondsTimeout); internal static async Task<int> ReadAll(QuicStream stream, byte[] buffer) { Memory<byte> memory = buffer; int bytesRead = 0; while (true) { int res = await stream.ReadAsync(memory); if (res == 0) { break; } bytesRead += res; memory = memory[res..]; } return bytesRead; } internal static async Task<int> WriteForever(QuicStream stream) { Memory<byte> buffer = new byte[] { 123 }; while (true) { await stream.WriteAsync(buffer); } } } public interface IQuicImplProviderFactory { QuicImplementationProvider GetProvider(); } public sealed class MsQuicProviderFactory : IQuicImplProviderFactory { public QuicImplementationProvider GetProvider() => QuicImplementationProviders.MsQuic; } public sealed class MockProviderFactory : IQuicImplProviderFactory { public QuicImplementationProvider GetProvider() => QuicImplementationProviders.Mock; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/Interaction.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. Imports System Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Runtime.Versioning Imports Microsoft.Win32 Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports System.Diagnostics.CodeAnalysis Namespace Microsoft.VisualBasic Public Module Interaction Private m_SortedEnvList As System.Collections.SortedList '============================================================================ ' Application/system interaction functions. '============================================================================ Public Function Shell(ByVal PathName As String, Optional ByVal Style As AppWinStyle = AppWinStyle.MinimizedFocus, Optional ByVal Wait As Boolean = False, Optional ByVal Timeout As Integer = -1) As Integer Return DirectCast(InvokeMethod("Shell", PathName, Style, Wait, Timeout), Integer) End Function Public Sub AppActivate(ByVal ProcessId As Integer) InvokeMethod("AppActivateByProcessId", ProcessId) End Sub Public Sub AppActivate(ByVal Title As String) InvokeMethod("AppActivateByTitle", Title) End Sub Private m_CommandLine As String Public Function Command() As String If m_CommandLine Is Nothing Then Dim s As String = Environment.CommandLine 'The first element of the array is the .exe name ' we must remove this when building the return value If (s Is Nothing) OrElse (s.Length = 0) Then Return "" End If 'The following code must remove the application name from the command line ' without disturbing the arguments (trailing and embedded spaces) ' 'We also need to handle embedded spaces in the application name ' as well as skipping over quotations used around embedded spaces within ' the application name ' examples: ' f:\"Program Files"\Microsoft\foo.exe a b d e f ' "f:\"Program Files"\Microsoft\foo.exe" a b d e f ' f:\Program Files\Microsoft\foo.exe a b d e f Dim LengthOfAppName, j As Integer 'Remove the app name from the arguments LengthOfAppName = Environment.GetCommandLineArgs(0).Length Do j = s.IndexOf(ChrW(34), j) If j >= 0 AndAlso j <= LengthOfAppName Then s = s.Remove(j, 1) End If Loop While (j >= 0 AndAlso j <= LengthOfAppName) If j = 0 OrElse j > s.Length Then m_CommandLine = "" Else m_CommandLine = LTrim(s.Substring(LengthOfAppName)) End If End If Return m_CommandLine End Function Public Function Environ(ByVal Expression As Integer) As String 'Validate index - Note that unlike the fx, this is a legacy VB function and the index is 1 based. If Expression <= 0 OrElse Expression > 255 Then Throw New ArgumentException(SR.Format(SR.Argument_Range1toFF1, "Expression")) End If If m_SortedEnvList Is Nothing Then SyncLock m_EnvironSyncObject If m_SortedEnvList Is Nothing Then 'Constructing the sorted environment list is extremely slow, so we keep a copy around. This list must be alphabetized to match vb5/vb6 behavior m_SortedEnvList = New System.Collections.SortedList(Environment.GetEnvironmentVariables()) End If End SyncLock End If If Expression > m_SortedEnvList.Count Then Return "" End If Dim EnvVarName As String = m_SortedEnvList.GetKey(Expression - 1).ToString() Dim EnvVarValue As String = m_SortedEnvList.GetByIndex(Expression - 1).ToString() Return (EnvVarName & "=" & EnvVarValue) End Function Private m_EnvironSyncObject As New Object Public Function Environ(ByVal Expression As String) As String Expression = Trim(Expression) If Expression.Length = 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Expression")) End If Return Environment.GetEnvironmentVariable(Expression) End Function '============================================================================ ' User interaction functions. '============================================================================ <SupportedOSPlatform("windows")> Public Sub Beep() #If TARGET_WINDOWS Then UnsafeNativeMethods.MessageBeep(0) #Else Throw New PlatformNotSupportedException() #End If End Sub Public Function InputBox(ByVal Prompt As String, Optional ByVal Title As String = "", Optional ByVal DefaultResponse As String = "", Optional ByVal XPos As Integer = -1, Optional ByVal YPos As Integer = -1) As String Return DirectCast(InvokeMethod("InputBox", Prompt, Title, DefaultResponse, XPos, YPos), String) End Function Public Function MsgBox(ByVal Prompt As Object, Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OkOnly, Optional ByVal Title As Object = Nothing) As MsgBoxResult Return DirectCast(InvokeMethod("MsgBox", Prompt, Buttons, Title), MsgBoxResult) End Function <UnconditionalSuppressMessage("ReflectionAnalsys", "IL2075:UnrecognizedReflectionPattern", Justification:="Trimmer warns because it can't see Microsoft.VisualBasic.Forms. If the assembly is there, the trimmer will be able to tell to preserve the method specified.")> Private Function InvokeMethod(methodName As String, ParamArray args As Object()) As Object Dim type As Type = Type.GetType("Microsoft.VisualBasic._Interaction, Microsoft.VisualBasic.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError:=False) Dim method As MethodInfo = type?.GetMethod(methodName) If method Is Nothing Then Throw New PlatformNotSupportedException(SR.MethodRequiresSystemWindowsForms) End If Return method.Invoke(Nothing, BindingFlags.DoNotWrapExceptions, Nothing, args, Nothing) End Function '============================================================================ ' String functions. '============================================================================ Public Function Choose(ByVal Index As Double, ByVal ParamArray Choice() As Object) As Object Dim FixedIndex As Integer = CInt(Fix(Index) - 1) 'ParamArray is 0 based, but Choose assumes 1 based If Choice.Rank <> 1 Then Throw New ArgumentException(SR.Format(SR.Argument_RankEQOne1, "Choice")) ElseIf FixedIndex < 0 OrElse FixedIndex > Choice.GetUpperBound(0) Then Return Nothing End If Return Choice(FixedIndex) End Function Public Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, ByVal FalsePart As Object) As Object If Expression Then Return TruePart End If Return FalsePart End Function Friend Function IIf(Of T)(ByVal condition As Boolean, ByVal truePart As T, ByVal falsePart As T) As T If condition Then Return truePart End If Return falsePart End Function Public Function Partition(ByVal Number As Long, ByVal Start As Long, ByVal [Stop] As Long, ByVal Interval As Long) As String 'CONSIDER: Change to use StringBuilder Dim Lower As Long Dim Upper As Long Dim NoUpper As Boolean Dim NoLower As Boolean Dim Buffer As String = Nothing Dim Buffer1 As String Dim Buffer2 As String Dim Spaces As Long 'Validate arguments If Start < 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Start")) End If If [Stop] <= Start Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Stop")) End If If Interval < 1 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Interval")) End If 'Check for before-first and after-last ranges If Number < Start Then Upper = Start - 1 NoLower = True ElseIf Number > [Stop] Then Lower = [Stop] + 1 NoUpper = True ElseIf Interval = 1 Then 'This is a special case Lower = Number Upper = Number Else 'Calculate the upper and lower ranges 'Note the use of Integer division "\" which truncates to whole number Lower = ((Number - Start) \ Interval) * Interval + Start Upper = Lower + Interval - 1 'Adjust for first and last ranges If Upper > [Stop] Then Upper = [Stop] End If If Lower < Start Then Lower = Start End If End If 'Build-up the string. Calculate number of spaces needed: VB3 uses Stop + 1. 'This may seem bogus but it has to be this way for VB3 compatibilty. Buffer1 = CStr([Stop] + 1) Buffer2 = CStr(Start - 1) If Len(Buffer1) > Len(Buffer2) Then Spaces = Len(Buffer1) Else Spaces = Len(Buffer2) End If 'Handle case where Upper is -1 and Stop < 9 If NoLower Then Buffer1 = CStr(Upper) If Spaces < Len(Buffer1) Then Spaces = Len(Buffer1) End If End If 'Insert lower-end of partition range. If NoLower Then InsertSpaces(Buffer, Spaces) Else InsertNumber(Buffer, Lower, Spaces) End If 'Insert the partition Buffer = Buffer & ":" 'Insert upper-end of partition range If NoUpper Then InsertSpaces(Buffer, Spaces) Else InsertNumber(Buffer, Upper, Spaces) End If Return Buffer End Function Private Sub InsertSpaces(ByRef Buffer As String, ByVal Spaces As Long) Do While Spaces > 0 'consider: - use stringbuilder Buffer = Buffer & " " Spaces = Spaces - 1 Loop End Sub Private Sub InsertNumber(ByRef Buffer As String, ByVal Num As Long, ByVal Spaces As Long) Dim Buffer1 As String 'consider: - use stringbuilder 'Convert number to a string Buffer1 = CStr(Num) 'Insert leading spaces InsertSpaces(Buffer, Spaces - Len(Buffer1)) 'Append string Buffer = Buffer & Buffer1 End Sub Public Function Switch(ByVal ParamArray VarExpr() As Object) As Object Dim Elements As Integer Dim Index As Integer If VarExpr Is Nothing Then Return Nothing End If Elements = VarExpr.Length Index = 0 'Ensure we have an even number of arguments (0 based) If (Elements Mod 2) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "VarExpr")) End If Do While Elements > 0 If CBool(VarExpr(Index)) Then Return VarExpr(Index + 1) End If Index += 2 Elements -= 2 Loop Return Nothing 'If nothing matched above End Function '============================================================================ ' Registry functions. '============================================================================ <SupportedOSPlatform("windows")> Public Sub DeleteSetting(ByVal AppName As String, Optional ByVal Section As String = Nothing, Optional ByVal Key As String = Nothing) Dim AppSection As String Dim UserKey As RegistryKey Dim AppSectionKey As RegistryKey = Nothing CheckPathComponent(AppName) AppSection = FormRegKey(AppName, Section) Try UserKey = Registry.CurrentUser If IsNothing(Key) OrElse (Key.Length = 0) Then UserKey.DeleteSubKeyTree(AppSection) Else AppSectionKey = UserKey.OpenSubKey(AppSection, True) If AppSectionKey Is Nothing Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Section")) End If AppSectionKey.DeleteValue(Key) End If Catch ex As Exception Throw ex Finally If AppSectionKey IsNot Nothing Then AppSectionKey.Close() End If End Try End Sub <SupportedOSPlatform("windows")> Public Function GetAllSettings(ByVal AppName As String, ByVal Section As String) As String(,) Dim rk As RegistryKey Dim sAppSect As String Dim i As Integer Dim lUpperBound As Integer Dim sValueNames() As String Dim sValues(,) As String Dim o As Object Dim sName As String ' Check for empty string in path CheckPathComponent(AppName) CheckPathComponent(Section) sAppSect = FormRegKey(AppName, Section) rk = Registry.CurrentUser.OpenSubKey(sAppSect) If rk Is Nothing Then Return Nothing End If GetAllSettings = Nothing Try If rk.ValueCount <> 0 Then sValueNames = rk.GetValueNames() lUpperBound = sValueNames.GetUpperBound(0) ReDim sValues(lUpperBound, 1) For i = 0 To lUpperBound sName = sValueNames(i) 'Assign name sValues(i, 0) = sName 'Assign value o = rk.GetValue(sName) If (Not o Is Nothing) AndAlso (TypeOf o Is String) Then sValues(i, 1) = o.ToString() End If Next i GetAllSettings = sValues End If Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch ex As Exception 'Consume the exception Finally rk.Close() End Try End Function <SupportedOSPlatform("windows")> Public Function GetSetting(ByVal AppName As String, ByVal Section As String, ByVal Key As String, Optional ByVal [Default] As String = "") As String Dim rk As RegistryKey = Nothing Dim sAppSect As String Dim o As Object 'Check for empty strings CheckPathComponent(AppName) CheckPathComponent(Section) CheckPathComponent(Key) If [Default] Is Nothing Then [Default] = "" End If 'Open the sub key sAppSect = FormRegKey(AppName, Section) Try rk = Registry.CurrentUser.OpenSubKey(sAppSect) 'By default, does not request write permission 'Get the key's value If rk Is Nothing Then Return [Default] End If o = rk.GetValue(Key, [Default]) Finally If rk IsNot Nothing Then rk.Close() End If End Try If o Is Nothing Then Return Nothing ElseIf TypeOf o Is String Then ' - odd that this is required to be a string when it isn't in GetAllSettings() above... Return DirectCast(o, String) Else Throw New ArgumentException(SR.Argument_InvalidValue) End If End Function <SupportedOSPlatform("windows")> Public Sub SaveSetting(ByVal AppName As String, ByVal Section As String, ByVal Key As String, ByVal Setting As String) Dim rk As RegistryKey Dim sIniSect As String ' Check for empty string in path CheckPathComponent(AppName) CheckPathComponent(Section) CheckPathComponent(Key) sIniSect = FormRegKey(AppName, Section) rk = Registry.CurrentUser.CreateSubKey(sIniSect) If rk Is Nothing Then 'Subkey could not be created Throw New ArgumentException(SR.Format(SR.Interaction_ResKeyNotCreated1, sIniSect)) End If Try rk.SetValue(Key, Setting) Catch ex As Exception Throw ex Finally rk.Close() End Try End Sub '============================================================================ ' Private functions. '============================================================================ Private Function FormRegKey(ByVal sApp As String, ByVal sSect As String) As String Const REGISTRY_INI_ROOT As String = "Software\VB and VBA Program Settings" 'Forms the string for the key value If IsNothing(sApp) OrElse (sApp.Length = 0) Then FormRegKey = REGISTRY_INI_ROOT ElseIf IsNothing(sSect) OrElse (sSect.Length = 0) Then FormRegKey = REGISTRY_INI_ROOT & "\" & sApp Else FormRegKey = REGISTRY_INI_ROOT & "\" & sApp & "\" & sSect End If End Function Private Sub CheckPathComponent(ByVal s As String) If (s Is Nothing) OrElse (s.Length = 0) Then Throw New ArgumentException(SR.Argument_PathNullOrEmpty) End If End Sub <SupportedOSPlatform("windows")> <RequiresUnreferencedCode("The COM object to be created cannot be statically analyzed and may be trimmed")> Public Function CreateObject(ByVal ProgId As String, Optional ByVal ServerName As String = "") As Object 'Creates local or remote COM2 objects. Should not be used to create COM+ objects. 'Applications that need to be STA should set STA either on their Sub Main via STAThreadAttribute 'or through Thread.CurrentThread.ApartmentState - the VB runtime will not change this. 'DO NOT SET THREAD STATE - Thread.CurrentThread.ApartmentState = ApartmentState.STA Dim t As Type If ProgId.Length = 0 Then Throw VbMakeException(vbErrors.CantCreateObject) End If If ServerName Is Nothing OrElse ServerName.Length = 0 Then ServerName = Nothing Else 'Does the ServerName match the MachineName? If String.Equals(Environment.MachineName, ServerName, StringComparison.OrdinalIgnoreCase) Then ServerName = Nothing End If End If Try If ServerName Is Nothing Then t = Type.GetTypeFromProgID(ProgId) Else t = Type.GetTypeFromProgID(ProgId, ServerName, True) End If Return System.Activator.CreateInstance(t) Catch e As COMException If e.ErrorCode = &H800706BA Then '&H800706BA = The RPC Server is unavailable Throw VbMakeException(vbErrors.ServerNotFound) Else Throw VbMakeException(vbErrors.CantCreateObject) End If Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch e As Exception Throw VbMakeException(vbErrors.CantCreateObject) End Try End Function <SupportedOSPlatform("windows")> <RequiresUnreferencedCode("The COM component to be returned cannot be statically analyzed and may be trimmed")> Public Function GetObject(Optional ByVal PathName As String = Nothing, Optional ByVal [Class] As String = Nothing) As Object 'Only works for Com2 objects, not for COM+ objects. If Len([Class]) = 0 Then Try Return Marshal.BindToMoniker([PathName]) Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch Throw VbMakeException(vbErrors.CantCreateObject) End Try Else If PathName Is Nothing Then Return Nothing ElseIf Len(PathName) = 0 Then Try Dim t As Type = Type.GetTypeFromProgID([Class]) Return System.Activator.CreateInstance(t) Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch Throw VbMakeException(vbErrors.CantCreateObject) End Try Else Return Nothing End If End If End Function '============================================================================ ' Object/latebound functions. '============================================================================ <RequiresUnreferencedCode("The type of ObjectRef cannot be statically analyzed and its members may be trimmed.")> Public Function CallByName(ByVal ObjectRef As System.Object, ByVal ProcName As String, ByVal UseCallType As CallType, ByVal ParamArray Args() As Object) As Object Select Case UseCallType Case CallType.Method 'Need to use LateGet, because we are returning a value Return CompilerServices.LateBinding.InternalLateCall(ObjectRef, Nothing, ProcName, Args, Nothing, Nothing, False) Case CallType.Get Return CompilerServices.LateBinding.LateGet(ObjectRef, Nothing, ProcName, Args, Nothing, Nothing) Case CallType.Let, CallType.Set CompilerServices.LateBinding.InternalLateSet(ObjectRef, Nothing, ProcName, Args, Nothing, False, UseCallType) Return Nothing Case Else Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "CallType")) End Select End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. Imports System Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Runtime.Versioning Imports Microsoft.Win32 Imports Microsoft.VisualBasic.CompilerServices Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils Imports System.Diagnostics.CodeAnalysis Namespace Microsoft.VisualBasic Public Module Interaction Private m_SortedEnvList As System.Collections.SortedList '============================================================================ ' Application/system interaction functions. '============================================================================ Public Function Shell(ByVal PathName As String, Optional ByVal Style As AppWinStyle = AppWinStyle.MinimizedFocus, Optional ByVal Wait As Boolean = False, Optional ByVal Timeout As Integer = -1) As Integer Return DirectCast(InvokeMethod("Shell", PathName, Style, Wait, Timeout), Integer) End Function Public Sub AppActivate(ByVal ProcessId As Integer) InvokeMethod("AppActivateByProcessId", ProcessId) End Sub Public Sub AppActivate(ByVal Title As String) InvokeMethod("AppActivateByTitle", Title) End Sub Private m_CommandLine As String Public Function Command() As String If m_CommandLine Is Nothing Then Dim s As String = Environment.CommandLine 'The first element of the array is the .exe name ' we must remove this when building the return value If (s Is Nothing) OrElse (s.Length = 0) Then Return "" End If 'The following code must remove the application name from the command line ' without disturbing the arguments (trailing and embedded spaces) ' 'We also need to handle embedded spaces in the application name ' as well as skipping over quotations used around embedded spaces within ' the application name ' examples: ' f:\"Program Files"\Microsoft\foo.exe a b d e f ' "f:\"Program Files"\Microsoft\foo.exe" a b d e f ' f:\Program Files\Microsoft\foo.exe a b d e f Dim LengthOfAppName, j As Integer 'Remove the app name from the arguments LengthOfAppName = Environment.GetCommandLineArgs(0).Length Do j = s.IndexOf(ChrW(34), j) If j >= 0 AndAlso j <= LengthOfAppName Then s = s.Remove(j, 1) End If Loop While (j >= 0 AndAlso j <= LengthOfAppName) If j = 0 OrElse j > s.Length Then m_CommandLine = "" Else m_CommandLine = LTrim(s.Substring(LengthOfAppName)) End If End If Return m_CommandLine End Function Public Function Environ(ByVal Expression As Integer) As String 'Validate index - Note that unlike the fx, this is a legacy VB function and the index is 1 based. If Expression <= 0 OrElse Expression > 255 Then Throw New ArgumentException(SR.Format(SR.Argument_Range1toFF1, "Expression")) End If If m_SortedEnvList Is Nothing Then SyncLock m_EnvironSyncObject If m_SortedEnvList Is Nothing Then 'Constructing the sorted environment list is extremely slow, so we keep a copy around. This list must be alphabetized to match vb5/vb6 behavior m_SortedEnvList = New System.Collections.SortedList(Environment.GetEnvironmentVariables()) End If End SyncLock End If If Expression > m_SortedEnvList.Count Then Return "" End If Dim EnvVarName As String = m_SortedEnvList.GetKey(Expression - 1).ToString() Dim EnvVarValue As String = m_SortedEnvList.GetByIndex(Expression - 1).ToString() Return (EnvVarName & "=" & EnvVarValue) End Function Private m_EnvironSyncObject As New Object Public Function Environ(ByVal Expression As String) As String Expression = Trim(Expression) If Expression.Length = 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Expression")) End If Return Environment.GetEnvironmentVariable(Expression) End Function '============================================================================ ' User interaction functions. '============================================================================ <SupportedOSPlatform("windows")> Public Sub Beep() #If TARGET_WINDOWS Then UnsafeNativeMethods.MessageBeep(0) #Else Throw New PlatformNotSupportedException() #End If End Sub Public Function InputBox(ByVal Prompt As String, Optional ByVal Title As String = "", Optional ByVal DefaultResponse As String = "", Optional ByVal XPos As Integer = -1, Optional ByVal YPos As Integer = -1) As String Return DirectCast(InvokeMethod("InputBox", Prompt, Title, DefaultResponse, XPos, YPos), String) End Function Public Function MsgBox(ByVal Prompt As Object, Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OkOnly, Optional ByVal Title As Object = Nothing) As MsgBoxResult Return DirectCast(InvokeMethod("MsgBox", Prompt, Buttons, Title), MsgBoxResult) End Function <UnconditionalSuppressMessage("ReflectionAnalsys", "IL2075:UnrecognizedReflectionPattern", Justification:="Trimmer warns because it can't see Microsoft.VisualBasic.Forms. If the assembly is there, the trimmer will be able to tell to preserve the method specified.")> Private Function InvokeMethod(methodName As String, ParamArray args As Object()) As Object Dim type As Type = Type.GetType("Microsoft.VisualBasic._Interaction, Microsoft.VisualBasic.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError:=False) Dim method As MethodInfo = type?.GetMethod(methodName) If method Is Nothing Then Throw New PlatformNotSupportedException(SR.MethodRequiresSystemWindowsForms) End If Return method.Invoke(Nothing, BindingFlags.DoNotWrapExceptions, Nothing, args, Nothing) End Function '============================================================================ ' String functions. '============================================================================ Public Function Choose(ByVal Index As Double, ByVal ParamArray Choice() As Object) As Object Dim FixedIndex As Integer = CInt(Fix(Index) - 1) 'ParamArray is 0 based, but Choose assumes 1 based If Choice.Rank <> 1 Then Throw New ArgumentException(SR.Format(SR.Argument_RankEQOne1, "Choice")) ElseIf FixedIndex < 0 OrElse FixedIndex > Choice.GetUpperBound(0) Then Return Nothing End If Return Choice(FixedIndex) End Function Public Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, ByVal FalsePart As Object) As Object If Expression Then Return TruePart End If Return FalsePart End Function Friend Function IIf(Of T)(ByVal condition As Boolean, ByVal truePart As T, ByVal falsePart As T) As T If condition Then Return truePart End If Return falsePart End Function Public Function Partition(ByVal Number As Long, ByVal Start As Long, ByVal [Stop] As Long, ByVal Interval As Long) As String 'CONSIDER: Change to use StringBuilder Dim Lower As Long Dim Upper As Long Dim NoUpper As Boolean Dim NoLower As Boolean Dim Buffer As String = Nothing Dim Buffer1 As String Dim Buffer2 As String Dim Spaces As Long 'Validate arguments If Start < 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Start")) End If If [Stop] <= Start Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Stop")) End If If Interval < 1 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Interval")) End If 'Check for before-first and after-last ranges If Number < Start Then Upper = Start - 1 NoLower = True ElseIf Number > [Stop] Then Lower = [Stop] + 1 NoUpper = True ElseIf Interval = 1 Then 'This is a special case Lower = Number Upper = Number Else 'Calculate the upper and lower ranges 'Note the use of Integer division "\" which truncates to whole number Lower = ((Number - Start) \ Interval) * Interval + Start Upper = Lower + Interval - 1 'Adjust for first and last ranges If Upper > [Stop] Then Upper = [Stop] End If If Lower < Start Then Lower = Start End If End If 'Build-up the string. Calculate number of spaces needed: VB3 uses Stop + 1. 'This may seem bogus but it has to be this way for VB3 compatibilty. Buffer1 = CStr([Stop] + 1) Buffer2 = CStr(Start - 1) If Len(Buffer1) > Len(Buffer2) Then Spaces = Len(Buffer1) Else Spaces = Len(Buffer2) End If 'Handle case where Upper is -1 and Stop < 9 If NoLower Then Buffer1 = CStr(Upper) If Spaces < Len(Buffer1) Then Spaces = Len(Buffer1) End If End If 'Insert lower-end of partition range. If NoLower Then InsertSpaces(Buffer, Spaces) Else InsertNumber(Buffer, Lower, Spaces) End If 'Insert the partition Buffer = Buffer & ":" 'Insert upper-end of partition range If NoUpper Then InsertSpaces(Buffer, Spaces) Else InsertNumber(Buffer, Upper, Spaces) End If Return Buffer End Function Private Sub InsertSpaces(ByRef Buffer As String, ByVal Spaces As Long) Do While Spaces > 0 'consider: - use stringbuilder Buffer = Buffer & " " Spaces = Spaces - 1 Loop End Sub Private Sub InsertNumber(ByRef Buffer As String, ByVal Num As Long, ByVal Spaces As Long) Dim Buffer1 As String 'consider: - use stringbuilder 'Convert number to a string Buffer1 = CStr(Num) 'Insert leading spaces InsertSpaces(Buffer, Spaces - Len(Buffer1)) 'Append string Buffer = Buffer & Buffer1 End Sub Public Function Switch(ByVal ParamArray VarExpr() As Object) As Object Dim Elements As Integer Dim Index As Integer If VarExpr Is Nothing Then Return Nothing End If Elements = VarExpr.Length Index = 0 'Ensure we have an even number of arguments (0 based) If (Elements Mod 2) <> 0 Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "VarExpr")) End If Do While Elements > 0 If CBool(VarExpr(Index)) Then Return VarExpr(Index + 1) End If Index += 2 Elements -= 2 Loop Return Nothing 'If nothing matched above End Function '============================================================================ ' Registry functions. '============================================================================ <SupportedOSPlatform("windows")> Public Sub DeleteSetting(ByVal AppName As String, Optional ByVal Section As String = Nothing, Optional ByVal Key As String = Nothing) Dim AppSection As String Dim UserKey As RegistryKey Dim AppSectionKey As RegistryKey = Nothing CheckPathComponent(AppName) AppSection = FormRegKey(AppName, Section) Try UserKey = Registry.CurrentUser If IsNothing(Key) OrElse (Key.Length = 0) Then UserKey.DeleteSubKeyTree(AppSection) Else AppSectionKey = UserKey.OpenSubKey(AppSection, True) If AppSectionKey Is Nothing Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Section")) End If AppSectionKey.DeleteValue(Key) End If Catch ex As Exception Throw ex Finally If AppSectionKey IsNot Nothing Then AppSectionKey.Close() End If End Try End Sub <SupportedOSPlatform("windows")> Public Function GetAllSettings(ByVal AppName As String, ByVal Section As String) As String(,) Dim rk As RegistryKey Dim sAppSect As String Dim i As Integer Dim lUpperBound As Integer Dim sValueNames() As String Dim sValues(,) As String Dim o As Object Dim sName As String ' Check for empty string in path CheckPathComponent(AppName) CheckPathComponent(Section) sAppSect = FormRegKey(AppName, Section) rk = Registry.CurrentUser.OpenSubKey(sAppSect) If rk Is Nothing Then Return Nothing End If GetAllSettings = Nothing Try If rk.ValueCount <> 0 Then sValueNames = rk.GetValueNames() lUpperBound = sValueNames.GetUpperBound(0) ReDim sValues(lUpperBound, 1) For i = 0 To lUpperBound sName = sValueNames(i) 'Assign name sValues(i, 0) = sName 'Assign value o = rk.GetValue(sName) If (Not o Is Nothing) AndAlso (TypeOf o Is String) Then sValues(i, 1) = o.ToString() End If Next i GetAllSettings = sValues End If Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch ex As Exception 'Consume the exception Finally rk.Close() End Try End Function <SupportedOSPlatform("windows")> Public Function GetSetting(ByVal AppName As String, ByVal Section As String, ByVal Key As String, Optional ByVal [Default] As String = "") As String Dim rk As RegistryKey = Nothing Dim sAppSect As String Dim o As Object 'Check for empty strings CheckPathComponent(AppName) CheckPathComponent(Section) CheckPathComponent(Key) If [Default] Is Nothing Then [Default] = "" End If 'Open the sub key sAppSect = FormRegKey(AppName, Section) Try rk = Registry.CurrentUser.OpenSubKey(sAppSect) 'By default, does not request write permission 'Get the key's value If rk Is Nothing Then Return [Default] End If o = rk.GetValue(Key, [Default]) Finally If rk IsNot Nothing Then rk.Close() End If End Try If o Is Nothing Then Return Nothing ElseIf TypeOf o Is String Then ' - odd that this is required to be a string when it isn't in GetAllSettings() above... Return DirectCast(o, String) Else Throw New ArgumentException(SR.Argument_InvalidValue) End If End Function <SupportedOSPlatform("windows")> Public Sub SaveSetting(ByVal AppName As String, ByVal Section As String, ByVal Key As String, ByVal Setting As String) Dim rk As RegistryKey Dim sIniSect As String ' Check for empty string in path CheckPathComponent(AppName) CheckPathComponent(Section) CheckPathComponent(Key) sIniSect = FormRegKey(AppName, Section) rk = Registry.CurrentUser.CreateSubKey(sIniSect) If rk Is Nothing Then 'Subkey could not be created Throw New ArgumentException(SR.Format(SR.Interaction_ResKeyNotCreated1, sIniSect)) End If Try rk.SetValue(Key, Setting) Catch ex As Exception Throw ex Finally rk.Close() End Try End Sub '============================================================================ ' Private functions. '============================================================================ Private Function FormRegKey(ByVal sApp As String, ByVal sSect As String) As String Const REGISTRY_INI_ROOT As String = "Software\VB and VBA Program Settings" 'Forms the string for the key value If IsNothing(sApp) OrElse (sApp.Length = 0) Then FormRegKey = REGISTRY_INI_ROOT ElseIf IsNothing(sSect) OrElse (sSect.Length = 0) Then FormRegKey = REGISTRY_INI_ROOT & "\" & sApp Else FormRegKey = REGISTRY_INI_ROOT & "\" & sApp & "\" & sSect End If End Function Private Sub CheckPathComponent(ByVal s As String) If (s Is Nothing) OrElse (s.Length = 0) Then Throw New ArgumentException(SR.Argument_PathNullOrEmpty) End If End Sub <SupportedOSPlatform("windows")> <RequiresUnreferencedCode("The COM object to be created cannot be statically analyzed and may be trimmed")> Public Function CreateObject(ByVal ProgId As String, Optional ByVal ServerName As String = "") As Object 'Creates local or remote COM2 objects. Should not be used to create COM+ objects. 'Applications that need to be STA should set STA either on their Sub Main via STAThreadAttribute 'or through Thread.CurrentThread.ApartmentState - the VB runtime will not change this. 'DO NOT SET THREAD STATE - Thread.CurrentThread.ApartmentState = ApartmentState.STA Dim t As Type If ProgId.Length = 0 Then Throw VbMakeException(vbErrors.CantCreateObject) End If If ServerName Is Nothing OrElse ServerName.Length = 0 Then ServerName = Nothing Else 'Does the ServerName match the MachineName? If String.Equals(Environment.MachineName, ServerName, StringComparison.OrdinalIgnoreCase) Then ServerName = Nothing End If End If Try If ServerName Is Nothing Then t = Type.GetTypeFromProgID(ProgId) Else t = Type.GetTypeFromProgID(ProgId, ServerName, True) End If Return System.Activator.CreateInstance(t) Catch e As COMException If e.ErrorCode = &H800706BA Then '&H800706BA = The RPC Server is unavailable Throw VbMakeException(vbErrors.ServerNotFound) Else Throw VbMakeException(vbErrors.CantCreateObject) End If Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch e As Exception Throw VbMakeException(vbErrors.CantCreateObject) End Try End Function <SupportedOSPlatform("windows")> <RequiresUnreferencedCode("The COM component to be returned cannot be statically analyzed and may be trimmed")> Public Function GetObject(Optional ByVal PathName As String = Nothing, Optional ByVal [Class] As String = Nothing) As Object 'Only works for Com2 objects, not for COM+ objects. If Len([Class]) = 0 Then Try Return Marshal.BindToMoniker([PathName]) Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch Throw VbMakeException(vbErrors.CantCreateObject) End Try Else If PathName Is Nothing Then Return Nothing ElseIf Len(PathName) = 0 Then Try Dim t As Type = Type.GetTypeFromProgID([Class]) Return System.Activator.CreateInstance(t) Catch ex As StackOverflowException Throw ex Catch ex As OutOfMemoryException Throw ex Catch Throw VbMakeException(vbErrors.CantCreateObject) End Try Else Return Nothing End If End If End Function '============================================================================ ' Object/latebound functions. '============================================================================ <RequiresUnreferencedCode("The type of ObjectRef cannot be statically analyzed and its members may be trimmed.")> Public Function CallByName(ByVal ObjectRef As System.Object, ByVal ProcName As String, ByVal UseCallType As CallType, ByVal ParamArray Args() As Object) As Object Select Case UseCallType Case CallType.Method 'Need to use LateGet, because we are returning a value Return CompilerServices.LateBinding.InternalLateCall(ObjectRef, Nothing, ProcName, Args, Nothing, Nothing, False) Case CallType.Get Return CompilerServices.LateBinding.LateGet(ObjectRef, Nothing, ProcName, Args, Nothing, Nothing) Case CallType.Let, CallType.Set CompilerServices.LateBinding.InternalLateSet(ObjectRef, Nothing, ProcName, Args, Nothing, False, UseCallType) Return Nothing Case Else Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "CallType")) End Select End Function End Module End Namespace
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/coreclr/pal/tests/palsuite/c_runtime/iswprint/test1/test1.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test1.c ** ** Purpose: Tests iswprint with all wide characters, ensuring they are ** consistent with GetStringTypeExW. ** ** **===================================================================*/ #include <palsuite.h> PALTEST(c_runtime_iswprint_test1_paltest_iswprint_test1, "c_runtime/iswprint/test1/paltest_iswprint_test1") { WORD Info; int ret; int i; WCHAR ch; if (PAL_Initialize(argc, argv)) { return FAIL; } for (i=0; i<=0xFFFF; i++) { ch = i; ret = GetStringTypeExW(LOCALE_USER_DEFAULT, CT_CTYPE1, &ch, 1, &Info); if (!ret) { Fail("GetStringTypeExW failed to get information for %#X!\n", ch); } ret = iswprint(ch); if (Info & (C1_BLANK|C1_PUNCT|C1_ALPHA|C1_DIGIT)) { if (!ret) { Fail("iswprint returned incorrect results for %#X: " "expected printable\n", ch); } } else { if (ret) { Fail("iswprint returned incorrect results for %#X: " "expected non-printable\n", ch); } } } PAL_Terminate(); return PASS; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*===================================================================== ** ** Source: test1.c ** ** Purpose: Tests iswprint with all wide characters, ensuring they are ** consistent with GetStringTypeExW. ** ** **===================================================================*/ #include <palsuite.h> PALTEST(c_runtime_iswprint_test1_paltest_iswprint_test1, "c_runtime/iswprint/test1/paltest_iswprint_test1") { WORD Info; int ret; int i; WCHAR ch; if (PAL_Initialize(argc, argv)) { return FAIL; } for (i=0; i<=0xFFFF; i++) { ch = i; ret = GetStringTypeExW(LOCALE_USER_DEFAULT, CT_CTYPE1, &ch, 1, &Info); if (!ret) { Fail("GetStringTypeExW failed to get information for %#X!\n", ch); } ret = iswprint(ch); if (Info & (C1_BLANK|C1_PUNCT|C1_ALPHA|C1_DIGIT)) { if (!ret) { Fail("iswprint returned incorrect results for %#X: " "expected printable\n", ch); } } else { if (ret) { Fail("iswprint returned incorrect results for %#X: " "expected non-printable\n", ch); } } } PAL_Terminate(); return PASS; }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_CopyTo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using Xunit.Abstractions; using System.Collections; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_CopyTo", Desc = "")] public class TC_SchemaSet_CopyTo : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_CopyTo(ITestOutputHelper output) { _output = output; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v1 - CopyTo with array = null")] public void v1() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.CopyTo(null, 0); } catch (ArgumentNullException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v2 - ICollection.CopyTo with array = null")] public void v2() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); ICollection Col = sc.Schemas(); Col.CopyTo(null, 0); } catch (ArgumentNullException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v3 - ICollection.CopyTo with array smaller than source", Priority = 0)] public void v3() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); ICollection Col = sc.Schemas(); XmlSchema[] array = new XmlSchema[1]; Col.CopyTo(array, 0); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v4 - CopyTo with index < 0")] public void v4() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[1]; sc.CopyTo(array, -1); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v5 - ICollection.CopyTo with index < 0")] public void v5() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); ICollection Col = sc.Schemas(); XmlSchema[] array = new XmlSchema[1]; Col.CopyTo(array, -1); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v6 - Filling last two positions of array", Priority = 0)] public void v6() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor); XmlSchema Schema2 = sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[10]; sc.CopyTo(array, 8); Assert.Equal(array[8], Schema1); Assert.Equal(array[9], Schema2); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v7 - Copy all to array of the same size", Priority = 0)] public void v7() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor); XmlSchema Schema2 = sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[2]; sc.CopyTo(array, 0); Assert.Equal(array[0], Schema1); Assert.Equal(array[1], Schema2); return; } [Fact] //[Variation(Desc = "v8 - 378346: CopyTo throws correct exception for index < 0 but incorrect exception for index > maxLength of array.", Priority = 0)] public void v8() { try { XmlSchemaSet ss = new XmlSchemaSet(); ss.CopyTo(new XmlSchema[2], 3); } catch (ArgumentOutOfRangeException e) { _output.WriteLine(e.Message); return; } Assert.True(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using Xunit.Abstractions; using System.Collections; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_CopyTo", Desc = "")] public class TC_SchemaSet_CopyTo : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_CopyTo(ITestOutputHelper output) { _output = output; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v1 - CopyTo with array = null")] public void v1() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); sc.CopyTo(null, 0); } catch (ArgumentNullException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v2 - ICollection.CopyTo with array = null")] public void v2() { try { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add("xsdauthor", TestData._XsdAuthor); ICollection Col = sc.Schemas(); Col.CopyTo(null, 0); } catch (ArgumentNullException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v3 - ICollection.CopyTo with array smaller than source", Priority = 0)] public void v3() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); ICollection Col = sc.Schemas(); XmlSchema[] array = new XmlSchema[1]; Col.CopyTo(array, 0); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v4 - CopyTo with index < 0")] public void v4() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[1]; sc.CopyTo(array, -1); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v5 - ICollection.CopyTo with index < 0")] public void v5() { XmlSchemaSet sc = new XmlSchemaSet(); try { sc.Add("xsdauthor", TestData._XsdAuthor); sc.Add(null, TestData._XsdNoNs); ICollection Col = sc.Schemas(); XmlSchema[] array = new XmlSchema[1]; Col.CopyTo(array, -1); } catch (ArgumentException) { // GLOBALIZATION return; } Assert.True(false); } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v6 - Filling last two positions of array", Priority = 0)] public void v6() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor); XmlSchema Schema2 = sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[10]; sc.CopyTo(array, 8); Assert.Equal(array[8], Schema1); Assert.Equal(array[9], Schema2); return; } //----------------------------------------------------------------------------------- [Fact] //[Variation(Desc = "v7 - Copy all to array of the same size", Priority = 0)] public void v7() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor); XmlSchema Schema2 = sc.Add(null, TestData._XsdNoNs); XmlSchema[] array = new XmlSchema[2]; sc.CopyTo(array, 0); Assert.Equal(array[0], Schema1); Assert.Equal(array[1], Schema2); return; } [Fact] //[Variation(Desc = "v8 - 378346: CopyTo throws correct exception for index < 0 but incorrect exception for index > maxLength of array.", Priority = 0)] public void v8() { try { XmlSchemaSet ss = new XmlSchemaSet(); ss.CopyTo(new XmlSchema[2], 3); } catch (ArgumentOutOfRangeException e) { _output.WriteLine(e.Message); return; } Assert.True(false); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Methodical/Boxing/misc/enum_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="enum.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="enum.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Collections/src/System/Collections/StructuralComparisons.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Collections { public static class StructuralComparisons { private static volatile IComparer? s_StructuralComparer; private static volatile IEqualityComparer? s_StructuralEqualityComparer; public static IComparer StructuralComparer { get { IComparer? comparer = s_StructuralComparer; if (comparer == null) { comparer = new StructuralComparer(); s_StructuralComparer = comparer; } return comparer; } } public static IEqualityComparer StructuralEqualityComparer { get { IEqualityComparer? comparer = s_StructuralEqualityComparer; if (comparer == null) { comparer = new StructuralEqualityComparer(); s_StructuralEqualityComparer = comparer; } return comparer; } } } internal sealed class StructuralEqualityComparer : IEqualityComparer { public new bool Equals(object? x, object? y) { if (x != null) { IStructuralEquatable? seObj = x as IStructuralEquatable; if (seObj != null) { return seObj.Equals(y, this); } if (y != null) { return x.Equals(y); } else { return false; } } if (y != null) return false; return true; } public int GetHashCode(object obj) { if (obj == null) return 0; IStructuralEquatable? seObj = obj as IStructuralEquatable; if (seObj != null) { return seObj.GetHashCode(this); } return obj.GetHashCode(); } } internal sealed class StructuralComparer : IComparer { public int Compare(object? x, object? y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; IStructuralComparable? scX = x as IStructuralComparable; if (scX != null) { return scX.CompareTo(y, this); } return Comparer<object>.Default.Compare(x, y); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; namespace System.Collections { public static class StructuralComparisons { private static volatile IComparer? s_StructuralComparer; private static volatile IEqualityComparer? s_StructuralEqualityComparer; public static IComparer StructuralComparer { get { IComparer? comparer = s_StructuralComparer; if (comparer == null) { comparer = new StructuralComparer(); s_StructuralComparer = comparer; } return comparer; } } public static IEqualityComparer StructuralEqualityComparer { get { IEqualityComparer? comparer = s_StructuralEqualityComparer; if (comparer == null) { comparer = new StructuralEqualityComparer(); s_StructuralEqualityComparer = comparer; } return comparer; } } } internal sealed class StructuralEqualityComparer : IEqualityComparer { public new bool Equals(object? x, object? y) { if (x != null) { IStructuralEquatable? seObj = x as IStructuralEquatable; if (seObj != null) { return seObj.Equals(y, this); } if (y != null) { return x.Equals(y); } else { return false; } } if (y != null) return false; return true; } public int GetHashCode(object obj) { if (obj == null) return 0; IStructuralEquatable? seObj = obj as IStructuralEquatable; if (seObj != null) { return seObj.GetHashCode(this); } return obj.GetHashCode(); } } internal sealed class StructuralComparer : IComparer { public int Compare(object? x, object? y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; IStructuralComparable? scX = x as IStructuralComparable; if (scX != null) { return scX.CompareTo(y, this); } return Comparer<object>.Default.Compare(x, y); } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Methodical/explicit/rotate/rotarg_valref_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_valref.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="rotarg_valref.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b82048/b82048.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public struct AA { public static sbyte m_suFwd3; public static int Main() { bool local9 = false; sbyte local11 = m_suFwd3; if (local9) { while (local9) { while (local9) m_suFwd3 = 0; } } else { while (local9) throw new Exception(); return 100; } try { } finally { if (local9) throw new IndexOutOfRangeException(); } return 102; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public struct AA { public static sbyte m_suFwd3; public static int Main() { bool local9 = false; sbyte local11 = m_suFwd3; if (local9) { while (local9) { while (local9) m_suFwd3 = 0; } } else { while (local9) throw new Exception(); return 100; } try { } finally { if (local9) throw new IndexOutOfRangeException(); } return 102; } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b37131/b37131.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Permissions/src/System/Diagnostics/EventLogPermissionAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security; using System.Security.Permissions; namespace System.Diagnostics { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = true, Inherited = false)] public class EventLogPermissionAttribute : CodeAccessSecurityAttribute { public EventLogPermissionAttribute(SecurityAction action) : base(action) { } public string MachineName { get { return null; } set { } } public EventLogPermissionAccess PermissionAccess { get; set; } public override IPermission CreatePermission() { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security; using System.Security.Permissions; namespace System.Diagnostics { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = true, Inherited = false)] public class EventLogPermissionAttribute : CodeAccessSecurityAttribute { public EventLogPermissionAttribute(SecurityAction action) : base(action) { } public string MachineName { get { return null; } set { } } public EventLogPermissionAccess PermissionAccess { get; set; } public override IPermission CreatePermission() { return null; } } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/libraries/System.Security.Cryptography.X509Certificates/System.Security.Cryptography.X509Certificates.sln
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{FC10D700-60DF-4D00-9433-47DFC3E3DC26}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Formats.Asn1", "..\System.Formats.Asn1\ref\System.Formats.Asn1.csproj", "{C3DE7458-876F-498F-8731-0458F0E34B9D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Formats.Asn1", "..\System.Formats.Asn1\src\System.Formats.Asn1.csproj", "{C2D74126-653E-41C9-9CF8-E58F1FD110B8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{8A203663-E5D7-494B-93F9-F1205E9164BD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Cng", "..\System.Security.Cryptography.Cng\src\System.Security.Cryptography.Cng.csproj", "{EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Pkcs", "..\System.Security.Cryptography.Pkcs\ref\System.Security.Cryptography.Pkcs.csproj", "{9E04AD65-21BC-4FF4-B38C-9B17488AACA5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Pkcs", "..\System.Security.Cryptography.Pkcs\src\System.Security.Cryptography.Pkcs.csproj", "{76812DB0-A6A2-4F0C-B560-18FC7A97E419}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates", "ref\System.Security.Cryptography.X509Certificates.csproj", "{4EC57148-D181-49B9-BDAF-1735D4687C79}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates", "src\System.Security.Cryptography.X509Certificates.csproj", "{2A203F48-05D2-4E45-8A98-98F02EE639A8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates.Tests", "tests\System.Security.Cryptography.X509Certificates.Tests.csproj", "{53F1E058-B5A4-4348-9BE6-8B006A6861AF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{C79093E1-DEC3-4A35-93CB-216D1E87ACDD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D171D0CF-B04B-4D8A-A678-7BB41E4A96FD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{A00A0A16-D202-49A0-B2C0-C3BB53FA858D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Debug|Any CPU.Build.0 = Debug|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Release|Any CPU.ActiveCfg = Release|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Release|Any CPU.Build.0 = Release|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Debug|Any CPU.Build.0 = Debug|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Release|Any CPU.Build.0 = Release|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Release|Any CPU.ActiveCfg = Release|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Release|Any CPU.Build.0 = Release|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Release|Any CPU.ActiveCfg = Release|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Release|Any CPU.Build.0 = Release|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Release|Any CPU.Build.0 = Release|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Debug|Any CPU.Build.0 = Debug|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Release|Any CPU.ActiveCfg = Release|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Release|Any CPU.Build.0 = Release|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Release|Any CPU.Build.0 = Release|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Debug|Any CPU.Build.0 = Debug|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Release|Any CPU.ActiveCfg = Release|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Release|Any CPU.Build.0 = Release|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Debug|Any CPU.Build.0 = Debug|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Release|Any CPU.ActiveCfg = Release|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Release|Any CPU.Build.0 = Release|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Release|Any CPU.Build.0 = Release|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Debug|Any CPU.Build.0 = Debug|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {FC10D700-60DF-4D00-9433-47DFC3E3DC26} = {E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5} {53F1E058-B5A4-4348-9BE6-8B006A6861AF} = {E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5} {C3DE7458-876F-498F-8731-0458F0E34B9D} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {9E04AD65-21BC-4FF4-B38C-9B17488AACA5} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {4EC57148-D181-49B9-BDAF-1735D4687C79} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {C2D74126-653E-41C9-9CF8-E58F1FD110B8} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {76812DB0-A6A2-4F0C-B560-18FC7A97E419} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {2A203F48-05D2-4E45-8A98-98F02EE639A8} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8} = {A00A0A16-D202-49A0-B2C0-C3BB53FA858D} {8A203663-E5D7-494B-93F9-F1205E9164BD} = {A00A0A16-D202-49A0-B2C0-C3BB53FA858D} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {5ED3739E-C629-4900-BC1B-DF714AB4BB45} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{FC10D700-60DF-4D00-9433-47DFC3E3DC26}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Formats.Asn1", "..\System.Formats.Asn1\ref\System.Formats.Asn1.csproj", "{C3DE7458-876F-498F-8731-0458F0E34B9D}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Formats.Asn1", "..\System.Formats.Asn1\src\System.Formats.Asn1.csproj", "{C2D74126-653E-41C9-9CF8-E58F1FD110B8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{8A203663-E5D7-494B-93F9-F1205E9164BD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Cng", "..\System.Security.Cryptography.Cng\src\System.Security.Cryptography.Cng.csproj", "{EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Pkcs", "..\System.Security.Cryptography.Pkcs\ref\System.Security.Cryptography.Pkcs.csproj", "{9E04AD65-21BC-4FF4-B38C-9B17488AACA5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.Pkcs", "..\System.Security.Cryptography.Pkcs\src\System.Security.Cryptography.Pkcs.csproj", "{76812DB0-A6A2-4F0C-B560-18FC7A97E419}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates", "ref\System.Security.Cryptography.X509Certificates.csproj", "{4EC57148-D181-49B9-BDAF-1735D4687C79}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates", "src\System.Security.Cryptography.X509Certificates.csproj", "{2A203F48-05D2-4E45-8A98-98F02EE639A8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Security.Cryptography.X509Certificates.Tests", "tests\System.Security.Cryptography.X509Certificates.Tests.csproj", "{53F1E058-B5A4-4348-9BE6-8B006A6861AF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{C79093E1-DEC3-4A35-93CB-216D1E87ACDD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D171D0CF-B04B-4D8A-A678-7BB41E4A96FD}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{A00A0A16-D202-49A0-B2C0-C3BB53FA858D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Debug|Any CPU.Build.0 = Debug|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Release|Any CPU.ActiveCfg = Release|Any CPU {FC10D700-60DF-4D00-9433-47DFC3E3DC26}.Release|Any CPU.Build.0 = Release|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Debug|Any CPU.Build.0 = Debug|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3DE7458-876F-498F-8731-0458F0E34B9D}.Release|Any CPU.Build.0 = Release|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Release|Any CPU.ActiveCfg = Release|Any CPU {C2D74126-653E-41C9-9CF8-E58F1FD110B8}.Release|Any CPU.Build.0 = Release|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Release|Any CPU.ActiveCfg = Release|Any CPU {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8}.Release|Any CPU.Build.0 = Release|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Debug|Any CPU.Build.0 = Debug|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Release|Any CPU.ActiveCfg = Release|Any CPU {8A203663-E5D7-494B-93F9-F1205E9164BD}.Release|Any CPU.Build.0 = Release|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Debug|Any CPU.Build.0 = Debug|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Release|Any CPU.ActiveCfg = Release|Any CPU {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357}.Release|Any CPU.Build.0 = Release|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Debug|Any CPU.Build.0 = Debug|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Release|Any CPU.ActiveCfg = Release|Any CPU {9E04AD65-21BC-4FF4-B38C-9B17488AACA5}.Release|Any CPU.Build.0 = Release|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Debug|Any CPU.Build.0 = Debug|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Release|Any CPU.ActiveCfg = Release|Any CPU {76812DB0-A6A2-4F0C-B560-18FC7A97E419}.Release|Any CPU.Build.0 = Release|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Debug|Any CPU.Build.0 = Debug|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Release|Any CPU.ActiveCfg = Release|Any CPU {4EC57148-D181-49B9-BDAF-1735D4687C79}.Release|Any CPU.Build.0 = Release|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Release|Any CPU.ActiveCfg = Release|Any CPU {2A203F48-05D2-4E45-8A98-98F02EE639A8}.Release|Any CPU.Build.0 = Release|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Debug|Any CPU.Build.0 = Debug|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {53F1E058-B5A4-4348-9BE6-8B006A6861AF}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {FC10D700-60DF-4D00-9433-47DFC3E3DC26} = {E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5} {53F1E058-B5A4-4348-9BE6-8B006A6861AF} = {E5625DC8-6D89-4C9C-9AF6-35D0FAE7E4A5} {C3DE7458-876F-498F-8731-0458F0E34B9D} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {9E04AD65-21BC-4FF4-B38C-9B17488AACA5} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {4EC57148-D181-49B9-BDAF-1735D4687C79} = {C79093E1-DEC3-4A35-93CB-216D1E87ACDD} {C2D74126-653E-41C9-9CF8-E58F1FD110B8} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {EEFBEDAF-C620-4C4E-867E-80A1EFEC4357} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {76812DB0-A6A2-4F0C-B560-18FC7A97E419} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {2A203F48-05D2-4E45-8A98-98F02EE639A8} = {D171D0CF-B04B-4D8A-A678-7BB41E4A96FD} {7AD6D18A-FEF8-4E9D-B256-A4B9FD82DFE8} = {A00A0A16-D202-49A0-B2C0-C3BB53FA858D} {8A203663-E5D7-494B-93F9-F1205E9164BD} = {A00A0A16-D202-49A0-B2C0-C3BB53FA858D} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {5ED3739E-C629-4900-BC1B-DF714AB4BB45} EndGlobalSection EndGlobal
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest694/Generated694.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated694 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1166`1<T0> extends class G2_C233`2<!T0,class BaseClass1> { .method public hidebysig newslot virtual instance string ClassMethod3730() cil managed noinlining { ldstr "G3_C1166::ClassMethod3730.14687()" ret } .method public hidebysig newslot virtual instance string ClassMethod3731<M0>() cil managed noinlining { ldstr "G3_C1166::ClassMethod3731.14688<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod3732<M0>() cil managed noinlining { ldstr "G3_C1166::ClassMethod3732.14689<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1803'() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1804'() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1806'<M0>() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1806<[1]>() ldstr "G3_C1166::ClassMethod1806.MI.14692<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C233`2<!T0,class BaseClass1>::.ctor() ret } } .class public G2_C233`2<T0, T1> extends class G1_C3`1<!T1> implements class IBase2`2<!T0,class BaseClass1> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C233::Method7.6917<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1803() cil managed noinlining { ldstr "G2_C233::ClassMethod1803.6918()" ret } .method public hidebysig newslot virtual instance string ClassMethod1804() cil managed noinlining { ldstr "G2_C233::ClassMethod1804.6919()" ret } .method public hidebysig newslot virtual instance string ClassMethod1805<M0>() cil managed noinlining { ldstr "G2_C233::ClassMethod1805.6920<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1806<M0>() cil managed noinlining { ldstr "G2_C233::ClassMethod1806.6921<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1318'() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1319'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1319<[1]>() ldstr "G2_C233::ClassMethod1319.MI.6923<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1320'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1320<[1]>() ldstr "G2_C233::ClassMethod1320.MI.6924<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C3`1<!T1>::.ctor() ret } } .class public G1_C3`1<T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C3::Method7.4785<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "G1_C3::Method7.MI.4786<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1318() cil managed noinlining { ldstr "G1_C3::ClassMethod1318.4787()" ret } .method public hidebysig newslot virtual instance string ClassMethod1319<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1319.4788<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1320<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1320.4789<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated694 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.T<T0,(class G3_C1166`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.T<T0,(class G3_C1166`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.A<(class G3_C1166`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.A<(class G3_C1166`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.B<(class G3_C1166`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.B<(class G3_C1166`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.T.T<T0,T1,(class G2_C233`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.T.T<T0,T1,(class G2_C233`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.T<T1,(class G2_C233`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.T<T1,(class G2_C233`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.A<(class G2_C233`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.A<(class G2_C233`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.B<(class G2_C233`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.B<(class G2_C233`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.T<T1,(class G2_C233`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.T<T1,(class G2_C233`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.A<(class G2_C233`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.A<(class G2_C233`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.B<(class G2_C233`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.B<(class G2_C233`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.T<class BaseClass0,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.A<class G3_C1166`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.B<class G3_C1166`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.A<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.A<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.A<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.A<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.A<class G1_C3`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.B<class G1_C3`1<class BaseClass0>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated694::MethodCallingTest() call void Generated694::ConstrainedCallsTest() call void Generated694::StructConstrainedInterfaceCallsTest() call void Generated694::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated694 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public G3_C1166`1<T0> extends class G2_C233`2<!T0,class BaseClass1> { .method public hidebysig newslot virtual instance string ClassMethod3730() cil managed noinlining { ldstr "G3_C1166::ClassMethod3730.14687()" ret } .method public hidebysig newslot virtual instance string ClassMethod3731<M0>() cil managed noinlining { ldstr "G3_C1166::ClassMethod3731.14688<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod3732<M0>() cil managed noinlining { ldstr "G3_C1166::ClassMethod3732.14689<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1803'() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1804'() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ret } .method public hidebysig newslot virtual instance string 'G2_C233<T0,class BaseClass1>.ClassMethod1806'<M0>() cil managed noinlining { .override method instance string class G2_C233`2<!T0,class BaseClass1>::ClassMethod1806<[1]>() ldstr "G3_C1166::ClassMethod1806.MI.14692<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G2_C233`2<!T0,class BaseClass1>::.ctor() ret } } .class public G2_C233`2<T0, T1> extends class G1_C3`1<!T1> implements class IBase2`2<!T0,class BaseClass1> { .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "G2_C233::Method7.6917<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1803() cil managed noinlining { ldstr "G2_C233::ClassMethod1803.6918()" ret } .method public hidebysig newslot virtual instance string ClassMethod1804() cil managed noinlining { ldstr "G2_C233::ClassMethod1804.6919()" ret } .method public hidebysig newslot virtual instance string ClassMethod1805<M0>() cil managed noinlining { ldstr "G2_C233::ClassMethod1805.6920<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1806<M0>() cil managed noinlining { ldstr "G2_C233::ClassMethod1806.6921<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1318'() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1319'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1319<[1]>() ldstr "G2_C233::ClassMethod1319.MI.6923<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'G1_C3<T1>.ClassMethod1320'<M0>() cil managed noinlining { .override method instance string class G1_C3`1<!T1>::ClassMethod1320<[1]>() ldstr "G2_C233::ClassMethod1320.MI.6924<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void class G1_C3`1<!T1>::.ctor() ret } } .class public G1_C3`1<T0> implements class IBase2`2<class BaseClass0,class BaseClass1> { .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "G1_C3::Method7.4785<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass0,class BaseClass1>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<[1]>() ldstr "G1_C3::Method7.MI.4786<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1318() cil managed noinlining { ldstr "G1_C3::ClassMethod1318.4787()" ret } .method public hidebysig newslot virtual instance string ClassMethod1319<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1319.4788<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string ClassMethod1320<M0>() cil managed noinlining { ldstr "G1_C3::ClassMethod1320.4789<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated694 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.T<T0,(class G3_C1166`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.T<T0,(class G3_C1166`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.A<(class G3_C1166`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.A<(class G3_C1166`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G3_C1166.B<(class G3_C1166`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 16 .locals init (string[] actualResults) ldc.i4.s 11 newarr string stloc.s actualResults ldarg.1 ldstr "M.G3_C1166.B<(class G3_C1166`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 11 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() stelem.ref ldloc.s actualResults ldc.i4.s 8 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() stelem.ref ldloc.s actualResults ldc.i4.s 9 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() stelem.ref ldloc.s actualResults ldc.i4.s 10 ldarga.s 0 constrained. !!W callvirt instance string class G3_C1166`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.T.T<T0,T1,(class G2_C233`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.T.T<T0,T1,(class G2_C233`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.T<T1,(class G2_C233`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.T<T1,(class G2_C233`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.A<(class G2_C233`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.A<(class G2_C233`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.A.B<(class G2_C233`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.A.B<(class G2_C233`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.T<T1,(class G2_C233`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.T<T1,(class G2_C233`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.A<(class G2_C233`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.A<(class G2_C233`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G2_C233.B.B<(class G2_C233`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 13 .locals init (string[] actualResults) ldc.i4.s 8 newarr string stloc.s actualResults ldarg.1 ldstr "M.G2_C233.B.B<(class G2_C233`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 8 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() stelem.ref ldloc.s actualResults ldc.i4.s 4 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() stelem.ref ldloc.s actualResults ldc.i4.s 5 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() stelem.ref ldloc.s actualResults ldc.i4.s 6 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() stelem.ref ldloc.s actualResults ldc.i4.s 7 ldarga.s 0 constrained. !!W callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.T<T0,(class G1_C3`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.A<(class G1_C3`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.G1_C3.B<(class G1_C3`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. !!W callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass0> callvirt instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G3_C1166`1<class BaseClass1> callvirt instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass0,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass0> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G2_C233`2<class BaseClass1,class BaseClass1> callvirt instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass0> callvirt instance string class G1_C3`1<class BaseClass0>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup castclass class G1_C3`1<class BaseClass1> callvirt instance string class G1_C3`1<class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc.0 dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass1,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.B<class G3_C1166`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.T<class BaseClass0,class G3_C1166`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.A<class G3_C1166`1<class BaseClass0>>(!!0,string) newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G3_C1166`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.T<class BaseClass1,class G3_C1166`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G3_C1166::ClassMethod1803.MI.14690()#G3_C1166::ClassMethod1804.MI.14691()#G2_C233::ClassMethod1805.6920<System.Object>()#G3_C1166::ClassMethod1806.MI.14692<System.Object>()#G3_C1166::ClassMethod3730.14687()#G3_C1166::ClassMethod3731.14688<System.Object>()#G3_C1166::ClassMethod3732.14689<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G3_C1166.B<class G3_C1166`1<class BaseClass1>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.A<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass0,class G2_C233`2<class BaseClass0,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.A<class G2_C233`2<class BaseClass0,class BaseClass0>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.T<class BaseClass1,class G2_C233`2<class BaseClass0,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.A.B<class G2_C233`2<class BaseClass0,class BaseClass1>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.A<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass0,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.A<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass0>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G2_C233`2<class BaseClass1,class BaseClass0>>(!!0,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G1_C3.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.A.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::ClassMethod1318.MI.6922()#G2_C233::ClassMethod1319.MI.6923<System.Object>()#G2_C233::ClassMethod1320.MI.6924<System.Object>()#G2_C233::ClassMethod1803.6918()#G2_C233::ClassMethod1804.6919()#G2_C233::ClassMethod1805.6920<System.Object>()#G2_C233::ClassMethod1806.6921<System.Object>()#G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.G2_C233.B.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass1,class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!2,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.T<class BaseClass1,class G2_C233`2<class BaseClass1,class BaseClass1>>(!!1,string) ldloc.0 ldstr "G2_C233::Method7.6917<System.Object>()#" call void Generated694::M.IBase2.B.B<class G2_C233`2<class BaseClass1,class BaseClass1>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass0,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.A<class G1_C3`1<class BaseClass0>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass0>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass0>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.B<class G1_C3`1<class BaseClass0>>(!!0,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::ClassMethod1318.4787()#G1_C3::ClassMethod1319.4788<System.Object>()#G1_C3::ClassMethod1320.4789<System.Object>()#G1_C3::Method7.4785<System.Object>()#" call void Generated694::M.G1_C3.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.T.T<class BaseClass0,class BaseClass1,class G1_C3`1<class BaseClass1>>(!!2,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.T<class BaseClass1,class G1_C3`1<class BaseClass1>>(!!1,string) ldloc.0 ldstr "G1_C3::Method7.MI.4786<System.Object>()#" call void Generated694::M.IBase2.A.B<class G1_C3`1<class BaseClass1>>(!!0,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) newobj instance void class G3_C1166`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3732<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3731<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod3730() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass0>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass0> on type class G3_C1166`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G3_C1166`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3732<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3732.14689<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3731<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3731.14688<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod3730() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod3730.14687()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1806<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1806.MI.14692<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1805<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1804() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1804.MI.14691()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1803() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G3_C1166::ClassMethod1803.MI.14690()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::Method7<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G3_C1166`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G3_C1166`1<class BaseClass1>::ClassMethod1318() calli default string(class G3_C1166`1<class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G3_C1166`1<class BaseClass1> on type class G3_C1166`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass0> on type class G2_C233`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass0,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass0,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass0,class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass0,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass0> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass0>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass0> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass0>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G2_C233`2<class BaseClass1,class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1806<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1806.6921<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1805<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1805.6920<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1804() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1804.6919()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1803() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1803.6918()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1320<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1320.MI.6924<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1319<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1319.MI.6923<System.Object>()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G2_C233`2<class BaseClass1,class BaseClass1> ldloc.0 ldvirtftn instance string class G2_C233`2<class BaseClass1,class BaseClass1>::ClassMethod1318() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::ClassMethod1318.MI.6922()" ldstr "class G2_C233`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(class G2_C233`2<class BaseClass1,class BaseClass1>) ldstr "G2_C233::Method7.6917<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type class G2_C233`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass0>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass0> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass0>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass0> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass0>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) newobj instance void class G1_C3`1<class BaseClass1>::.ctor() stloc.0 ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1320<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1320.4789<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1319<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1319.4788<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::ClassMethod1318() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::ClassMethod1318.4787()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 castclass class G1_C3`1<class BaseClass1> ldloc.0 ldvirtftn instance string class G1_C3`1<class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.4785<System.Object>()" ldstr "class G1_C3`1<class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc.0 ldloc.0 ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(class G1_C3`1<class BaseClass1>) ldstr "G1_C3::Method7.MI.4786<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type class G1_C3`1<class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated694::MethodCallingTest() call void Generated694::ConstrainedCallsTest() call void Generated694::StructConstrainedInterfaceCallsTest() call void Generated694::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,180
Backport docs fixes for Cbor
The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
gewarren
2022-03-04T03:50:30Z
2022-03-07T17:33:11Z
14c3a15145ef465f4f3a2e14270c930142249454
47d419e2a8feb8c03d6dffba1aa9e6f264adb037
Backport docs fixes for Cbor. The `<p>` tags are needed around the separate exception lines, otherwise the newlines are lost on the rendered page: ![image](https://user-images.githubusercontent.com/24882762/156695909-31cc2837-64e0-4bae-b94e-1fed1f3c93d8.png)
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Inequality.UInt32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_InequalityUInt32() { var test = new VectorBooleanBinaryOpTest__op_InequalityUInt32(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__op_InequalityUInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt32> _fld1; public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_InequalityUInt32 testClass) { var result = _fld1 != _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_InequalityUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public VectorBooleanBinaryOpTest__op_InequalityUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr) != Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<UInt32>).GetMethod("op_Inequality", new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 != _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = op1 != op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_InequalityUInt32(); var result = test._fld1 != test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 != _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 != test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] != right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Inequality<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_InequalityUInt32() { var test = new VectorBooleanBinaryOpTest__op_InequalityUInt32(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__op_InequalityUInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt32> _fld1; public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_InequalityUInt32 testClass) { var result = _fld1 != _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_InequalityUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public VectorBooleanBinaryOpTest__op_InequalityUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr) != Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<UInt32>).GetMethod("op_Inequality", new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = _clsVar1 != _clsVar2; ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = op1 != op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_InequalityUInt32(); var result = test._fld1 != test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = _fld1 != _fld2; ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = test._fld1 != test._fld2; ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult |= (left[i] != right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.op_Inequality<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // ConfigurationErrorsExceptionTest.cs // // Author: // Gert Driesen <[email protected]> // // Copyright (C) 2008 Gert Driesen // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Configuration; using System.Configuration.Internal; using System.IO; using System.Text.RegularExpressions; using System.Xml; using Xunit; namespace MonoTests.System.Configuration { public class ConfigurationErrorsExceptionTest { [Fact] // ctor () public void Constructor1() { ConfigurationErrorsException cee = new ConfigurationErrorsException(); Assert.NotNull(cee.BareMessage); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.True(Regex.IsMatch(cee.BareMessage, @"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]"), "#2:" + cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String) public void Constructor2() { string msg; ConfigurationErrorsException cee; msg = "MSG"; cee = new ConfigurationErrorsException(msg); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = null; cee = new ConfigurationErrorsException(msg); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String, Exception) public void Constructor3() { string msg; Exception inner; ConfigurationErrorsException cee; msg = "MSG"; inner = new Exception(); cee = new ConfigurationErrorsException(msg, inner); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = null; inner = null; cee = new ConfigurationErrorsException(msg, inner); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String, XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void Constructor4() { using (var temp = new TempDirectory()) { string msg; XmlNode node; ConfigurationErrorsException cee; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); msg = "MSG"; node = new XmlDocument(); cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new XmlDocument(); doc.Load(xmlfile); msg = "MSG"; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new ConfigXmlDocument(); doc.Load(xmlfile); msg = "MSG"; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Equal(xmlfile, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(1, cee.Line); Assert.Equal(msg + " (" + xmlfile + " line 1)", cee.Message); msg = null; node = null; cee = new ConfigurationErrorsException(msg, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } } [Fact] // ctor (String, Exception, XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void Constructor6() { using (var temp = new TempDirectory()) { string msg; Exception inner; XmlNode node; ConfigurationErrorsException cee; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); msg = "MSG"; inner = new Exception(); node = new XmlDocument(); cee = new ConfigurationErrorsException(msg, inner, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new XmlDocument(); doc.Load(xmlfile); msg = null; inner = null; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); doc = new ConfigXmlDocument(); doc.Load(xmlfile); msg = null; inner = null; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Equal(xmlfile, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(1, cee.Line); Assert.Equal(cee.BareMessage + " (" + xmlfile + " line 1)", cee.Message); msg = null; inner = null; node = null; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } } [Fact] // ctor (String, String, Int32) public void Constructor8() { string msg; string filename; int line; ConfigurationErrorsException cee; msg = "MSG"; filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal("MSG (abc.txt line 7)", cee.Message); msg = null; filename = null; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); msg = null; filename = "abc.txt"; line = 5; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(5, cee.Line); Assert.Equal(cee.BareMessage + " (abc.txt line 5)", cee.Message); msg = "MSG"; filename = null; line = 5; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(5, cee.Line); Assert.Equal(msg + " (line 5)", cee.Message); msg = "MSG"; filename = "abc.txt"; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(msg + " (abc.txt)", cee.Message); msg = null; filename = null; line = 4; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(4, cee.Line); Assert.Equal(cee.BareMessage + " (line 4)", cee.Message); msg = string.Empty; filename = string.Empty; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = string.Empty; filename = "abc.txt"; line = 6; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(6, cee.Line); Assert.Equal(msg + " (abc.txt line 6)", cee.Message); msg = "MSG"; filename = string.Empty; line = 6; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(6, cee.Line); Assert.Equal(msg + " (line 6)", cee.Message); msg = string.Empty; filename = string.Empty; line = 4; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(4, cee.Line); Assert.Equal(msg + " (line 4)", cee.Message); msg = "MSG"; filename = string.Empty; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(msg, cee.Message); } [Fact] // ctor (String, Exception, String, Int32) public void Constructor9() { string msg; Exception inner; string filename; int line; ConfigurationErrorsException cee; msg = "MSG"; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(msg + " (abc.txt line 7)", cee.Message); msg = null; inner = null; filename = null; line = 0; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); msg = null; inner = new Exception(); filename = null; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (line 7)", cee.Message); msg = string.Empty; inner = new Exception(); filename = string.Empty; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(" (line 7)", cee.Message); msg = string.Empty; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(" (abc.txt line 7)", cee.Message); msg = "MSG"; inner = new Exception(); filename = null; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (line 7)", cee.Message); msg = null; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (abc.txt line 7)", cee.Message); } [Fact] // GetFilename (XmlReader) public void GetFilename1_Reader_Null() { XmlReader reader = null; string filename = ConfigurationErrorsException.GetFilename(reader); Assert.Null(filename); } [Fact] // GetFilename (XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void GetFilename2() { using (var temp = new TempDirectory()) { XmlNode node; string filename; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); node = new XmlDocument(); filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); doc = new XmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); doc = new ConfigXmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; filename = ConfigurationErrorsException.GetFilename(node); Assert.Equal(xmlfile, filename); } } [Fact] // GetFilename (XmlNode) public void GetFilename2_Node_Null() { XmlNode node = null; string filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); } [Fact] // GetLineNumber (XmlReader) public void GetLineNumber1() { using (var temp = new TempDirectory()) { string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); using (XmlReader reader = new XmlTextReader(xmlfile)) { int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(0, line); } using (XmlErrorReader reader = new XmlErrorReader(xmlfile)) { int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(666, line); } } } [Fact] // GetLineNumber (XmlReader) public void GetLineNumber1_Reader_Null() { XmlReader reader = null; int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(0, line); } [Fact] // GetLineNumber (XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void GetLineNumber2() { using (var temp = new TempDirectory()) { XmlNode node; int line; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); node = new XmlDocument(); line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); doc = new XmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); doc = new ConfigXmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(1, line); } } [Fact] // GetLineNumber (XmlNode) public void GetLineNumber2_Node_Null() { XmlNode node = null; int line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); } class XmlErrorReader : XmlTextReader, IConfigErrorInfo { public XmlErrorReader(string filename) : base(filename) { } string IConfigErrorInfo.Filename { get { return "FILE"; } } int IConfigErrorInfo.LineNumber { get { return 666; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // ConfigurationErrorsExceptionTest.cs // // Author: // Gert Driesen <[email protected]> // // Copyright (C) 2008 Gert Driesen // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Configuration; using System.Configuration.Internal; using System.IO; using System.Text.RegularExpressions; using System.Xml; using Xunit; namespace MonoTests.System.Configuration { public class ConfigurationErrorsExceptionTest { [Fact] // ctor () public void Constructor1() { ConfigurationErrorsException cee = new ConfigurationErrorsException(); Assert.NotNull(cee.BareMessage); // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po Assert.Matches(@"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]", cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String) public void Constructor2() { string msg; ConfigurationErrorsException cee; msg = "MSG"; cee = new ConfigurationErrorsException(msg); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = null; cee = new ConfigurationErrorsException(msg); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String, Exception) public void Constructor3() { string msg; Exception inner; ConfigurationErrorsException cee; msg = "MSG"; inner = new Exception(); cee = new ConfigurationErrorsException(msg, inner); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = null; inner = null; cee = new ConfigurationErrorsException(msg, inner); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } [Fact] // ctor (String, XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void Constructor4() { using (var temp = new TempDirectory()) { string msg; XmlNode node; ConfigurationErrorsException cee; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); msg = "MSG"; node = new XmlDocument(); cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new XmlDocument(); doc.Load(xmlfile); msg = "MSG"; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new ConfigXmlDocument(); doc.Load(xmlfile); msg = "MSG"; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Equal(xmlfile, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(1, cee.Line); Assert.Equal(msg + " (" + xmlfile + " line 1)", cee.Message); msg = null; node = null; cee = new ConfigurationErrorsException(msg, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } } [Fact] // ctor (String, Exception, XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void Constructor6() { using (var temp = new TempDirectory()) { string msg; Exception inner; XmlNode node; ConfigurationErrorsException cee; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); msg = "MSG"; inner = new Exception(); node = new XmlDocument(); cee = new ConfigurationErrorsException(msg, inner, node); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); doc = new XmlDocument(); doc.Load(xmlfile); msg = null; inner = null; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); doc = new ConfigXmlDocument(); doc.Load(xmlfile); msg = null; inner = null; node = doc.DocumentElement; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Equal(xmlfile, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(1, cee.Line); Assert.Equal(cee.BareMessage + " (" + xmlfile + " line 1)", cee.Message); msg = null; inner = null; node = null; cee = new ConfigurationErrorsException(msg, inner, node); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Null(cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); } } [Fact] // ctor (String, String, Int32) public void Constructor8() { string msg; string filename; int line; ConfigurationErrorsException cee; msg = "MSG"; filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal("MSG (abc.txt line 7)", cee.Message); msg = null; filename = null; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); msg = null; filename = "abc.txt"; line = 5; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(5, cee.Line); Assert.Equal(cee.BareMessage + " (abc.txt line 5)", cee.Message); msg = "MSG"; filename = null; line = 5; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(5, cee.Line); Assert.Equal(msg + " (line 5)", cee.Message); msg = "MSG"; filename = "abc.txt"; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(msg + " (abc.txt)", cee.Message); msg = null; filename = null; line = 4; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(4, cee.Line); Assert.Equal(cee.BareMessage + " (line 4)", cee.Message); msg = string.Empty; filename = string.Empty; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Same(msg, cee.Message); msg = string.Empty; filename = "abc.txt"; line = 6; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(6, cee.Line); Assert.Equal(msg + " (abc.txt line 6)", cee.Message); msg = "MSG"; filename = string.Empty; line = 6; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(6, cee.Line); Assert.Equal(msg + " (line 6)", cee.Message); msg = string.Empty; filename = string.Empty; line = 4; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(4, cee.Line); Assert.Equal(msg + " (line 4)", cee.Message); msg = "MSG"; filename = string.Empty; line = 0; cee = new ConfigurationErrorsException(msg, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Null(cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(msg, cee.Message); } [Fact] // ctor (String, Exception, String, Int32) public void Constructor9() { string msg; Exception inner; string filename; int line; ConfigurationErrorsException cee; msg = "MSG"; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(msg + " (abc.txt line 7)", cee.Message); msg = null; inner = null; filename = null; line = 0; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(0, cee.Line); Assert.Equal(cee.BareMessage, cee.Message); msg = null; inner = new Exception(); filename = null; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (line 7)", cee.Message); msg = string.Empty; inner = new Exception(); filename = string.Empty; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(" (line 7)", cee.Message); msg = string.Empty; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(" (abc.txt line 7)", cee.Message); msg = "MSG"; inner = new Exception(); filename = null; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Same(msg, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (line 7)", cee.Message); msg = null; inner = new Exception(); filename = "abc.txt"; line = 7; cee = new ConfigurationErrorsException(msg, inner, filename, line); Assert.Equal(new ConfigurationErrorsException().Message, cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); Assert.Same(filename, cee.Filename); Assert.Same(inner, cee.InnerException); Assert.Equal(line, cee.Line); Assert.Equal(cee.BareMessage + " (abc.txt line 7)", cee.Message); } [Fact] // GetFilename (XmlReader) public void GetFilename1_Reader_Null() { XmlReader reader = null; string filename = ConfigurationErrorsException.GetFilename(reader); Assert.Null(filename); } [Fact] // GetFilename (XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void GetFilename2() { using (var temp = new TempDirectory()) { XmlNode node; string filename; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); node = new XmlDocument(); filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); doc = new XmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); doc = new ConfigXmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; filename = ConfigurationErrorsException.GetFilename(node); Assert.Equal(xmlfile, filename); } } [Fact] // GetFilename (XmlNode) public void GetFilename2_Node_Null() { XmlNode node = null; string filename = ConfigurationErrorsException.GetFilename(node); Assert.Null(filename); } [Fact] // GetLineNumber (XmlReader) public void GetLineNumber1() { using (var temp = new TempDirectory()) { string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); using (XmlReader reader = new XmlTextReader(xmlfile)) { int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(0, line); } using (XmlErrorReader reader = new XmlErrorReader(xmlfile)) { int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(666, line); } } } [Fact] // GetLineNumber (XmlReader) public void GetLineNumber1_Reader_Null() { XmlReader reader = null; int line = ConfigurationErrorsException.GetLineNumber(reader); Assert.Equal(0, line); } [Fact] // GetLineNumber (XmlNode) // Doesn't pass on Mono // [Category("NotWorking")] public void GetLineNumber2() { using (var temp = new TempDirectory()) { XmlNode node; int line; string xmlfile = Path.Combine(temp.Path, "test.xml"); XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("test")); doc.Save(xmlfile); node = new XmlDocument(); line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); doc = new XmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); doc = new ConfigXmlDocument(); doc.Load(xmlfile); node = doc.DocumentElement; line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(1, line); } } [Fact] // GetLineNumber (XmlNode) public void GetLineNumber2_Node_Null() { XmlNode node = null; int line = ConfigurationErrorsException.GetLineNumber(node); Assert.Equal(0, line); } class XmlErrorReader : XmlTextReader, IConfigErrorInfo { public XmlErrorReader(string filename) : base(filename) { } string IConfigErrorInfo.Filename { get { return "FILE"; } } int IConfigErrorInfo.LineNumber { get { return 666; } } } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Diagnostics { public static class Ignored { public static StackTrace Method() => new StackTrace(); public static StackTrace MethodWithException() { try { throw new Exception(); } catch (Exception exception) { return new StackTrace(exception); } } } } namespace System.Diagnostics.Tests { public class StackTraceTests { [Fact] public void MethodsToSkip_Get_ReturnsZero() { Assert.Equal(0, StackTrace.METHODS_TO_SKIP); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public void Ctor_Default() { var stackTrace = new StackTrace(); VerifyFrames(stackTrace, false); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(true)] [InlineData(false)] public void Ctor_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(fNeedFileInfo); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0)] [InlineData(1)] public void Ctor_SkipFrames(int skipFrames) { var emptyStackTrace = new StackTrace(); IEnumerable<MethodBase> expectedMethods = emptyStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(skipFrames); Assert.Equal(emptyStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); Assert.Equal(expectedMethods, stackTrace.GetFrames().Select(f => f.GetMethod())); VerifyFrames(stackTrace, false); } [Fact] public void Ctor_LargeSkipFrames_GetFramesReturnsEmtpy() { var stackTrace = new StackTrace(int.MaxValue); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0, true)] [InlineData(1, true)] [InlineData(0, false)] [InlineData(1, false)] public void Ctor_SkipFrames_FNeedFileInfo(int skipFrames, bool fNeedFileInfo) { var emptyStackTrace = new StackTrace(); IEnumerable<MethodBase> expectedMethods = emptyStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(skipFrames, fNeedFileInfo); Assert.Equal(emptyStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); Assert.Equal(expectedMethods, stackTrace.GetFrames().Select(f => f.GetMethod())); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_LargeSkipFramesFNeedFileInfo_GetFramesReturnsEmpty(bool fNeedFileInfo) { var stackTrace = new StackTrace(int.MaxValue, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public void Ctor_ThrownException_GetFramesReturnsExpected() { var stackTrace = new StackTrace(InvokeException()); VerifyFrames(stackTrace, false); } [Fact] public void Ctor_EmptyException_GetFramesReturnsEmpty() { var exception = new Exception(); var stackTrace = new StackTrace(exception); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(true)] [InlineData(false)] public void Ctor_Bool_ThrownException_GetFramesReturnsExpected(bool fNeedFileInfo) { var stackTrace = new StackTrace(InvokeException(), fNeedFileInfo); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_EmptyException_FNeedFileInfo(bool fNeedFileInfo) { var exception = new Exception(); var stackTrace = new StackTrace(exception, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31796", TestRuntimes.Mono)] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0)] [InlineData(1)] public void Ctor_Exception_SkipFrames(int skipFrames) { Exception ex = InvokeException(); var exceptionStackTrace = new StackTrace(ex); IEnumerable<MethodBase> expectedMethods = exceptionStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(ex, skipFrames); Assert.Equal(exceptionStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); // .NET Framework has null Frames if skipping frames in Release mode. StackFrame[] frames = stackTrace.GetFrames(); Assert.Equal(expectedMethods, frames.Select(f => f.GetMethod())); if (frames != null) { VerifyFrames(stackTrace, false); } } [Fact] public void Ctor_Exception_LargeSkipFrames() { var stackTrace = new StackTrace(InvokeException(), int.MaxValue); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Fact] public void Ctor_EmptyException_SkipFrames() { var stackTrace = new StackTrace(new Exception(), 0); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31796", TestRuntimes.Mono)] [InlineData(0, true)] [InlineData(1, true)] [InlineData(0, false)] [InlineData(1, false)] public void Ctor_Exception_SkipFrames_FNeedFileInfo(int skipFrames, bool fNeedFileInfo) { Exception ex = InvokeException(); var exceptionStackTrace = new StackTrace(ex); IEnumerable<MethodBase> expectedMethods = exceptionStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(ex, skipFrames, fNeedFileInfo); // .NET Framework has null Frames if skipping frames in Release mode. StackFrame[] frames = stackTrace.GetFrames(); Assert.Equal(expectedMethods, frames.Select(f => f.GetMethod())); if (frames != null) { VerifyFrames(stackTrace, fNeedFileInfo); } } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Exception_LargeSkipFrames_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(InvokeException(), int.MaxValue, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_EmptyException_SkipFrames_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(new Exception(), 0, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Fact] public void Ctor_NullException_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace((Exception)null)); AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace((Exception)null, false)); AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace(null, 1)); } public static IEnumerable<object[]> Ctor_Frame_TestData() { yield return new object[] { new StackFrame() }; yield return new object[] { null }; } [Theory] [MemberData(nameof(Ctor_Frame_TestData))] public void Ctor_Frame(StackFrame stackFrame) { var stackTrace = new StackTrace(stackFrame); Assert.Equal(1, stackTrace.FrameCount); Assert.Equal(new StackFrame[] { stackFrame }, stackTrace.GetFrames()); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new StackTrace(InvokeException()), "System.Diagnostics.Tests.StackTraceTests.ThrowException()" }; yield return new object[] { new StackTrace(new Exception()), "" }; yield return new object[] { NoParameters(), "System.Diagnostics.Tests.StackTraceTests.NoParameters()" }; yield return new object[] { OneParameter(1), "System.Diagnostics.Tests.StackTraceTests.OneParameter(Int32 x)" }; yield return new object[] { TwoParameters(1, null), "System.Diagnostics.Tests.StackTraceTests.TwoParameters(Int32 x, String y)" }; yield return new object[] { Generic<int>(), "System.Diagnostics.Tests.StackTraceTests.Generic[T]()" }; yield return new object[] { Generic<int, string>(), "System.Diagnostics.Tests.StackTraceTests.Generic[T,U]()" }; yield return new object[] { new ClassWithConstructor().StackTrace, "System.Diagnostics.Tests.StackTraceTests.ClassWithConstructor..ctor()" }; // Methods belonging to the System.Diagnostics namespace are ignored. yield return new object[] { InvokeIgnoredMethod(), "System.Diagnostics.Tests.StackTraceTests.InvokeIgnoredMethod()" }; yield return new object[] { InvokeIgnoredMethodWithException(), "System.Diagnostics.Ignored.MethodWithException()" }; } [Fact] public void GetFrame_InvalidIndex_ReturnsNull() { var stackTrace = new StackTrace(); Assert.Null(stackTrace.GetFrame(-1)); Assert.Null(stackTrace.GetFrame(stackTrace.FrameCount)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31797", TestRuntimes.Mono)] [MemberData(nameof(ToString_TestData))] public void ToString_Invoke_ReturnsExpected(StackTrace stackTrace, string expectedToString) { if (expectedToString.Length == 0) { Assert.Equal(Environment.NewLine, stackTrace.ToString()); } else { string toString = stackTrace.ToString(); Assert.Contains(expectedToString, toString); Assert.EndsWith(Environment.NewLine, toString); string[] frames = toString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // StackTrace pretty printer omits uninteresting frames from the formatted stacktrace AssertExtensions.LessThanOrEqualTo(frames.Length, stackTrace.FrameCount); } } [Fact] public void ToString_NullFrame_ThrowsNullReferenceException() { var stackTrace = new StackTrace((StackFrame)null); Assert.Equal(Environment.NewLine, stackTrace.ToString()); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/11354", TestRuntimes.Mono)] public unsafe void ToString_FunctionPointerSignature() { // This is sepate from ToString_Invoke_ReturnsExpected since unsafe cannot be used for iterators var stackTrace = FunctionPointerParameter(null); Assert.Contains("System.Diagnostics.Tests.StackTraceTests.FunctionPointerParameter(IntPtr x)", stackTrace.ToString()); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void ToString_ShowILOffset() { string AssemblyName = "ExceptionTestAssembly.dll"; string SourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, AssemblyName); string regPattern = @":token 0x([a-f0-9]*)\+0x([a-f0-9]*)"; // Normal loading case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var asm = Assembly.LoadFrom(asmPath); try { asm.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // Assembly.Load(Byte[]) case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var inMemBlob = File.ReadAllBytes(asmPath); var asm2 = Assembly.Load(inMemBlob); try { asm2.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // AssmblyBuilder.DefineDynamicAssembly() case RemoteExecutor.Invoke((p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); AssemblyName asmName = new AssemblyName("ExceptionTestAssembly"); AssemblyBuilder asmBldr = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(asmName.Name); TypeBuilder tBldr = modBldr.DefineType("Program"); MethodBuilder mBldr = tBldr.DefineMethod("Foo", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilGen = mBldr.GetILGenerator(); ilGen.ThrowException(typeof(NullReferenceException)); ilGen.Emit(OpCodes.Ret); Type t = tBldr.CreateType(); try { t.InvokeMember("Foo", BindingFlags.InvokeMethod, null, null, null); } catch (Exception e) { Assert.Contains("RefEmit_InMemoryManifestModule", e.InnerException.StackTrace); Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); } }, regPattern).Dispose(); } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace NoParameters() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace OneParameter(int x) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace TwoParameters(int x, string y) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private unsafe static StackTrace FunctionPointerParameter(delegate*<void> x) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace Generic<T>() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace Generic<T, U>() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace InvokeIgnoredMethod() => Ignored.Method(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace InvokeIgnoredMethodWithException() => Ignored.MethodWithException(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static Exception InvokeException() { try { ThrowException(); return null; } catch (Exception ex) { return ex; } } private static void ThrowException() => throw new Exception(); private class ClassWithConstructor { public StackTrace StackTrace { get; } [MethodImpl(MethodImplOptions.NoInlining)] public ClassWithConstructor() => StackTrace = new StackTrace(); } private static void VerifyFrames(StackTrace stackTrace, bool hasFileInfo) { Assert.True(stackTrace.FrameCount > 0); StackFrame[] stackFrames = stackTrace.GetFrames(); Assert.Equal(stackTrace.FrameCount, stackFrames.Length); for (int i = 0; i < stackFrames.Length; i++) { StackFrame stackFrame = stackFrames[i]; if (!hasFileInfo) { Assert.Null(stackFrame.GetFileName()); Assert.Equal(0, stackFrame.GetFileLineNumber()); Assert.Equal(0, stackFrame.GetFileColumnNumber()); } Assert.NotNull(stackFrame.GetMethod()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Diagnostics { public static class Ignored { public static StackTrace Method() => new StackTrace(); public static StackTrace MethodWithException() { try { throw new Exception(); } catch (Exception exception) { return new StackTrace(exception); } } } } namespace System.Diagnostics.Tests { public class StackTraceTests { [Fact] public void MethodsToSkip_Get_ReturnsZero() { Assert.Equal(0, StackTrace.METHODS_TO_SKIP); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public void Ctor_Default() { var stackTrace = new StackTrace(); VerifyFrames(stackTrace, false); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(true)] [InlineData(false)] public void Ctor_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(fNeedFileInfo); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0)] [InlineData(1)] public void Ctor_SkipFrames(int skipFrames) { var emptyStackTrace = new StackTrace(); IEnumerable<MethodBase> expectedMethods = emptyStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(skipFrames); Assert.Equal(emptyStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); Assert.Equal(expectedMethods, stackTrace.GetFrames().Select(f => f.GetMethod())); VerifyFrames(stackTrace, false); } [Fact] public void Ctor_LargeSkipFrames_GetFramesReturnsEmtpy() { var stackTrace = new StackTrace(int.MaxValue); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0, true)] [InlineData(1, true)] [InlineData(0, false)] [InlineData(1, false)] public void Ctor_SkipFrames_FNeedFileInfo(int skipFrames, bool fNeedFileInfo) { var emptyStackTrace = new StackTrace(); IEnumerable<MethodBase> expectedMethods = emptyStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(skipFrames, fNeedFileInfo); Assert.Equal(emptyStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); Assert.Equal(expectedMethods, stackTrace.GetFrames().Select(f => f.GetMethod())); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_LargeSkipFramesFNeedFileInfo_GetFramesReturnsEmpty(bool fNeedFileInfo) { var stackTrace = new StackTrace(int.MaxValue, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public void Ctor_ThrownException_GetFramesReturnsExpected() { var stackTrace = new StackTrace(InvokeException()); VerifyFrames(stackTrace, false); } [Fact] public void Ctor_EmptyException_GetFramesReturnsEmpty() { var exception = new Exception(); var stackTrace = new StackTrace(exception); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(true)] [InlineData(false)] public void Ctor_Bool_ThrownException_GetFramesReturnsExpected(bool fNeedFileInfo) { var stackTrace = new StackTrace(InvokeException(), fNeedFileInfo); VerifyFrames(stackTrace, fNeedFileInfo); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_EmptyException_FNeedFileInfo(bool fNeedFileInfo) { var exception = new Exception(); var stackTrace = new StackTrace(exception, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31796", TestRuntimes.Mono)] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] [InlineData(0)] [InlineData(1)] public void Ctor_Exception_SkipFrames(int skipFrames) { Exception ex = InvokeException(); var exceptionStackTrace = new StackTrace(ex); IEnumerable<MethodBase> expectedMethods = exceptionStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(ex, skipFrames); Assert.Equal(exceptionStackTrace.FrameCount - skipFrames, stackTrace.FrameCount); // .NET Framework has null Frames if skipping frames in Release mode. StackFrame[] frames = stackTrace.GetFrames(); Assert.Equal(expectedMethods, frames.Select(f => f.GetMethod())); if (frames != null) { VerifyFrames(stackTrace, false); } } [Fact] public void Ctor_Exception_LargeSkipFrames() { var stackTrace = new StackTrace(InvokeException(), int.MaxValue); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Fact] public void Ctor_EmptyException_SkipFrames() { var stackTrace = new StackTrace(new Exception(), 0); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31796", TestRuntimes.Mono)] [InlineData(0, true)] [InlineData(1, true)] [InlineData(0, false)] [InlineData(1, false)] public void Ctor_Exception_SkipFrames_FNeedFileInfo(int skipFrames, bool fNeedFileInfo) { Exception ex = InvokeException(); var exceptionStackTrace = new StackTrace(ex); IEnumerable<MethodBase> expectedMethods = exceptionStackTrace.GetFrames().Skip(skipFrames).Select(f => f.GetMethod()); var stackTrace = new StackTrace(ex, skipFrames, fNeedFileInfo); // .NET Framework has null Frames if skipping frames in Release mode. StackFrame[] frames = stackTrace.GetFrames(); Assert.Equal(expectedMethods, frames.Select(f => f.GetMethod())); if (frames != null) { VerifyFrames(stackTrace, fNeedFileInfo); } } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_Exception_LargeSkipFrames_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(InvokeException(), int.MaxValue, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); } [Theory] [InlineData(true)] [InlineData(false)] public void Ctor_EmptyException_SkipFrames_FNeedFileInfo(bool fNeedFileInfo) { var stackTrace = new StackTrace(new Exception(), 0, fNeedFileInfo); Assert.Equal(0, stackTrace.FrameCount); Assert.Empty(stackTrace.GetFrames()); Assert.Null(stackTrace.GetFrame(0)); } [Fact] public void Ctor_NullException_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace((Exception)null)); AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace((Exception)null, false)); AssertExtensions.Throws<ArgumentNullException>("e", () => new StackTrace(null, 1)); } public static IEnumerable<object[]> Ctor_Frame_TestData() { yield return new object[] { new StackFrame() }; yield return new object[] { null }; } [Theory] [MemberData(nameof(Ctor_Frame_TestData))] public void Ctor_Frame(StackFrame stackFrame) { var stackTrace = new StackTrace(stackFrame); Assert.Equal(1, stackTrace.FrameCount); Assert.Equal(new StackFrame[] { stackFrame }, stackTrace.GetFrames()); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new StackTrace(InvokeException()), "System.Diagnostics.Tests.StackTraceTests.ThrowException()" }; yield return new object[] { new StackTrace(new Exception()), "" }; yield return new object[] { NoParameters(), "System.Diagnostics.Tests.StackTraceTests.NoParameters()" }; yield return new object[] { OneParameter(1), "System.Diagnostics.Tests.StackTraceTests.OneParameter(Int32 x)" }; yield return new object[] { TwoParameters(1, null), "System.Diagnostics.Tests.StackTraceTests.TwoParameters(Int32 x, String y)" }; yield return new object[] { Generic<int>(), "System.Diagnostics.Tests.StackTraceTests.Generic[T]()" }; yield return new object[] { Generic<int, string>(), "System.Diagnostics.Tests.StackTraceTests.Generic[T,U]()" }; yield return new object[] { new ClassWithConstructor().StackTrace, "System.Diagnostics.Tests.StackTraceTests.ClassWithConstructor..ctor()" }; // Methods belonging to the System.Diagnostics namespace are ignored. yield return new object[] { InvokeIgnoredMethod(), "System.Diagnostics.Tests.StackTraceTests.InvokeIgnoredMethod()" }; yield return new object[] { InvokeIgnoredMethodWithException(), "System.Diagnostics.Ignored.MethodWithException()" }; } [Fact] public void GetFrame_InvalidIndex_ReturnsNull() { var stackTrace = new StackTrace(); Assert.Null(stackTrace.GetFrame(-1)); Assert.Null(stackTrace.GetFrame(stackTrace.FrameCount)); } [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/31797", TestRuntimes.Mono)] [MemberData(nameof(ToString_TestData))] public void ToString_Invoke_ReturnsExpected(StackTrace stackTrace, string expectedToString) { if (expectedToString.Length == 0) { Assert.Equal(Environment.NewLine, stackTrace.ToString()); } else { string toString = stackTrace.ToString(); Assert.Contains(expectedToString, toString); Assert.EndsWith(Environment.NewLine, toString); string[] frames = toString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // StackTrace pretty printer omits uninteresting frames from the formatted stacktrace AssertExtensions.LessThanOrEqualTo(frames.Length, stackTrace.FrameCount); } } [Fact] public void ToString_NullFrame_ThrowsNullReferenceException() { var stackTrace = new StackTrace((StackFrame)null); Assert.Equal(Environment.NewLine, stackTrace.ToString()); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/11354", TestRuntimes.Mono)] public unsafe void ToString_FunctionPointerSignature() { // This is sepate from ToString_Invoke_ReturnsExpected since unsafe cannot be used for iterators var stackTrace = FunctionPointerParameter(null); Assert.Contains("System.Diagnostics.Tests.StackTraceTests.FunctionPointerParameter(IntPtr x)", stackTrace.ToString()); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void ToString_ShowILOffset() { string AssemblyName = "ExceptionTestAssembly.dll"; string SourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, AssemblyName); string regPattern = @":token 0x([a-f0-9]*)\+0x([a-f0-9]*)"; // Normal loading case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var asm = Assembly.LoadFrom(asmPath); try { asm.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // Assembly.Load(Byte[]) case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var inMemBlob = File.ReadAllBytes(asmPath); var asm2 = Assembly.Load(inMemBlob); try { asm2.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // AssmblyBuilder.DefineDynamicAssembly() case RemoteExecutor.Invoke((p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); AssemblyName asmName = new AssemblyName("ExceptionTestAssembly"); AssemblyBuilder asmBldr = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(asmName.Name); TypeBuilder tBldr = modBldr.DefineType("Program"); MethodBuilder mBldr = tBldr.DefineMethod("Foo", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilGen = mBldr.GetILGenerator(); ilGen.ThrowException(typeof(NullReferenceException)); ilGen.Emit(OpCodes.Ret); Type t = tBldr.CreateType(); try { t.InvokeMember("Foo", BindingFlags.InvokeMethod, null, null, null); } catch (Exception e) { Assert.Contains("RefEmit_InMemoryManifestModule", e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, regPattern).Dispose(); } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace NoParameters() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace OneParameter(int x) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace TwoParameters(int x, string y) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private unsafe static StackTrace FunctionPointerParameter(delegate*<void> x) => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace Generic<T>() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace Generic<T, U>() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace InvokeIgnoredMethod() => Ignored.Method(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace InvokeIgnoredMethodWithException() => Ignored.MethodWithException(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static Exception InvokeException() { try { ThrowException(); return null; } catch (Exception ex) { return ex; } } private static void ThrowException() => throw new Exception(); private class ClassWithConstructor { public StackTrace StackTrace { get; } [MethodImpl(MethodImplOptions.NoInlining)] public ClassWithConstructor() => StackTrace = new StackTrace(); } private static void VerifyFrames(StackTrace stackTrace, bool hasFileInfo) { Assert.True(stackTrace.FrameCount > 0); StackFrame[] stackFrames = stackTrace.GetFrames(); Assert.Equal(stackTrace.FrameCount, stackFrames.Length); for (int i = 0; i < stackFrames.Length; i++) { StackFrame stackFrame = stackFrames[i]; if (!hasFileInfo) { Assert.Null(stackFrame.GetFileName()); Assert.Equal(0, stackFrame.GetFileLineNumber()); Assert.Equal(0, stackFrame.GetFileColumnNumber()); } Assert.NotNull(stackFrame.GetMethod()); } } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; namespace BasicEventSourceTests { /// <summary> /// Tests the user experience for common user errors. /// </summary> public partial class TestsUserErrors { /// <summary> /// Try to pass a user defined class (even with EventData) /// to a manifest based eventSource /// </summary> [Fact] public void Test_BadTypes_Manifest_UserClass() { var badEventSource = new BadEventSource_Bad_Type_UserClass(); Test_BadTypes_Manifest(badEventSource); } private void Test_BadTypes_Manifest(EventSource source) { try { using (var listener = new EventListenerListener()) { var events = new List<Event>(); Debug.WriteLine("Adding delegate to onevent"); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(source.Name, EventCommand.Enable); listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " Assert.Matches("Unsupported type", message); } } finally { source.Dispose(); } } /// <summary> /// Test the /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/runtime/issues/26197 [ActiveIssue("https://github.com/dotnet/runtime/issues/51382", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void Test_BadEventSource_MismatchedIds() { TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new List<Func<Listener>>(); listenerGenerators.Add(() => new EventListenerListener()); var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func<Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// A helper that can run the test under a variety of conditions /// * Whether the eventSource is enabled at startup /// * Whether the listener is ETW or an EventListern /// * Whether the ETW output is self describing or not. /// </summary> private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings) { var eventSourceName = typeof(BadEventSource_MismatchedIds).Name; Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")"); // Activate the source before the source exists (if told to). if (onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; using (var source = new BadEventSource_MismatchedIds(settings)) { Assert.Equal(eventSourceName, source.Name); // activate the source after the source exists (if told to). if (!onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); source.Event1(1); // Try to send something. } listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); Debug.WriteLine(string.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. " if (!PlatformDetection.IsNetFramework) // .NET Framework has typo Assert.Matches("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message); // Validate the details of the EventWrittenEventArgs object if (_event is EventListenerListener.EventListenerEvent elEvent) { EventWrittenEventArgs ea = elEvent.Data; Assert.NotNull(ea); Assert.Equal(EventSource.CurrentThreadActivityId, ea.ActivityId); Assert.Equal(EventChannel.None, ea.Channel); Assert.Equal(0, ea.EventId); Assert.Equal("EventSourceMessage", ea.EventName); Assert.NotNull(ea.EventSource); Assert.Equal(EventKeywords.None, ea.Keywords); Assert.Equal(EventLevel.LogAlways, ea.Level); Assert.Equal((EventOpcode)0, ea.Opcode); Assert.NotNull(ea.Payload); Assert.NotNull(ea.PayloadNames); Assert.Equal(ea.PayloadNames.Count, ea.Payload.Count); Assert.Equal(Guid.Empty, ea.RelatedActivityId); Assert.Equal(EventTags.None, ea.Tags); Assert.Equal(EventTask.None, ea.Task); Assert.InRange(ea.TimeStamp, DateTime.MinValue, DateTime.MaxValue); Assert.Equal(0, ea.Version); } } [Fact] public void Test_Bad_WriteRelatedID_ParameterName() { #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null; EventListenerListener listener = null; try { Guid oldGuid; Guid newGuid = Guid.NewGuid(); Guid newGuid2 = Guid.NewGuid(); EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter(); using (var listener = new EventListenerListener()) { var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(bes.Name, EventCommand.Enable); bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.")); } } finally { if (bes != null) { bes.Dispose(); } if (listener != null) { listener.Dispose(); } } #endif } } /// <summary> /// This EventSource has a common user error, and we want to make sure EventSource /// gives a reasonable experience in that case. /// </summary> internal class BadEventSource_MismatchedIds : EventSource { public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { } public void Event1(int arg) { WriteEvent(1, arg); } // Error Used the same event ID for this event. public void Event2(int arg) { WriteEvent(1, arg); } } /// <summary> /// A manifest based provider with a bad type byte[] /// </summary> internal class BadEventSource_Bad_Type_ByteArray : EventSource { public void Event1(byte[] myArray) { WriteEvent(1, myArray); } } public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource { public void E2() { this.Write("sampleevent", new { a = "a string" }); } [Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)] public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId) { WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId); } public class Keywords { public const EventKeywords Debug = (EventKeywords)0x0002; } } [EventData] public class UserClass { public int i; }; /// <summary> /// A manifest based provider with a bad type (only supported in self describing) /// </summary> internal class BadEventSource_Bad_Type_UserClass : EventSource { public void Event1(UserClass myClass) { WriteEvent(1, myClass); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; namespace BasicEventSourceTests { /// <summary> /// Tests the user experience for common user errors. /// </summary> public partial class TestsUserErrors { /// <summary> /// Try to pass a user defined class (even with EventData) /// to a manifest based eventSource /// </summary> [Fact] public void Test_BadTypes_Manifest_UserClass() { var badEventSource = new BadEventSource_Bad_Type_UserClass(); Test_BadTypes_Manifest(badEventSource); } private void Test_BadTypes_Manifest(EventSource source) { try { using (var listener = new EventListenerListener()) { var events = new List<Event>(); Debug.WriteLine("Adding delegate to onevent"); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(source.Name, EventCommand.Enable); listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " Assert.Contains("Unsupported type", message); } } finally { source.Dispose(); } } /// <summary> /// Test the /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // ActiveIssue: https://github.com/dotnet/runtime/issues/26197 [ActiveIssue("https://github.com/dotnet/runtime/issues/51382", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void Test_BadEventSource_MismatchedIds() { TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new List<Func<Listener>>(); listenerGenerators.Add(() => new EventListenerListener()); var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func<Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// A helper that can run the test under a variety of conditions /// * Whether the eventSource is enabled at startup /// * Whether the listener is ETW or an EventListern /// * Whether the ETW output is self describing or not. /// </summary> private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings) { var eventSourceName = typeof(BadEventSource_MismatchedIds).Name; Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")"); // Activate the source before the source exists (if told to). if (onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; using (var source = new BadEventSource_MismatchedIds(settings)) { Assert.Equal(eventSourceName, source.Name); // activate the source after the source exists (if told to). if (!onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); source.Event1(1); // Try to send something. } listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); Debug.WriteLine(string.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. " if (!PlatformDetection.IsNetFramework) // .NET Framework has typo Assert.Contains("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message); // Validate the details of the EventWrittenEventArgs object if (_event is EventListenerListener.EventListenerEvent elEvent) { EventWrittenEventArgs ea = elEvent.Data; Assert.NotNull(ea); Assert.Equal(EventSource.CurrentThreadActivityId, ea.ActivityId); Assert.Equal(EventChannel.None, ea.Channel); Assert.Equal(0, ea.EventId); Assert.Equal("EventSourceMessage", ea.EventName); Assert.NotNull(ea.EventSource); Assert.Equal(EventKeywords.None, ea.Keywords); Assert.Equal(EventLevel.LogAlways, ea.Level); Assert.Equal((EventOpcode)0, ea.Opcode); Assert.NotNull(ea.Payload); Assert.NotNull(ea.PayloadNames); Assert.Equal(ea.PayloadNames.Count, ea.Payload.Count); Assert.Equal(Guid.Empty, ea.RelatedActivityId); Assert.Equal(EventTags.None, ea.Tags); Assert.Equal(EventTask.None, ea.Task); Assert.InRange(ea.TimeStamp, DateTime.MinValue, DateTime.MaxValue); Assert.Equal(0, ea.Version); } } [Fact] public void Test_Bad_WriteRelatedID_ParameterName() { #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else Guid oldGuid; Guid newGuid = Guid.NewGuid(); Guid newGuid2 = Guid.NewGuid(); EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); using (var bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter()) using (var listener = new EventListenerListener()) { var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(bes.Name, EventCommand.Enable); bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(1, events.Count); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." Assert.Contains("EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.", message); } #endif } } /// <summary> /// This EventSource has a common user error, and we want to make sure EventSource /// gives a reasonable experience in that case. /// </summary> internal class BadEventSource_MismatchedIds : EventSource { public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { } public void Event1(int arg) { WriteEvent(1, arg); } // Error Used the same event ID for this event. public void Event2(int arg) { WriteEvent(1, arg); } } /// <summary> /// A manifest based provider with a bad type byte[] /// </summary> internal class BadEventSource_Bad_Type_ByteArray : EventSource { public void Event1(byte[] myArray) { WriteEvent(1, myArray); } } public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource { public void E2() { this.Write("sampleevent", new { a = "a string" }); } [Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)] public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId) { WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId); } public class Keywords { public const EventKeywords Debug = (EventKeywords)0x0002; } } [EventData] public class UserClass { public int i; }; /// <summary> /// A manifest based provider with a bad type (only supported in self describing) /// </summary> internal class BadEventSource_Bad_Type_UserClass : EventSource { public void Event1(UserClass myClass) { WriteEvent(1, myClass); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipelines.Tests { public partial class PipelineReaderWriterFacts : IDisposable { public PipelineReaderWriterFacts() { _pool = new TestMemoryPool(); _pipe = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false)); } public void Dispose() { _pipe.Writer.Complete(); _pipe.Reader.Complete(); _pool?.Dispose(); } private readonly Pipe _pipe; private readonly TestMemoryPool _pool; [Fact] public async Task CanReadAndWrite() { byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.Equal(11, buffer.Length); Assert.True(buffer.IsSingleSegment); var array = new byte[11]; buffer.First.Span.CopyTo(array); Assert.Equal("Hello World", Encoding.ASCII.GetString(array)); _pipe.Reader.AdvanceTo(buffer.End); } [Fact] public async Task AdvanceResetsCommitHeadIndex() { _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(100); await _pipe.Writer.FlushAsync(); // Advance to the end ReadResult readResult = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(readResult.Buffer.End); // Try reading, it should block ValueTask<ReadResult> awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); _pipe.Writer.Write(new byte[1]); await _pipe.Writer.FlushAsync(); Assert.True(awaitable.IsCompleted); // Advance to the end should reset awaitable readResult = await awaitable; _pipe.Reader.AdvanceTo(readResult.Buffer.End); // Try reading, it should block awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); } [Fact] public async Task AdvanceShouldResetStateIfReadCanceled() { _pipe.Reader.CancelPendingRead(); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.AdvanceTo(buffer.End); Assert.False(result.IsCompleted); Assert.True(result.IsCanceled); Assert.True(buffer.IsEmpty); ValueTask<ReadResult> awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); } [Fact] public async Task AdvanceToInvalidCursorThrows() { await _pipe.Writer.WriteAsync(new byte[100]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.AdvanceTo(buffer.End); _pipe.Reader.CancelPendingRead(); result = await _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(buffer.End)); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public async Task AdvanceWithGetPositionCrossingIntoWriteHeadWorks() { // Create two blocks Memory<byte> memory = _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(memory.Length); memory = _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(memory.Length); await _pipe.Writer.FlushAsync(); // Read single block ReadResult readResult = await _pipe.Reader.ReadAsync(); // Allocate more memory memory = _pipe.Writer.GetMemory(1); // Create position that would cross into write head ReadOnlySequence<byte> buffer = readResult.Buffer; SequencePosition position = buffer.GetPosition(buffer.Length); // Return everything _pipe.Reader.AdvanceTo(position); // Advance writer _pipe.Writer.Advance(memory.Length); } [Fact] public async Task CompleteReaderAfterFlushWithoutAdvancingDoesNotThrow() { await _pipe.Writer.WriteAsync(new byte[10]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.Complete(); } [Fact] public async Task AdvanceAfterCompleteThrows() { await _pipe.Writer.WriteAsync(new byte[1]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.Complete(); var exception = Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(buffer.End)); Assert.Equal("Reading is not allowed after reader was completed.", exception.Message); } [Fact] public async Task HelloWorldAcrossTwoBlocks() { // block 1 -> block2 // [padding..hello] -> [ world ] PipeWriter writeBuffer = _pipe.Writer; var blockSize = _pipe.Writer.GetMemory().Length; byte[] paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray(); byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); writeBuffer.Write(paddingBytes); writeBuffer.Write(bytes); await writeBuffer.FlushAsync(); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.False(buffer.IsSingleSegment); ReadOnlySequence<byte> helloBuffer = buffer.Slice(blockSize - 5); Assert.False(helloBuffer.IsSingleSegment); var memory = new List<ReadOnlyMemory<byte>>(); foreach (ReadOnlyMemory<byte> m in helloBuffer) { memory.Add(m); } List<ReadOnlyMemory<byte>> spans = memory; _pipe.Reader.AdvanceTo(buffer.Start, buffer.Start); Assert.Equal(2, memory.Count); var helloBytes = new byte[spans[0].Length]; spans[0].Span.CopyTo(helloBytes); var worldBytes = new byte[spans[1].Length]; spans[1].Span.CopyTo(worldBytes); Assert.Equal("Hello", Encoding.ASCII.GetString(helloBytes)); Assert.Equal(" World", Encoding.ASCII.GetString(worldBytes)); } [MethodImpl(MethodImplOptions.NoInlining)] void ThrowTestException(Exception ex, Action<Exception> catchAction) { try { throw ex; } catch (Exception e) { catchAction(e); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public async Task ReadAsync_ThrowsIfWriterCompletedWithException() { ThrowTestException(new InvalidOperationException("Writer exception"), e => _pipe.Writer.Complete(e)); InvalidOperationException invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync()); Assert.Equal("Writer exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync()); Assert.Equal("Writer exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public async Task WriteAsync_ThrowsIfReaderCompletedWithException() { ThrowTestException(new InvalidOperationException("Reader exception"), e => _pipe.Reader.Complete(e)); InvalidOperationException invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Writer.WriteAsync(new byte[1])); Assert.Equal("Reader exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Writer.WriteAsync(new byte[1])); Assert.Equal("Reader exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); } [Fact] public async Task ReaderShouldNotGetUnflushedBytes() { // Write 10 and flush PipeWriter buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 10 }); await buffer.FlushAsync(); // Write 9 buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 9 }); // Write 8 buffer.Write(new byte[] { 0, 0, 0, 8 }); // Make sure we don't see it yet ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(4, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.ToArray()); // Don't move _pipe.Reader.AdvanceTo(reader.Start); // Now flush await buffer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; Assert.Equal(12, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 8 }, reader.Slice(8, 4).ToArray()); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [Fact] public async Task ReaderShouldNotGetUnflushedBytesWhenOverflowingSegments() { // Fill the block with stuff leaving 5 bytes at the end Memory<byte> buffer = _pipe.Writer.GetMemory(); int len = buffer.Length; // Fill the buffer with garbage // block 1 -> block2 // [padding..hello] -> [ world ] byte[] paddingBytes = Enumerable.Repeat((byte)'a', len - 5).ToArray(); _pipe.Writer.Write(paddingBytes); await _pipe.Writer.FlushAsync(); // Write 10 and flush _pipe.Writer.Write(new byte[] { 0, 0, 0, 10 }); // Write 9 _pipe.Writer.Write(new byte[] { 0, 0, 0, 9 }); // Write 8 _pipe.Writer.Write(new byte[] { 0, 0, 0, 8 }); // Make sure we don't see it yet ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(len - 5, reader.Length); // Don't move _pipe.Reader.AdvanceTo(reader.End); // Now flush await _pipe.Writer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; Assert.Equal(12, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 8 }, reader.Slice(8, 4).ToArray()); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [Fact] public async Task ReaderShouldNotGetUnflushedBytesWithAppend() { // Write 10 and flush PipeWriter buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 10 }); await buffer.FlushAsync(); // Write Hello to another pipeline and get the buffer byte[] bytes = Encoding.ASCII.GetBytes("Hello"); var c2 = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline)); await c2.Writer.WriteAsync(bytes); ReadResult result = await c2.Reader.ReadAsync(); ReadOnlySequence<byte> c2Buffer = result.Buffer; Assert.Equal(bytes.Length, c2Buffer.Length); // Write 9 to the buffer buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 9 }); // Append the data from the other pipeline foreach (ReadOnlyMemory<byte> memory in c2Buffer) { buffer.Write(memory.Span); } // Mark it as consumed c2.Reader.AdvanceTo(c2Buffer.End); // Now read and make sure we only see the comitted data result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(4, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); // Consume nothing _pipe.Reader.AdvanceTo(reader.Start); // Flush the second set of writes await buffer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; // int, int, "Hello" Assert.Equal(13, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal("Hello", Encoding.ASCII.GetString(reader.Slice(8).ToArray())); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(true)] [InlineData(false)] public async Task ReadAsyncOnCompletedCapturesTheExecutionContext(bool useSynchronizationContext) { var pipe = new Pipe(new PipeOptions(useSynchronizationContext: useSynchronizationContext)); SynchronizationContext previous = SynchronizationContext.Current; var sc = new CustomSynchronizationContext(); if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(sc); } try { AsyncLocal<int> val = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); val.Value = 10; pipe.Reader.ReadAsync().GetAwaiter().OnCompleted(() => { tcs.TrySetResult(val.Value); }); val.Value = 20; pipe.Writer.WriteEmpty(100); // Don't run any code on our fake sync context await pipe.Writer.FlushAsync().ConfigureAwait(false); if (useSynchronizationContext) { Assert.Equal(1, sc.Callbacks.Count); sc.Callbacks[0].Item1(sc.Callbacks[0].Item2); } int value = await tcs.Task.ConfigureAwait(false); Assert.Equal(10, value); } finally { if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(previous); } pipe.Reader.Complete(); pipe.Writer.Complete(); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(true)] [InlineData(false)] public async Task FlushAsyncOnCompletedCapturesTheExecutionContextAndSyncContext(bool useSynchronizationContext) { var pipe = new Pipe(new PipeOptions(useSynchronizationContext: useSynchronizationContext, pauseWriterThreshold: 20, resumeWriterThreshold: 10)); SynchronizationContext previous = SynchronizationContext.Current; var sc = new CustomSynchronizationContext(); if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(sc); } try { AsyncLocal<int> val = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); val.Value = 10; pipe.Writer.WriteEmpty(20); pipe.Writer.FlushAsync().GetAwaiter().OnCompleted(() => { tcs.TrySetResult(val.Value); }); val.Value = 20; // Don't run any code on our fake sync context ReadResult result = await pipe.Reader.ReadAsync().ConfigureAwait(false); pipe.Reader.AdvanceTo(result.Buffer.End); if (useSynchronizationContext) { Assert.Equal(1, sc.Callbacks.Count); sc.Callbacks[0].Item1(sc.Callbacks[0].Item2); } int value = await tcs.Task.ConfigureAwait(false); Assert.Equal(10, value); } finally { if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(previous); } pipe.Reader.Complete(); pipe.Writer.Complete(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task ReadingCanBeCanceled() { var cts = new CancellationTokenSource(); cts.Token.Register(() => { _pipe.Writer.Complete(new OperationCanceledException(cts.Token)); }); Task ignore = Task.Run( async () => { await Task.Delay(1000); cts.Cancel(); }); await Assert.ThrowsAsync<OperationCanceledException>( async () => { ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; }); } [Fact] public async Task SyncReadThenAsyncRead() { PipeWriter buffer = _pipe.Writer; buffer.Write(Encoding.ASCII.GetBytes("Hello World")); await buffer.FlushAsync(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(gotData); Assert.Equal("Hello World", Encoding.ASCII.GetString(result.Buffer.ToArray())); _pipe.Reader.AdvanceTo(result.Buffer.GetPosition(6)); result = await _pipe.Reader.ReadAsync(); Assert.Equal("World", Encoding.ASCII.GetString(result.Buffer.ToArray())); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void ThrowsOnAllocAfterCompleteWriter() { _pipe.Writer.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Writer.GetMemory()); } [Fact] public void ThrowsOnReadAfterCompleteReader() { _pipe.Reader.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.ReadAsync()); } [Fact] public void TryReadAfterCancelPendingReadReturnsTrue() { _pipe.Reader.CancelPendingRead(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(result.IsCanceled); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void TryReadAfterCloseWriterWithExceptionThrows() { _pipe.Writer.Complete(new Exception("wow")); var ex = Assert.Throws<Exception>(() => _pipe.Reader.TryRead(out ReadResult result)); Assert.Equal("wow", ex.Message); } [Fact] public void TryReadAfterReaderCompleteThrows() { _pipe.Reader.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.TryRead(out ReadResult result)); } [Fact] public void TryReadAfterWriterCompleteReturnsTrue() { _pipe.Writer.Complete(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(result.IsCompleted); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void WhenTryReadReturnsFalseDontNeedToCallAdvance() { bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.False(gotData); _pipe.Reader.AdvanceTo(default); } [Fact] public async Task WritingDataMakesDataReadableViaPipeline() { byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.Equal(11, buffer.Length); Assert.True(buffer.IsSingleSegment); var array = new byte[11]; buffer.First.Span.CopyTo(array); Assert.Equal("Hello World", Encoding.ASCII.GetString(array)); _pipe.Reader.AdvanceTo(buffer.Start, buffer.Start); } [Fact] public async Task DoubleAsyncReadThrows() { ValueTask<ReadResult> readTask1 = _pipe.Reader.ReadAsync(); ValueTask<ReadResult> readTask2 = _pipe.Reader.ReadAsync(); var task1 = Assert.ThrowsAsync<InvalidOperationException>(async () => await readTask1); var task2 = Assert.ThrowsAsync<InvalidOperationException>(async () => await readTask2); var exception1 = await task1; var exception2 = await task2; Assert.Equal("Concurrent reads or writes are not supported.", exception1.Message); Assert.Equal("Concurrent reads or writes are not supported.", exception2.Message); } [Fact] public void GetResultBeforeCompletedThrows() { ValueTask<ReadResult> awaiter = _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => awaiter.GetAwaiter().GetResult()); } [Fact] public async Task CompleteAfterAdvanceCommits() { _pipe.Writer.WriteEmpty(4); _pipe.Writer.Complete(); var result = await _pipe.Reader.ReadAsync(); Assert.Equal(4, result.Buffer.Length); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public async Task AdvanceWithoutReadThrows() { await _pipe.Writer.WriteAsync(new byte[3]); ReadResult readResult = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(readResult.Buffer.Start); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(readResult.Buffer.End)); Assert.Equal("No reading operation to complete.", exception.Message); } [Fact] public async Task TryReadAfterReadAsyncThrows() { await _pipe.Writer.WriteAsync(new byte[3]); ReadResult readResult = await _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.TryRead(out _)); _pipe.Reader.AdvanceTo(readResult.Buffer.Start); } [Fact] public void GetMemoryZeroReturnsNonEmpty() { Assert.True(_pipe.Writer.GetMemory(0).Length > 0); } [Fact] public async Task ReadAsyncWithDataReadyReturnsTaskWithValue() { _pipe.Writer.WriteEmpty(10); await _pipe.Writer.FlushAsync(); var task = _pipe.Reader.ReadAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void CancelledReadAsyncReturnsTaskWithValue() { _pipe.Reader.CancelPendingRead(); var task = _pipe.Reader.ReadAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void FlushAsyncWithoutBackpressureReturnsTaskWithValue() { _pipe.Writer.WriteEmpty(10); var task = _pipe.Writer.FlushAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void CancelledFlushAsyncReturnsTaskWithValue() { _pipe.Writer.CancelPendingFlush(); var task = _pipe.Writer.FlushAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void EmptyFlushAsyncDoesntWakeUpReader() { ValueTask<ReadResult> task = _pipe.Reader.ReadAsync(); _pipe.Writer.FlushAsync(); Assert.False(task.IsCompleted); } [Fact] public async Task EmptyFlushAsyncDoesntWakeUpReaderAfterAdvance() { await _pipe.Writer.WriteAsync(new byte[10]); ReadResult result = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(result.Buffer.Start, result.Buffer.End); ValueTask<ReadResult> task = _pipe.Reader.ReadAsync(); await _pipe.Writer.FlushAsync(); Assert.False(task.IsCompleted); } [Fact] public async Task ReadAsyncReturnsDataAfterCanceledRead() { var pipe = new Pipe(); ValueTask<ReadResult> readTask = pipe.Reader.ReadAsync(); pipe.Reader.CancelPendingRead(); ReadResult readResult = await readTask; Assert.True(readResult.IsCanceled); readTask = pipe.Reader.ReadAsync(); await pipe.Writer.WriteAsync(new byte[] { 1, 2, 3 }); readResult = await readTask; Assert.False(readResult.IsCanceled); Assert.False(readResult.IsCompleted); Assert.Equal(3, readResult.Buffer.Length); pipe.Reader.AdvanceTo(readResult.Buffer.End); } private bool IsTaskWithResult<T>(ValueTask<T> task) { return task == new ValueTask<T>(task.Result); } private sealed class CustomSynchronizationContext : SynchronizationContext { public List<Tuple<SendOrPostCallback, object>> Callbacks = new List<Tuple<SendOrPostCallback, object>>(); public override void Post(SendOrPostCallback d, object state) { Callbacks.Add(Tuple.Create(d, state)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipelines.Tests { public partial class PipelineReaderWriterFacts : IDisposable { public PipelineReaderWriterFacts() { _pool = new TestMemoryPool(); _pipe = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false)); } public void Dispose() { _pipe.Writer.Complete(); _pipe.Reader.Complete(); _pool?.Dispose(); } private readonly Pipe _pipe; private readonly TestMemoryPool _pool; [Fact] public async Task CanReadAndWrite() { byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.Equal(11, buffer.Length); Assert.True(buffer.IsSingleSegment); var array = new byte[11]; buffer.First.Span.CopyTo(array); Assert.Equal("Hello World", Encoding.ASCII.GetString(array)); _pipe.Reader.AdvanceTo(buffer.End); } [Fact] public async Task AdvanceResetsCommitHeadIndex() { _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(100); await _pipe.Writer.FlushAsync(); // Advance to the end ReadResult readResult = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(readResult.Buffer.End); // Try reading, it should block ValueTask<ReadResult> awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); _pipe.Writer.Write(new byte[1]); await _pipe.Writer.FlushAsync(); Assert.True(awaitable.IsCompleted); // Advance to the end should reset awaitable readResult = await awaitable; _pipe.Reader.AdvanceTo(readResult.Buffer.End); // Try reading, it should block awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); } [Fact] public async Task AdvanceShouldResetStateIfReadCanceled() { _pipe.Reader.CancelPendingRead(); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.AdvanceTo(buffer.End); Assert.False(result.IsCompleted); Assert.True(result.IsCanceled); Assert.True(buffer.IsEmpty); ValueTask<ReadResult> awaitable = _pipe.Reader.ReadAsync(); Assert.False(awaitable.IsCompleted); } [Fact] public async Task AdvanceToInvalidCursorThrows() { await _pipe.Writer.WriteAsync(new byte[100]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.AdvanceTo(buffer.End); _pipe.Reader.CancelPendingRead(); result = await _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(buffer.End)); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public async Task AdvanceWithGetPositionCrossingIntoWriteHeadWorks() { // Create two blocks Memory<byte> memory = _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(memory.Length); memory = _pipe.Writer.GetMemory(1); _pipe.Writer.Advance(memory.Length); await _pipe.Writer.FlushAsync(); // Read single block ReadResult readResult = await _pipe.Reader.ReadAsync(); // Allocate more memory memory = _pipe.Writer.GetMemory(1); // Create position that would cross into write head ReadOnlySequence<byte> buffer = readResult.Buffer; SequencePosition position = buffer.GetPosition(buffer.Length); // Return everything _pipe.Reader.AdvanceTo(position); // Advance writer _pipe.Writer.Advance(memory.Length); } [Fact] public async Task CompleteReaderAfterFlushWithoutAdvancingDoesNotThrow() { await _pipe.Writer.WriteAsync(new byte[10]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.Complete(); } [Fact] public async Task AdvanceAfterCompleteThrows() { await _pipe.Writer.WriteAsync(new byte[1]); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; _pipe.Reader.Complete(); var exception = Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(buffer.End)); Assert.Equal("Reading is not allowed after reader was completed.", exception.Message); } [Fact] public async Task HelloWorldAcrossTwoBlocks() { // block 1 -> block2 // [padding..hello] -> [ world ] PipeWriter writeBuffer = _pipe.Writer; var blockSize = _pipe.Writer.GetMemory().Length; byte[] paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray(); byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); writeBuffer.Write(paddingBytes); writeBuffer.Write(bytes); await writeBuffer.FlushAsync(); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.False(buffer.IsSingleSegment); ReadOnlySequence<byte> helloBuffer = buffer.Slice(blockSize - 5); Assert.False(helloBuffer.IsSingleSegment); var memory = new List<ReadOnlyMemory<byte>>(); foreach (ReadOnlyMemory<byte> m in helloBuffer) { memory.Add(m); } List<ReadOnlyMemory<byte>> spans = memory; _pipe.Reader.AdvanceTo(buffer.Start, buffer.Start); Assert.Equal(2, memory.Count); var helloBytes = new byte[spans[0].Length]; spans[0].Span.CopyTo(helloBytes); var worldBytes = new byte[spans[1].Length]; spans[1].Span.CopyTo(worldBytes); Assert.Equal("Hello", Encoding.ASCII.GetString(helloBytes)); Assert.Equal(" World", Encoding.ASCII.GetString(worldBytes)); } [MethodImpl(MethodImplOptions.NoInlining)] void ThrowTestException(Exception ex, Action<Exception> catchAction) { try { throw ex; } catch (Exception e) { catchAction(e); } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public async Task ReadAsync_ThrowsIfWriterCompletedWithException() { ThrowTestException(new InvalidOperationException("Writer exception"), e => _pipe.Writer.Complete(e)); InvalidOperationException invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync()); Assert.Equal("Writer exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync()); Assert.Equal("Writer exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public async Task WriteAsync_ThrowsIfReaderCompletedWithException() { ThrowTestException(new InvalidOperationException("Reader exception"), e => _pipe.Reader.Complete(e)); InvalidOperationException invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Writer.WriteAsync(new byte[1])); Assert.Equal("Reader exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Writer.WriteAsync(new byte[1])); Assert.Equal("Reader exception", invalidOperationException.Message); Assert.Contains(nameof(ThrowTestException), invalidOperationException.StackTrace); } [Fact] public async Task ReaderShouldNotGetUnflushedBytes() { // Write 10 and flush PipeWriter buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 10 }); await buffer.FlushAsync(); // Write 9 buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 9 }); // Write 8 buffer.Write(new byte[] { 0, 0, 0, 8 }); // Make sure we don't see it yet ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(4, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.ToArray()); // Don't move _pipe.Reader.AdvanceTo(reader.Start); // Now flush await buffer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; Assert.Equal(12, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 8 }, reader.Slice(8, 4).ToArray()); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [Fact] public async Task ReaderShouldNotGetUnflushedBytesWhenOverflowingSegments() { // Fill the block with stuff leaving 5 bytes at the end Memory<byte> buffer = _pipe.Writer.GetMemory(); int len = buffer.Length; // Fill the buffer with garbage // block 1 -> block2 // [padding..hello] -> [ world ] byte[] paddingBytes = Enumerable.Repeat((byte)'a', len - 5).ToArray(); _pipe.Writer.Write(paddingBytes); await _pipe.Writer.FlushAsync(); // Write 10 and flush _pipe.Writer.Write(new byte[] { 0, 0, 0, 10 }); // Write 9 _pipe.Writer.Write(new byte[] { 0, 0, 0, 9 }); // Write 8 _pipe.Writer.Write(new byte[] { 0, 0, 0, 8 }); // Make sure we don't see it yet ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(len - 5, reader.Length); // Don't move _pipe.Reader.AdvanceTo(reader.End); // Now flush await _pipe.Writer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; Assert.Equal(12, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 8 }, reader.Slice(8, 4).ToArray()); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [Fact] public async Task ReaderShouldNotGetUnflushedBytesWithAppend() { // Write 10 and flush PipeWriter buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 10 }); await buffer.FlushAsync(); // Write Hello to another pipeline and get the buffer byte[] bytes = Encoding.ASCII.GetBytes("Hello"); var c2 = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline)); await c2.Writer.WriteAsync(bytes); ReadResult result = await c2.Reader.ReadAsync(); ReadOnlySequence<byte> c2Buffer = result.Buffer; Assert.Equal(bytes.Length, c2Buffer.Length); // Write 9 to the buffer buffer = _pipe.Writer; buffer.Write(new byte[] { 0, 0, 0, 9 }); // Append the data from the other pipeline foreach (ReadOnlyMemory<byte> memory in c2Buffer) { buffer.Write(memory.Span); } // Mark it as consumed c2.Reader.AdvanceTo(c2Buffer.End); // Now read and make sure we only see the comitted data result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> reader = result.Buffer; Assert.Equal(4, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); // Consume nothing _pipe.Reader.AdvanceTo(reader.Start); // Flush the second set of writes await buffer.FlushAsync(); reader = (await _pipe.Reader.ReadAsync()).Buffer; // int, int, "Hello" Assert.Equal(13, reader.Length); Assert.Equal(new byte[] { 0, 0, 0, 10 }, reader.Slice(0, 4).ToArray()); Assert.Equal(new byte[] { 0, 0, 0, 9 }, reader.Slice(4, 4).ToArray()); Assert.Equal("Hello", Encoding.ASCII.GetString(reader.Slice(8).ToArray())); _pipe.Reader.AdvanceTo(reader.Start, reader.Start); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(true)] [InlineData(false)] public async Task ReadAsyncOnCompletedCapturesTheExecutionContext(bool useSynchronizationContext) { var pipe = new Pipe(new PipeOptions(useSynchronizationContext: useSynchronizationContext)); SynchronizationContext previous = SynchronizationContext.Current; var sc = new CustomSynchronizationContext(); if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(sc); } try { AsyncLocal<int> val = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); val.Value = 10; pipe.Reader.ReadAsync().GetAwaiter().OnCompleted(() => { tcs.TrySetResult(val.Value); }); val.Value = 20; pipe.Writer.WriteEmpty(100); // Don't run any code on our fake sync context await pipe.Writer.FlushAsync().ConfigureAwait(false); if (useSynchronizationContext) { Assert.Equal(1, sc.Callbacks.Count); sc.Callbacks[0].Item1(sc.Callbacks[0].Item2); } int value = await tcs.Task.ConfigureAwait(false); Assert.Equal(10, value); } finally { if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(previous); } pipe.Reader.Complete(); pipe.Writer.Complete(); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(true)] [InlineData(false)] public async Task FlushAsyncOnCompletedCapturesTheExecutionContextAndSyncContext(bool useSynchronizationContext) { var pipe = new Pipe(new PipeOptions(useSynchronizationContext: useSynchronizationContext, pauseWriterThreshold: 20, resumeWriterThreshold: 10)); SynchronizationContext previous = SynchronizationContext.Current; var sc = new CustomSynchronizationContext(); if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(sc); } try { AsyncLocal<int> val = new AsyncLocal<int>(); var tcs = new TaskCompletionSource<int>(); val.Value = 10; pipe.Writer.WriteEmpty(20); pipe.Writer.FlushAsync().GetAwaiter().OnCompleted(() => { tcs.TrySetResult(val.Value); }); val.Value = 20; // Don't run any code on our fake sync context ReadResult result = await pipe.Reader.ReadAsync().ConfigureAwait(false); pipe.Reader.AdvanceTo(result.Buffer.End); if (useSynchronizationContext) { Assert.Equal(1, sc.Callbacks.Count); sc.Callbacks[0].Item1(sc.Callbacks[0].Item2); } int value = await tcs.Task.ConfigureAwait(false); Assert.Equal(10, value); } finally { if (useSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(previous); } pipe.Reader.Complete(); pipe.Writer.Complete(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task ReadingCanBeCanceled() { var cts = new CancellationTokenSource(); cts.Token.Register(() => { _pipe.Writer.Complete(new OperationCanceledException(cts.Token)); }); Task ignore = Task.Run( async () => { await Task.Delay(1000); cts.Cancel(); }); await Assert.ThrowsAsync<OperationCanceledException>( async () => { ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; }); } [Fact] public async Task SyncReadThenAsyncRead() { PipeWriter buffer = _pipe.Writer; buffer.Write(Encoding.ASCII.GetBytes("Hello World")); await buffer.FlushAsync(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(gotData); Assert.Equal("Hello World", Encoding.ASCII.GetString(result.Buffer.ToArray())); _pipe.Reader.AdvanceTo(result.Buffer.GetPosition(6)); result = await _pipe.Reader.ReadAsync(); Assert.Equal("World", Encoding.ASCII.GetString(result.Buffer.ToArray())); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void ThrowsOnAllocAfterCompleteWriter() { _pipe.Writer.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Writer.GetMemory()); } [Fact] public void ThrowsOnReadAfterCompleteReader() { _pipe.Reader.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.ReadAsync()); } [Fact] public void TryReadAfterCancelPendingReadReturnsTrue() { _pipe.Reader.CancelPendingRead(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(result.IsCanceled); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void TryReadAfterCloseWriterWithExceptionThrows() { _pipe.Writer.Complete(new Exception("wow")); var ex = Assert.Throws<Exception>(() => _pipe.Reader.TryRead(out ReadResult result)); Assert.Equal("wow", ex.Message); } [Fact] public void TryReadAfterReaderCompleteThrows() { _pipe.Reader.Complete(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.TryRead(out ReadResult result)); } [Fact] public void TryReadAfterWriterCompleteReturnsTrue() { _pipe.Writer.Complete(); bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.True(result.IsCompleted); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public void WhenTryReadReturnsFalseDontNeedToCallAdvance() { bool gotData = _pipe.Reader.TryRead(out ReadResult result); Assert.False(gotData); _pipe.Reader.AdvanceTo(default); } [Fact] public async Task WritingDataMakesDataReadableViaPipeline() { byte[] bytes = Encoding.ASCII.GetBytes("Hello World"); await _pipe.Writer.WriteAsync(bytes); ReadResult result = await _pipe.Reader.ReadAsync(); ReadOnlySequence<byte> buffer = result.Buffer; Assert.Equal(11, buffer.Length); Assert.True(buffer.IsSingleSegment); var array = new byte[11]; buffer.First.Span.CopyTo(array); Assert.Equal("Hello World", Encoding.ASCII.GetString(array)); _pipe.Reader.AdvanceTo(buffer.Start, buffer.Start); } [Fact] public async Task DoubleAsyncReadThrows() { ValueTask<ReadResult> readTask1 = _pipe.Reader.ReadAsync(); ValueTask<ReadResult> readTask2 = _pipe.Reader.ReadAsync(); var task1 = Assert.ThrowsAsync<InvalidOperationException>(async () => await readTask1); var task2 = Assert.ThrowsAsync<InvalidOperationException>(async () => await readTask2); var exception1 = await task1; var exception2 = await task2; Assert.Equal("Concurrent reads or writes are not supported.", exception1.Message); Assert.Equal("Concurrent reads or writes are not supported.", exception2.Message); } [Fact] public void GetResultBeforeCompletedThrows() { ValueTask<ReadResult> awaiter = _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => awaiter.GetAwaiter().GetResult()); } [Fact] public async Task CompleteAfterAdvanceCommits() { _pipe.Writer.WriteEmpty(4); _pipe.Writer.Complete(); var result = await _pipe.Reader.ReadAsync(); Assert.Equal(4, result.Buffer.Length); _pipe.Reader.AdvanceTo(result.Buffer.End); } [Fact] public async Task AdvanceWithoutReadThrows() { await _pipe.Writer.WriteAsync(new byte[3]); ReadResult readResult = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(readResult.Buffer.Start); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => _pipe.Reader.AdvanceTo(readResult.Buffer.End)); Assert.Equal("No reading operation to complete.", exception.Message); } [Fact] public async Task TryReadAfterReadAsyncThrows() { await _pipe.Writer.WriteAsync(new byte[3]); ReadResult readResult = await _pipe.Reader.ReadAsync(); Assert.Throws<InvalidOperationException>(() => _pipe.Reader.TryRead(out _)); _pipe.Reader.AdvanceTo(readResult.Buffer.Start); } [Fact] public void GetMemoryZeroReturnsNonEmpty() { Assert.True(_pipe.Writer.GetMemory(0).Length > 0); } [Fact] public async Task ReadAsyncWithDataReadyReturnsTaskWithValue() { _pipe.Writer.WriteEmpty(10); await _pipe.Writer.FlushAsync(); var task = _pipe.Reader.ReadAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void CancelledReadAsyncReturnsTaskWithValue() { _pipe.Reader.CancelPendingRead(); var task = _pipe.Reader.ReadAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void FlushAsyncWithoutBackpressureReturnsTaskWithValue() { _pipe.Writer.WriteEmpty(10); var task = _pipe.Writer.FlushAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void CancelledFlushAsyncReturnsTaskWithValue() { _pipe.Writer.CancelPendingFlush(); var task = _pipe.Writer.FlushAsync(); Assert.True(IsTaskWithResult(task)); } [Fact] public void EmptyFlushAsyncDoesntWakeUpReader() { ValueTask<ReadResult> task = _pipe.Reader.ReadAsync(); _pipe.Writer.FlushAsync(); Assert.False(task.IsCompleted); } [Fact] public async Task EmptyFlushAsyncDoesntWakeUpReaderAfterAdvance() { await _pipe.Writer.WriteAsync(new byte[10]); ReadResult result = await _pipe.Reader.ReadAsync(); _pipe.Reader.AdvanceTo(result.Buffer.Start, result.Buffer.End); ValueTask<ReadResult> task = _pipe.Reader.ReadAsync(); await _pipe.Writer.FlushAsync(); Assert.False(task.IsCompleted); } [Fact] public async Task ReadAsyncReturnsDataAfterCanceledRead() { var pipe = new Pipe(); ValueTask<ReadResult> readTask = pipe.Reader.ReadAsync(); pipe.Reader.CancelPendingRead(); ReadResult readResult = await readTask; Assert.True(readResult.IsCanceled); readTask = pipe.Reader.ReadAsync(); await pipe.Writer.WriteAsync(new byte[] { 1, 2, 3 }); readResult = await readTask; Assert.False(readResult.IsCanceled); Assert.False(readResult.IsCompleted); Assert.Equal(3, readResult.Buffer.Length); pipe.Reader.AdvanceTo(readResult.Buffer.End); } private bool IsTaskWithResult<T>(ValueTask<T> task) { return task == new ValueTask<T>(task.Result); } private sealed class CustomSynchronizationContext : SynchronizationContext { public List<Tuple<SendOrPostCallback, object>> Callbacks = new List<Tuple<SendOrPostCallback, object>>(); public override void Post(SendOrPostCallback d, object state) { Callbacks.Add(Tuple.Create(d, state)); } } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Linq.Expressions/tests/CompilerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using Xunit; namespace System.Linq.Expressions.Tests { public static class CompilerTests { [Theory] [ClassData(typeof(CompilationTypes))] [OuterLoop("Takes over a minute to complete")] public static void CompileDeepTree_NoStackOverflow(bool useInterpreter) { var e = (Expression)Expression.Constant(0); int n = 10000; for (var i = 0; i < n; i++) e = Expression.Add(e, Expression.Constant(1)); Func<int> f = Expression.Lambda<Func<int>>(e).Compile(useInterpreter); Assert.Equal(n, f()); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_NonNullableValueTypes() { VerifyEmitConstantsToIL((bool)true); VerifyEmitConstantsToIL((char)'a'); VerifyEmitConstantsToIL((sbyte)42); VerifyEmitConstantsToIL((byte)42); VerifyEmitConstantsToIL((short)42); VerifyEmitConstantsToIL((ushort)42); VerifyEmitConstantsToIL((int)42); VerifyEmitConstantsToIL((uint)42); VerifyEmitConstantsToIL((long)42); VerifyEmitConstantsToIL((ulong)42); VerifyEmitConstantsToIL((float)3.14); VerifyEmitConstantsToIL((double)3.14); VerifyEmitConstantsToIL((decimal)49.95m); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_NullableValueTypes() { VerifyEmitConstantsToIL((bool?)null); VerifyEmitConstantsToIL((bool?)true); VerifyEmitConstantsToIL((char?)null); VerifyEmitConstantsToIL((char?)'a'); VerifyEmitConstantsToIL((sbyte?)null); VerifyEmitConstantsToIL((sbyte?)42); VerifyEmitConstantsToIL((byte?)null); VerifyEmitConstantsToIL((byte?)42); VerifyEmitConstantsToIL((short?)null); VerifyEmitConstantsToIL((short?)42); VerifyEmitConstantsToIL((ushort?)null); VerifyEmitConstantsToIL((ushort?)42); VerifyEmitConstantsToIL((int?)null); VerifyEmitConstantsToIL((int?)42); VerifyEmitConstantsToIL((uint?)null); VerifyEmitConstantsToIL((uint?)42); VerifyEmitConstantsToIL((long?)null); VerifyEmitConstantsToIL((long?)42); VerifyEmitConstantsToIL((ulong?)null); VerifyEmitConstantsToIL((ulong?)42); VerifyEmitConstantsToIL((float?)null); VerifyEmitConstantsToIL((float?)3.14); VerifyEmitConstantsToIL((double?)null); VerifyEmitConstantsToIL((double?)3.14); VerifyEmitConstantsToIL((decimal?)null); VerifyEmitConstantsToIL((decimal?)49.95m); VerifyEmitConstantsToIL((DateTime?)null); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_ReferenceTypes() { VerifyEmitConstantsToIL((string)null); VerifyEmitConstantsToIL((string)"bar"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_Enums() { VerifyEmitConstantsToIL(ConstantsEnum.A); VerifyEmitConstantsToIL((ConstantsEnum?)null); VerifyEmitConstantsToIL((ConstantsEnum?)ConstantsEnum.A); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_ShareReferences() { var o = new object(); VerifyEmitConstantsToIL(Expression.Equal(Expression.Constant(o), Expression.Constant(o)), 1, true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_LiftedToClosure() { VerifyEmitConstantsToIL(DateTime.Now, 1); VerifyEmitConstantsToIL((DateTime?)DateTime.Now, 1); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void VariableBinder_CatchBlock_Filter1() { // See https://github.com/dotnet/runtime/issues/18676 for reported issue Verify_VariableBinder_CatchBlock_Filter( Expression.Catch( Expression.Parameter(typeof(Exception), "ex"), Expression.Empty(), Expression.Parameter(typeof(bool), "???") ) ); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void VariableBinder_CatchBlock_Filter2() { // See https://github.com/dotnet/runtime/issues/18676 for reported issue Verify_VariableBinder_CatchBlock_Filter( Expression.Catch( typeof(Exception), Expression.Empty(), Expression.Parameter(typeof(bool), "???") ) ); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Simple() { Expression<Func<int>> f = () => Math.Abs(42); f.VerifyIL( @".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: call int32 class [System.Private.CoreLib]System.Math::Abs(int32) IL_0007: ret }"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Exceptions() { ParameterExpression x = Expression.Parameter(typeof(int), "x"); Expression<Func<int, int>> f = Expression.Lambda<Func<int, int>>( Expression.TryCatchFinally( Expression.Call( typeof(Math).GetMethod(nameof(Math.Abs), new[] { typeof(int) }), Expression.Divide( Expression.Constant(42), x ) ), Expression.Empty(), Expression.Catch( typeof(DivideByZeroException), Expression.Constant(-1) ) ), x ); f.VerifyIL( @".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 4 .locals init ( [0] int32 ) .try { .try { IL_0000: ldc.i4.s 42 IL_0002: ldarg.1 IL_0003: div IL_0004: call int32 class [System.Private.CoreLib]System.Math::Abs(int32) IL_0009: stloc.0 IL_000a: leave IL_0017 } catch (class [System.Private.CoreLib]System.DivideByZeroException) { IL_000f: pop IL_0010: ldc.i4.m1 IL_0011: stloc.0 IL_0012: leave IL_0017 } IL_0017: leave IL_001d } finally { IL_001c: endfinally } IL_001d: ldloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure1() { Expression<Func<Func<int>>> f = () => () => 42; f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0006: ldc.i4.0 IL_0007: ldelem.ref IL_0008: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_000d: ldtoken class [System.Private.CoreLib]System.Func`1<int32> IL_0012: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0017: ldnull IL_0018: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_001d: castclass class [System.Private.CoreLib]System.Func`1<int32> IL_0022: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }", appendInnerLambdas: true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure2() { Expression<Func<int, Func<int>>> f = x => () => x; f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 8 .locals init ( [0] object[] ) IL_0000: ldc.i4.1 IL_0001: newarr object IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.1 IL_0009: newobj instance void class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32) IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_001d: ldtoken class [System.Private.CoreLib]System.Func`1<int32> IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0027: ldnull IL_0028: ldloc.0 IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[]) IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_0033: castclass class [System.Private.CoreLib]System.Func`1<int32> IL_0038: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 2 .locals init ( [0] object[] ) IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldelem.ref IL_000a: castclass class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32> IL_000f: ldfld class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::Value IL_0014: ret }", appendInnerLambdas: true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure3() { // Using an unchecked addition to ensure that an add instruction is emitted (and not add.ovf) Expression<Func<int, Func<int, int>>> f = x => y => unchecked(x + y); f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`2<int32,int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 8 .locals init ( [0] object[] ) IL_0000: ldc.i4.1 IL_0001: newarr object IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.1 IL_0009: newobj instance void class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32) IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_001d: ldtoken class [System.Private.CoreLib]System.Func`2<int32,int32> IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0027: ldnull IL_0028: ldloc.0 IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[]) IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_0033: castclass class [System.Private.CoreLib]System.Func`2<int32,int32> IL_0038: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 2 .locals init ( [0] object[] ) IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldelem.ref IL_000a: castclass class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32> IL_000f: ldfld class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::Value IL_0014: ldarg.1 IL_0015: add IL_0016: ret }", appendInnerLambdas: true); } internal static void VerifyIL(this LambdaExpression expression, string expected, bool appendInnerLambdas = false) { string actual = expression.GetIL(appendInnerLambdas); string nExpected = Normalize(expected); string nActual = Normalize(actual); Assert.Equal(nExpected, nActual); } private static string Normalize(string s) { Collections.Generic.IEnumerable<string> lines = s .Replace("\r\n", "\n") .Split(new[] { '\n' }) .Select(line => line.Trim()) .Where(line => line != "" && !line.StartsWith("//")); string beforeLambdaUniquifierRemoval = string.Join("\n", lines); return Regex.Replace(beforeLambdaUniquifierRemoval, "lambda_method[0-9]*", "lambda_method"); } private static void VerifyEmitConstantsToIL<T>(T value) { VerifyEmitConstantsToIL<T>(value, 0); } private static void VerifyEmitConstantsToIL<T>(T value, int expectedCount) { VerifyEmitConstantsToIL(Expression.Constant(value, typeof(T)), expectedCount, value); } private static void VerifyEmitConstantsToIL(Expression e, int expectedCount, object expectedValue) { Delegate f = Expression.Lambda(e).Compile(); var c = f.Target as Closure; Assert.NotNull(c); Assert.Equal(expectedCount, c.Constants.Length); object o = f.DynamicInvoke(); Assert.Equal(expectedValue, o); } private static void Verify_VariableBinder_CatchBlock_Filter(CatchBlock @catch) { Expression<Action> e = Expression.Lambda<Action>( Expression.TryCatch( Expression.Empty(), @catch ) ); Assert.Throws<InvalidOperationException>(() => e.Compile()); } } public enum ConstantsEnum { A } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Linq.Expressions.Tests { public static class CompilerTests { [Theory] [ClassData(typeof(CompilationTypes))] [OuterLoop("Takes over a minute to complete")] public static void CompileDeepTree_NoStackOverflow(bool useInterpreter) { var e = (Expression)Expression.Constant(0); int n = 10000; for (var i = 0; i < n; i++) e = Expression.Add(e, Expression.Constant(1)); Func<int> f = Expression.Lambda<Func<int>>(e).Compile(useInterpreter); Assert.Equal(n, f()); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_NonNullableValueTypes() { VerifyEmitConstantsToIL((bool)true); VerifyEmitConstantsToIL((char)'a'); VerifyEmitConstantsToIL((sbyte)42); VerifyEmitConstantsToIL((byte)42); VerifyEmitConstantsToIL((short)42); VerifyEmitConstantsToIL((ushort)42); VerifyEmitConstantsToIL((int)42); VerifyEmitConstantsToIL((uint)42); VerifyEmitConstantsToIL((long)42); VerifyEmitConstantsToIL((ulong)42); VerifyEmitConstantsToIL((float)3.14); VerifyEmitConstantsToIL((double)3.14); VerifyEmitConstantsToIL((decimal)49.95m); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_NullableValueTypes() { VerifyEmitConstantsToIL((bool?)null); VerifyEmitConstantsToIL((bool?)true); VerifyEmitConstantsToIL((char?)null); VerifyEmitConstantsToIL((char?)'a'); VerifyEmitConstantsToIL((sbyte?)null); VerifyEmitConstantsToIL((sbyte?)42); VerifyEmitConstantsToIL((byte?)null); VerifyEmitConstantsToIL((byte?)42); VerifyEmitConstantsToIL((short?)null); VerifyEmitConstantsToIL((short?)42); VerifyEmitConstantsToIL((ushort?)null); VerifyEmitConstantsToIL((ushort?)42); VerifyEmitConstantsToIL((int?)null); VerifyEmitConstantsToIL((int?)42); VerifyEmitConstantsToIL((uint?)null); VerifyEmitConstantsToIL((uint?)42); VerifyEmitConstantsToIL((long?)null); VerifyEmitConstantsToIL((long?)42); VerifyEmitConstantsToIL((ulong?)null); VerifyEmitConstantsToIL((ulong?)42); VerifyEmitConstantsToIL((float?)null); VerifyEmitConstantsToIL((float?)3.14); VerifyEmitConstantsToIL((double?)null); VerifyEmitConstantsToIL((double?)3.14); VerifyEmitConstantsToIL((decimal?)null); VerifyEmitConstantsToIL((decimal?)49.95m); VerifyEmitConstantsToIL((DateTime?)null); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_ReferenceTypes() { VerifyEmitConstantsToIL((string)null); VerifyEmitConstantsToIL((string)"bar"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_Enums() { VerifyEmitConstantsToIL(ConstantsEnum.A); VerifyEmitConstantsToIL((ConstantsEnum?)null); VerifyEmitConstantsToIL((ConstantsEnum?)ConstantsEnum.A); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_ShareReferences() { var o = new object(); VerifyEmitConstantsToIL(Expression.Equal(Expression.Constant(o), Expression.Constant(o)), 1, true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void EmitConstantsToIL_LiftedToClosure() { VerifyEmitConstantsToIL(DateTime.Now, 1); VerifyEmitConstantsToIL((DateTime?)DateTime.Now, 1); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void VariableBinder_CatchBlock_Filter1() { // See https://github.com/dotnet/runtime/issues/18676 for reported issue Verify_VariableBinder_CatchBlock_Filter( Expression.Catch( Expression.Parameter(typeof(Exception), "ex"), Expression.Empty(), Expression.Parameter(typeof(bool), "???") ) ); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] public static void VariableBinder_CatchBlock_Filter2() { // See https://github.com/dotnet/runtime/issues/18676 for reported issue Verify_VariableBinder_CatchBlock_Filter( Expression.Catch( typeof(Exception), Expression.Empty(), Expression.Parameter(typeof(bool), "???") ) ); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Simple() { Expression<Func<int>> f = () => Math.Abs(42); f.VerifyIL( @".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: call int32 class [System.Private.CoreLib]System.Math::Abs(int32) IL_0007: ret }"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Exceptions() { ParameterExpression x = Expression.Parameter(typeof(int), "x"); Expression<Func<int, int>> f = Expression.Lambda<Func<int, int>>( Expression.TryCatchFinally( Expression.Call( typeof(Math).GetMethod(nameof(Math.Abs), new[] { typeof(int) }), Expression.Divide( Expression.Constant(42), x ) ), Expression.Empty(), Expression.Catch( typeof(DivideByZeroException), Expression.Constant(-1) ) ), x ); f.VerifyIL( @".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 4 .locals init ( [0] int32 ) .try { .try { IL_0000: ldc.i4.s 42 IL_0002: ldarg.1 IL_0003: div IL_0004: call int32 class [System.Private.CoreLib]System.Math::Abs(int32) IL_0009: stloc.0 IL_000a: leave IL_0017 } catch (class [System.Private.CoreLib]System.DivideByZeroException) { IL_000f: pop IL_0010: ldc.i4.m1 IL_0011: stloc.0 IL_0012: leave IL_0017 } IL_0017: leave IL_001d } finally { IL_001c: endfinally } IL_001d: ldloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure1() { Expression<Func<Func<int>>> f = () => () => 42; f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 3 IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0006: ldc.i4.0 IL_0007: ldelem.ref IL_0008: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_000d: ldtoken class [System.Private.CoreLib]System.Func`1<int32> IL_0012: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0017: ldnull IL_0018: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_001d: castclass class [System.Private.CoreLib]System.Func`1<int32> IL_0022: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }", appendInnerLambdas: true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure2() { Expression<Func<int, Func<int>>> f = x => () => x; f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 8 .locals init ( [0] object[] ) IL_0000: ldc.i4.1 IL_0001: newarr object IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.1 IL_0009: newobj instance void class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32) IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_001d: ldtoken class [System.Private.CoreLib]System.Func`1<int32> IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0027: ldnull IL_0028: ldloc.0 IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[]) IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_0033: castclass class [System.Private.CoreLib]System.Func`1<int32> IL_0038: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 2 .locals init ( [0] object[] ) IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldelem.ref IL_000a: castclass class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32> IL_000f: ldfld class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::Value IL_0014: ret }", appendInnerLambdas: true); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotLinqExpressionsBuiltWithIsInterpretingOnly))] [ActiveIssue("https://github.com/mono/mono/issues/14919", TestRuntimes.Mono)] public static void VerifyIL_Closure3() { // Using an unchecked addition to ensure that an add instruction is emitted (and not add.ovf) Expression<Func<int, Func<int, int>>> f = x => y => unchecked(x + y); f.VerifyIL( @".method class [System.Private.CoreLib]System.Func`2<int32,int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 8 .locals init ( [0] object[] ) IL_0000: ldc.i4.1 IL_0001: newarr object IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.1 IL_0009: newobj instance void class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32) IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo IL_001d: ldtoken class [System.Private.CoreLib]System.Func`2<int32,int32> IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle) IL_0027: ldnull IL_0028: ldloc.0 IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[]) IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object) IL_0033: castclass class [System.Private.CoreLib]System.Func`2<int32,int32> IL_0038: ret } // closure.Constants[0] .method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32) { .maxstack 2 .locals init ( [0] object[] ) IL_0000: ldarg.0 IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldelem.ref IL_000a: castclass class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32> IL_000f: ldfld class [System.Private.CoreLib]System.Runtime.CompilerServices.StrongBox`1<int32>::Value IL_0014: ldarg.1 IL_0015: add IL_0016: ret }", appendInnerLambdas: true); } internal static void VerifyIL(this LambdaExpression expression, string expected, bool appendInnerLambdas = false) { string actual = expression.GetIL(appendInnerLambdas); string nExpected = Normalize(expected); string nActual = Normalize(actual); Assert.Equal(nExpected, nActual); } private static string Normalize(string s) { var normalizeRegex = new Regex(@"lambda_method[0-9]*"); Collections.Generic.IEnumerable<string> lines = s .Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Where(line => !line.StartsWith("//")) .Select(beforeLambdaUniquifierRemoval => normalizeRegex.Replace(beforeLambdaUniquifierRemoval, "lambda_method")); return string.Join("\n", lines); } private static void VerifyEmitConstantsToIL<T>(T value) { VerifyEmitConstantsToIL<T>(value, 0); } private static void VerifyEmitConstantsToIL<T>(T value, int expectedCount) { VerifyEmitConstantsToIL(Expression.Constant(value, typeof(T)), expectedCount, value); } private static void VerifyEmitConstantsToIL(Expression e, int expectedCount, object expectedValue) { Delegate f = Expression.Lambda(e).Compile(); var c = f.Target as Closure; Assert.NotNull(c); Assert.Equal(expectedCount, c.Constants.Length); object o = f.DynamicInvoke(); Assert.Equal(expectedValue, o); } private static void Verify_VariableBinder_CatchBlock_Filter(CatchBlock @catch) { Expression<Action> e = Expression.Lambda<Action>( Expression.TryCatch( Expression.Empty(), @catch ) ); Assert.Throws<InvalidOperationException>(() => e.Compile()); } } public enum ConstantsEnum { A } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Linq.Expressions.Tests { public class GetDelegateTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetDelegateType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs[1]", () => Expression.GetDelegateType(typeof(int), null)); } [Fact] public void EmptyArgs() { AssertExtensions.Throws<ArgumentException>("typeArgs", () => Expression.GetDelegateType()); } [Theory, MemberData(nameof(ValidTypeArgs), true)] public void SuccessfulGetFuncType(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs); Assert.StartsWith("System.Func`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray()); Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Fact] public void GetNullaryAction() { Assert.Equal(typeof(Action), Expression.GetDelegateType(typeof(void))); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(ByRefLikeTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] public void CantBeFunc(Type[] typeArgs) { if (!RuntimeFeature.IsDynamicCodeSupported) { Assert.Throws<PlatformNotSupportedException>(() => Expression.GetDelegateType(typeArgs)); } else { Type delType = Expression.GetDelegateType(typeArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName); Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeArgs.Last(), method.ReturnType); Assert.Equal(typeArgs.Take(typeArgs.Length - 1), method.GetParameters().Select(p => p.ParameterType)); } } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(ByRefLikeTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] public void CantBeAction(Type[] typeArgs) { Type[] delegateArgs = typeArgs.Append(typeof(void)).ToArray(); if (!RuntimeFeature.IsDynamicCodeSupported) { Assert.Throws<PlatformNotSupportedException>(() => Expression.GetDelegateType(delegateArgs)); } else { Type delType = Expression.GetDelegateType(delegateArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName); Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeof(void), method.ReturnType); Assert.Equal(typeArgs, method.GetParameters().Select(p => p.ParameterType)); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetFuncTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs); Assert.Equal("Func`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray()); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(VoidTypeArgs), false)] public void VoidArgToFuncTypeDelegate(Type[] typeArgs) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.GetDelegateType(typeArgs)); } [Theory, MemberData(nameof(VoidTypeArgs), false)] public void VoidArgToActionTypeDelegate(Type[] typeArgs) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using Xunit; namespace System.Linq.Expressions.Tests { public class GetDelegateTypeTests : DelegateCreationTests { [Fact] public void NullTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs", () => Expression.GetDelegateType(default(Type[]))); } [Fact] public void NullInTypeList() { AssertExtensions.Throws<ArgumentNullException>("typeArgs[1]", () => Expression.GetDelegateType(typeof(int), null)); } [Fact] public void EmptyArgs() { AssertExtensions.Throws<ArgumentException>("typeArgs", () => Expression.GetDelegateType()); } [Theory, MemberData(nameof(ValidTypeArgs), true)] public void SuccessfulGetFuncType(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs); Assert.StartsWith("System.Func`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(ValidTypeArgs), false)] public void SuccessfulGetActionType(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray()); Assert.StartsWith("System.Action`" + typeArgs.Length, funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Fact] public void GetNullaryAction() { Assert.Equal(typeof(Action), Expression.GetDelegateType(typeof(void))); } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(ByRefLikeTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] public void CantBeFunc(Type[] typeArgs) { if (!RuntimeFeature.IsDynamicCodeSupported) { Assert.Throws<PlatformNotSupportedException>(() => Expression.GetDelegateType(typeArgs)); } else { Type delType = Expression.GetDelegateType(typeArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); Assert.DoesNotContain("System.Action", delType.FullName); Assert.DoesNotContain("System.Func", delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeArgs.Last(), method.ReturnType); Assert.Equal(typeArgs.Take(typeArgs.Length - 1), method.GetParameters().Select(p => p.ParameterType)); } } [Theory] [MemberData(nameof(ExcessiveLengthTypeArgs))] [MemberData(nameof(ExcessiveLengthOpenGenericTypeArgs))] [MemberData(nameof(ByRefTypeArgs))] [MemberData(nameof(ByRefLikeTypeArgs))] [MemberData(nameof(PointerTypeArgs))] [MemberData(nameof(ManagedPointerTypeArgs))] public void CantBeAction(Type[] typeArgs) { Type[] delegateArgs = typeArgs.Append(typeof(void)).ToArray(); if (!RuntimeFeature.IsDynamicCodeSupported) { Assert.Throws<PlatformNotSupportedException>(() => Expression.GetDelegateType(delegateArgs)); } else { Type delType = Expression.GetDelegateType(delegateArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); Assert.DoesNotContain("System.Action", delType.FullName); Assert.DoesNotContain("System.Func", delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeof(void), method.ReturnType); Assert.Equal(typeArgs, method.GetParameters().Select(p => p.ParameterType)); } } // Open generic type args aren't useful directly with Expressions, but creating them is allowed. [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetFuncTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs); Assert.Equal("Func`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(OpenGenericTypeArgs), false)] public void SuccessfulGetActionTypeOpenGeneric(Type[] typeArgs) { Type funcType = Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray()); Assert.Equal("Action`" + typeArgs.Length, funcType.Name); Assert.Null(funcType.FullName); Assert.Equal(typeArgs, funcType.GetGenericArguments()); } [Theory, MemberData(nameof(VoidTypeArgs), false)] public void VoidArgToFuncTypeDelegate(Type[] typeArgs) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.GetDelegateType(typeArgs)); } [Theory, MemberData(nameof(VoidTypeArgs), false)] public void VoidArgToActionTypeDelegate(Type[] typeArgs) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.GetDelegateType(typeArgs.Append(typeof(void)).ToArray())); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <NoWarn>$(NoWarn);1634;1691;649</NoWarn> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <!-- Too much private reflection. Do not bother with trimming --> <ILLinkTrimAssembly>false</ILLinkTrimAssembly> <Nullable>enable</Nullable> </PropertyGroup> <PropertyGroup> <RuntimeSerializationSources>System\Runtime\Serialization</RuntimeSerializationSources> <JsonSources>System\Runtime\Serialization\Json</JsonSources> <XmlSources>System\Xml</XmlSources> <TextSources>System\Text</TextSources> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="$(RuntimeSerializationSources)\Attributes.cs" /> <Compile Include="$(RuntimeSerializationSources)\CodeGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\ClassDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\CollectionDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\DateTimeOffsetAdapter.cs" /> <Compile Include="$(RuntimeSerializationSources)\DiagnosticUtility.cs" /> <Compile Include="$(RuntimeSerializationSources)\DictionaryGlobals.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractResolver.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializer.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializerSettings.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataMember.cs" /> <Compile Include="$(RuntimeSerializationSources)\EnumDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\ExtensionDataObject.cs" /> <Compile Include="$(RuntimeSerializationSources)\ExtensionDataReader.cs" /> <Compile Include="$(RuntimeSerializationSources)\Globals.cs" /> <Compile Include="$(RuntimeSerializationSources)\GenericParameterDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\HybridObjectCache.cs" /> <Compile Include="$(RuntimeSerializationSources)\ObjectToIdCache.cs" /> <Compile Include="$(RuntimeSerializationSources)\ObjectReferenceStack.cs" /> <Compile Include="$(RuntimeSerializationSources)\PrimitiveDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\SchemaExporter.cs" /> <Compile Include="$(RuntimeSerializationSources)\ScopedKnownTypes.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatGeneratorStatics.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatReaderGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatWriterGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializer.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerWriteContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerReadContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlReaderDelegator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableReader.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableWriter.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlWriterDelegator.cs" /> <Compile Include="$(RuntimeSerializationSources)\SerializationMode.cs" /> <Compile Include="$(RuntimeSerializationSources)\SpecialTypeDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\TypeCode.cs" /> <Compile Include="$(RuntimeSerializationSources)\KnownTypeDataContractResolver.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerReadContextComplex.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerWriteContextComplex.cs" /> <Compile Include="$(RuntimeSerializationSources)\BitFlagsGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSurrogateCaller.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializerExtensions.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableServices.cs" /> <Compile Include="$(XmlSources)\ArrayHelper.cs" /> <Compile Include="$(XmlSources)\BytesWithOffset.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryAsyncCheckWriter.cs" /> <Compile Include="$(XmlSources)\IStreamProvider.cs" /> <Compile Include="$(XmlSources)\IXmlDictionary.cs" /> <Compile Include="$(XmlSources)\PrefixHandle.cs" /> <Compile Include="$(XmlSources)\StringHandle.cs" /> <Compile Include="$(XmlSources)\UniqueId.cs" /> <Compile Include="$(XmlSources)\ValueHandle.cs" /> <Compile Include="$(XmlSources)\XmlBaseReader.cs" /> <Compile Include="$(XmlSources)\XmlBaseWriter.cs" /> <Compile Include="$(XmlSources)\XmlBinaryNodeType.cs" /> <Compile Include="$(XmlSources)\XmlBinaryReader.cs" /> <Compile Include="$(XmlSources)\XmlBinaryReaderSession.cs" /> <Compile Include="$(XmlSources)\XmlBinaryWriter.cs" /> <Compile Include="$(XmlSources)\XmlBinaryWriterSession.cs" /> <Compile Include="$(XmlSources)\XmlBufferReader.cs" /> <Compile Include="$(XmlSources)\XmlConverter.cs" /> <Compile Include="$(XmlSources)\XmlDictionary.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryWriter.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryReader.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryReaderQuotas.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryString.cs" /> <Compile Include="$(XmlSources)\XmlExceptionHelper.cs" /> <Compile Include="$(XmlSources)\XmlNodeWriter.cs" /> <Compile Include="$(XmlSources)\XmlStreamNodeWriter.cs" /> <Compile Include="$(XmlSources)\XmlUTF8TextReader.cs" /> <Compile Include="$(XmlSources)\XmlUTF8TextWriter.cs" /> <Compile Include="$(XmlSources)\EncodingStreamWrapper.cs" /> <Compile Include="$(TextSources)\Base64Encoding.cs" /> <Compile Include="$(TextSources)\SurrogateChar.cs" /> <Compile Include="$(TextSources)\BinHexEncoding.cs" /> <Compile Include="$(JsonSources)\DataContractJsonSerializer.cs" /> <Compile Include="$(JsonSources)\JsonByteArrayDataContract.cs" /> <Compile Include="$(JsonSources)\JsonClassDataContract.cs" /> <Compile Include="$(JsonSources)\JsonCollectionDataContract.cs" /> <Compile Include="$(JsonSources)\JsonDataContract.cs" /> <Compile Include="$(JsonSources)\JsonEnumDataContract.cs" /> <Compile Include="$(JsonSources)\JsonFormatWriterGenerator.cs" /> <Compile Include="$(JsonSources)\JsonFormatReaderGenerator.cs" /> <Compile Include="$(JsonSources)\JsonObjectDataContract.cs" /> <Compile Include="$(JsonSources)\JsonQNameDataContract.cs" /> <Compile Include="$(JsonSources)\JsonReaderDelegator.cs" /> <Compile Include="$(JsonSources)\JsonWriterDelegator.cs" /> <Compile Include="$(JsonSources)\JsonStringDataContract.cs" /> <Compile Include="$(JsonSources)\JsonUriDataContract.cs" /> <Compile Include="$(JsonSources)\JsonXmlDataContract.cs" /> <Compile Include="$(JsonSources)\JsonGlobals.cs" /> <Compile Include="$(JsonSources)\XmlObjectSerializerReadContextComplexJson.cs" /> <Compile Include="$(JsonSources)\XmlObjectSerializerWriteContextComplexJson.cs" /> <Compile Include="$(JsonSources)\DateTimeFormat.cs" /> <Compile Include="$(JsonSources)\EmitTypeInformation.cs" /> <Compile Include="$(JsonSources)\DataContractJsonSerializerSettings.cs" /> <Compile Include="$(JsonSources)\XmlJsonReader.cs" /> <Compile Include="$(JsonSources)\XmlJsonWriter.cs" /> <Compile Include="$(JsonSources)\JsonReaderWriterFactory.cs" /> <Compile Include="$(JsonSources)\JsonNodeType.cs" /> <Compile Include="$(JsonSources)\IXmlJsonReaderInitializer.cs" /> <Compile Include="$(JsonSources)\IXmlJsonWriterInitializer.cs" /> <Compile Include="$(JsonSources)\ByteArrayHelperWithString.cs" /> <Compile Include="$(JsonSources)\JsonEncodingStreamWrapper.cs" /> <Compile Include="$(JsonSources)\JsonFormatGeneratorStatics.cs" /> <Compile Include="System\Runtime\Serialization\AccessorBuilder.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeTypeReference.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeTypeReferenceCollection.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeObject.cs" /> <Compile Include="System\Runtime\Serialization\DataContractSet.cs" /> <Compile Include="System\Runtime\Serialization\ExportOptions.cs" /> <Compile Include="System\Runtime\Serialization\IExtensibleDataObject.cs" /> <Compile Include="System\Runtime\Serialization\Json\ReflectionJsonFormatReader.cs" /> <Compile Include="System\Runtime\Serialization\Json\ReflectionJsonFormatWriter.cs" /> <Compile Include="System\Runtime\Serialization\MemoryStreamAdapter.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionFeature.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionReader.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionClassWriter.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionXmlFormatReader.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionXmlFormatWriter.cs" /> <Compile Include="System\Runtime\Serialization\SchemaHelper.cs" /> <Compile Include="System\Runtime\Serialization\SerializationOption.cs" /> <Compile Include="System\Runtime\Serialization\XPathQueryGenerator.cs" /> <Compile Include="System\Runtime\Serialization\XsdDataContractExporter.cs" /> <Compile Include="System\Runtime\Serialization\SurrogateDataContract.cs" /> <Compile Include="System\Xml\IFragmentCapableXmlDictionaryWriter.cs" /> <Compile Include="System\Xml\XmlCanonicalWriter.cs" /> <Compile Include="System\Xml\XmlSigningNodeWriter.cs" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.Linq" /> <Reference Include="System.Memory" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.Serialization.Formatters" /> <Reference Include="System.Runtime.Serialization.Primitives" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Xml.ReaderWriter" /> <Reference Include="System.Xml.XDocument" /> <Reference Include="System.Xml.XmlSerializer" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <NoWarn>$(NoWarn);1634;1691;649</NoWarn> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <!-- Too much private reflection. Do not bother with trimming --> <ILLinkTrimAssembly>false</ILLinkTrimAssembly> <Nullable>enable</Nullable> <EnableRegexGenerator>true</EnableRegexGenerator> </PropertyGroup> <PropertyGroup> <RuntimeSerializationSources>System\Runtime\Serialization</RuntimeSerializationSources> <JsonSources>System\Runtime\Serialization\Json</JsonSources> <XmlSources>System\Xml</XmlSources> <TextSources>System\Text</TextSources> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="$(RuntimeSerializationSources)\Attributes.cs" /> <Compile Include="$(RuntimeSerializationSources)\CodeGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\ClassDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\CollectionDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\DateTimeOffsetAdapter.cs" /> <Compile Include="$(RuntimeSerializationSources)\DiagnosticUtility.cs" /> <Compile Include="$(RuntimeSerializationSources)\DictionaryGlobals.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractResolver.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializer.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializerSettings.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataMember.cs" /> <Compile Include="$(RuntimeSerializationSources)\EnumDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\ExtensionDataObject.cs" /> <Compile Include="$(RuntimeSerializationSources)\ExtensionDataReader.cs" /> <Compile Include="$(RuntimeSerializationSources)\Globals.cs" /> <Compile Include="$(RuntimeSerializationSources)\GenericParameterDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\HybridObjectCache.cs" /> <Compile Include="$(RuntimeSerializationSources)\ObjectToIdCache.cs" /> <Compile Include="$(RuntimeSerializationSources)\ObjectReferenceStack.cs" /> <Compile Include="$(RuntimeSerializationSources)\PrimitiveDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\SchemaExporter.cs" /> <Compile Include="$(RuntimeSerializationSources)\ScopedKnownTypes.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatGeneratorStatics.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatReaderGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlFormatWriterGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializer.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerWriteContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerReadContext.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlReaderDelegator.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableReader.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableWriter.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlWriterDelegator.cs" /> <Compile Include="$(RuntimeSerializationSources)\SerializationMode.cs" /> <Compile Include="$(RuntimeSerializationSources)\SpecialTypeDataContract.cs" /> <Compile Include="$(RuntimeSerializationSources)\TypeCode.cs" /> <Compile Include="$(RuntimeSerializationSources)\KnownTypeDataContractResolver.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerReadContextComplex.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlObjectSerializerWriteContextComplex.cs" /> <Compile Include="$(RuntimeSerializationSources)\BitFlagsGenerator.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSurrogateCaller.cs" /> <Compile Include="$(RuntimeSerializationSources)\DataContractSerializerExtensions.cs" /> <Compile Include="$(RuntimeSerializationSources)\XmlSerializableServices.cs" /> <Compile Include="$(XmlSources)\ArrayHelper.cs" /> <Compile Include="$(XmlSources)\BytesWithOffset.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryAsyncCheckWriter.cs" /> <Compile Include="$(XmlSources)\IStreamProvider.cs" /> <Compile Include="$(XmlSources)\IXmlDictionary.cs" /> <Compile Include="$(XmlSources)\PrefixHandle.cs" /> <Compile Include="$(XmlSources)\StringHandle.cs" /> <Compile Include="$(XmlSources)\UniqueId.cs" /> <Compile Include="$(XmlSources)\ValueHandle.cs" /> <Compile Include="$(XmlSources)\XmlBaseReader.cs" /> <Compile Include="$(XmlSources)\XmlBaseWriter.cs" /> <Compile Include="$(XmlSources)\XmlBinaryNodeType.cs" /> <Compile Include="$(XmlSources)\XmlBinaryReader.cs" /> <Compile Include="$(XmlSources)\XmlBinaryReaderSession.cs" /> <Compile Include="$(XmlSources)\XmlBinaryWriter.cs" /> <Compile Include="$(XmlSources)\XmlBinaryWriterSession.cs" /> <Compile Include="$(XmlSources)\XmlBufferReader.cs" /> <Compile Include="$(XmlSources)\XmlConverter.cs" /> <Compile Include="$(XmlSources)\XmlDictionary.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryWriter.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryReader.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryReaderQuotas.cs" /> <Compile Include="$(XmlSources)\XmlDictionaryString.cs" /> <Compile Include="$(XmlSources)\XmlExceptionHelper.cs" /> <Compile Include="$(XmlSources)\XmlNodeWriter.cs" /> <Compile Include="$(XmlSources)\XmlStreamNodeWriter.cs" /> <Compile Include="$(XmlSources)\XmlUTF8TextReader.cs" /> <Compile Include="$(XmlSources)\XmlUTF8TextWriter.cs" /> <Compile Include="$(XmlSources)\EncodingStreamWrapper.cs" /> <Compile Include="$(TextSources)\Base64Encoding.cs" /> <Compile Include="$(TextSources)\SurrogateChar.cs" /> <Compile Include="$(TextSources)\BinHexEncoding.cs" /> <Compile Include="$(JsonSources)\DataContractJsonSerializer.cs" /> <Compile Include="$(JsonSources)\JsonByteArrayDataContract.cs" /> <Compile Include="$(JsonSources)\JsonClassDataContract.cs" /> <Compile Include="$(JsonSources)\JsonCollectionDataContract.cs" /> <Compile Include="$(JsonSources)\JsonDataContract.cs" /> <Compile Include="$(JsonSources)\JsonEnumDataContract.cs" /> <Compile Include="$(JsonSources)\JsonFormatWriterGenerator.cs" /> <Compile Include="$(JsonSources)\JsonFormatReaderGenerator.cs" /> <Compile Include="$(JsonSources)\JsonObjectDataContract.cs" /> <Compile Include="$(JsonSources)\JsonQNameDataContract.cs" /> <Compile Include="$(JsonSources)\JsonReaderDelegator.cs" /> <Compile Include="$(JsonSources)\JsonWriterDelegator.cs" /> <Compile Include="$(JsonSources)\JsonStringDataContract.cs" /> <Compile Include="$(JsonSources)\JsonUriDataContract.cs" /> <Compile Include="$(JsonSources)\JsonXmlDataContract.cs" /> <Compile Include="$(JsonSources)\JsonGlobals.cs" /> <Compile Include="$(JsonSources)\XmlObjectSerializerReadContextComplexJson.cs" /> <Compile Include="$(JsonSources)\XmlObjectSerializerWriteContextComplexJson.cs" /> <Compile Include="$(JsonSources)\DateTimeFormat.cs" /> <Compile Include="$(JsonSources)\EmitTypeInformation.cs" /> <Compile Include="$(JsonSources)\DataContractJsonSerializerSettings.cs" /> <Compile Include="$(JsonSources)\XmlJsonReader.cs" /> <Compile Include="$(JsonSources)\XmlJsonWriter.cs" /> <Compile Include="$(JsonSources)\JsonReaderWriterFactory.cs" /> <Compile Include="$(JsonSources)\JsonNodeType.cs" /> <Compile Include="$(JsonSources)\IXmlJsonReaderInitializer.cs" /> <Compile Include="$(JsonSources)\IXmlJsonWriterInitializer.cs" /> <Compile Include="$(JsonSources)\ByteArrayHelperWithString.cs" /> <Compile Include="$(JsonSources)\JsonEncodingStreamWrapper.cs" /> <Compile Include="$(JsonSources)\JsonFormatGeneratorStatics.cs" /> <Compile Include="System\Runtime\Serialization\AccessorBuilder.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeTypeReference.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeTypeReferenceCollection.cs" /> <Compile Include="$(CommonPath)System\CodeDom\CodeObject.cs" /> <Compile Include="System\Runtime\Serialization\DataContractSet.cs" /> <Compile Include="System\Runtime\Serialization\ExportOptions.cs" /> <Compile Include="System\Runtime\Serialization\IExtensibleDataObject.cs" /> <Compile Include="System\Runtime\Serialization\Json\ReflectionJsonFormatReader.cs" /> <Compile Include="System\Runtime\Serialization\Json\ReflectionJsonFormatWriter.cs" /> <Compile Include="System\Runtime\Serialization\MemoryStreamAdapter.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionFeature.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionReader.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionClassWriter.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionXmlFormatReader.cs" /> <Compile Include="System\Runtime\Serialization\ReflectionXmlFormatWriter.cs" /> <Compile Include="System\Runtime\Serialization\SchemaHelper.cs" /> <Compile Include="System\Runtime\Serialization\SerializationOption.cs" /> <Compile Include="System\Runtime\Serialization\XPathQueryGenerator.cs" /> <Compile Include="System\Runtime\Serialization\XsdDataContractExporter.cs" /> <Compile Include="System\Runtime\Serialization\SurrogateDataContract.cs" /> <Compile Include="System\Xml\IFragmentCapableXmlDictionaryWriter.cs" /> <Compile Include="System\Xml\XmlCanonicalWriter.cs" /> <Compile Include="System\Xml\XmlSigningNodeWriter.cs" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Collections.Specialized" /> <Reference Include="System.Linq" /> <Reference Include="System.Memory" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Primitives" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.Serialization.Formatters" /> <Reference Include="System.Runtime.Serialization.Primitives" /> <Reference Include="System.Text.Encoding.Extensions" /> <Reference Include="System.Text.RegularExpressions" /> <Reference Include="System.Threading" /> <Reference Include="System.Xml.ReaderWriter" /> <Reference Include="System.Xml.XDocument" /> <Reference Include="System.Xml.XmlSerializer" /> </ItemGroup> </Project>
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.Serialization { using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Text.RegularExpressions; using System.Runtime.CompilerServices; using System.Linq; using Xml.Schema; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; internal abstract class DataContract { private XmlDictionaryString _name; private XmlDictionaryString _ns; // this the global dictionary for data contracts introduced for multi-file. private static readonly Dictionary<Type, DataContract> s_dataContracts = new Dictionary<Type, DataContract>(); internal const string SerializerTrimmerWarning = "Data Contract Serialization and Deserialization might require types that cannot be statically analyzed. Make sure all of the " + "required types are preserved."; public static Dictionary<Type, DataContract> GetDataContracts() { return s_dataContracts; } private readonly DataContractCriticalHelper _helper; internal DataContract(DataContractCriticalHelper helper) { _helper = helper; _name = helper.Name; _ns = helper.Namespace; } private static DataContract? GetGeneratedDataContract(Type type) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method DataContract? result; return s_dataContracts.TryGetValue(type, out result) ? result : null; } internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract? dataContract) { dataContract = GetGeneratedDataContract(type); return dataContract != null; } internal static DataContract? GetDataContractFromGeneratedAssembly(Type? type) { return null; } internal MethodInfo? ParseMethod { get { return _helper.ParseMethod; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(Type type) { return GetDataContract(type.TypeHandle, type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { return GetDataContract(typeHandle, type, SerializationMode.SharedContract); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { int id = GetId(typeHandle); DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); return dataContract.GetValidContract(mode); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle, SerializationMode mode) { DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); return dataContract.GetValidContract(mode); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); dataContract = dataContract.GetValidContract(mode); if (dataContract is ClassDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)), SR.Format(SR.NoSetMethodForProperty, string.Empty, string.Empty)))); } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); } internal static DataContract GetDataContractForInitialization(int id) { return DataContractCriticalHelper.GetDataContractForInitialization(id); } internal static int GetIdForInitialization(ClassDataContract classContract) { return DataContractCriticalHelper.GetIdForInitialization(classContract); } internal static int GetId(RuntimeTypeHandle typeHandle) { return DataContractCriticalHelper.GetId(typeHandle); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(Type type) { return DataContractCriticalHelper.GetBuiltInDataContract(type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string name, string ns) { return DataContractCriticalHelper.GetBuiltInDataContract(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string typeName) { return DataContractCriticalHelper.GetBuiltInDataContract(typeName); } internal static string GetNamespace(string key) { return DataContractCriticalHelper.GetNamespace(key); } internal static XmlDictionaryString GetClrTypeString(string key) { return DataContractCriticalHelper.GetClrTypeString(key); } [DoesNotReturn] internal static void ThrowInvalidDataContractException(string? message, Type? type) { DataContractCriticalHelper.ThrowInvalidDataContractException(message, type); } protected DataContractCriticalHelper Helper { get { return _helper; } } [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] public Type UnderlyingType { get { return _helper.UnderlyingType; } set { _helper.UnderlyingType = value; } } public Type OriginalUnderlyingType { get { return _helper.OriginalUnderlyingType; } set { _helper.OriginalUnderlyingType = value; } } public virtual bool IsBuiltInDataContract { get { return _helper.IsBuiltInDataContract; } set { } } internal Type TypeForInitialization { get { return _helper.TypeForInitialization; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } public virtual object ReadXmlElement(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } public bool IsValueType { get { return _helper.IsValueType; } set { _helper.IsValueType = value; } } public bool IsReference { get { return _helper.IsReference; } set { _helper.IsReference = value; } } public XmlQualifiedName StableName { get { return _helper.StableName; } set { _helper.StableName = value; } } public virtual DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } public virtual bool IsISerializable { get { return _helper.IsISerializable; } set { _helper.IsISerializable = value; } } public XmlDictionaryString Name { get { return _name; } set { _name = value; } } public virtual XmlDictionaryString Namespace { get { return _ns; } set { _ns = value; } } public virtual bool HasRoot { get { return true; } set { } } public virtual XmlDictionaryString? TopLevelElementName { get { return _helper.TopLevelElementName; } set { _helper.TopLevelElementName = value; } } public virtual XmlDictionaryString? TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } set { _helper.TopLevelElementNamespace = value; } } internal virtual bool CanContainReferences { get { return true; } } internal virtual bool IsPrimitive { get { return false; } } internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive) writer.WriteStartElement(Globals.SerPrefix, name, ns); else writer.WriteStartElement(name, ns); } internal virtual DataContract GetValidContract(SerializationMode mode) { return this; } internal virtual DataContract GetValidContract() { return this; } internal virtual bool IsValidContract(SerializationMode mode) { return true; } internal class DataContractCriticalHelper { private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private static DataContract[] s_dataContractCache = new DataContract[32]; private static int s_dataContractID; private static Dictionary<Type, DataContract?>? s_typeToBuiltInContract; private static Dictionary<XmlQualifiedName, DataContract?>? s_nameToBuiltInContract; private static Dictionary<string, string>? s_namespaces; private static Dictionary<string, XmlDictionaryString>? s_clrTypeStrings; private static XmlDictionary? s_clrTypeStringsDictionary; private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly object s_cacheLock = new object(); private static readonly object s_createDataContractLock = new object(); private static readonly object s_initBuiltInContractsLock = new object(); private static readonly object s_namespacesLock = new object(); private static readonly object s_clrTypeStringsLock = new object(); [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] private Type _underlyingType; private Type? _originalUnderlyingType; private bool _isReference; private bool _isValueType; private XmlQualifiedName _stableName = null!; // StableName is always set in concrete ctors set except for the "invalid" CollectionDataContract private XmlDictionaryString _name = null!; // Name is always set in concrete ctors set except for the "invalid" CollectionDataContract private XmlDictionaryString _ns = null!; // Namespace is always set in concrete ctors set except for the "invalid" CollectionDataContract private MethodInfo? _parseMethod; private bool _parseMethodSet; /// <SecurityNote> /// Critical - in deserialization, we initialize an object instance passing this Type to GetUninitializedObject method /// </SecurityNote> private Type _typeForInitialization; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateDataContract(id, typeHandle, type); AssignDataContractToId(dataContract, id); } else { return dataContract.GetValidContract(); } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type); s_dataContractCache[id] = dataContract; } return dataContract; } internal static DataContract GetDataContractForInitialization(int id) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } return dataContract; } internal static int GetIdForInitialization(ClassDataContract classContract) { int id = DataContract.GetId(classContract.TypeForInitialization!.TypeHandle); if (id < s_dataContractCache.Length && ContractMatches(classContract, s_dataContractCache[id])) { return id; } int currentDataContractId = DataContractCriticalHelper.s_dataContractID; for (int i = 0; i < currentDataContractId; i++) { if (ContractMatches(classContract, s_dataContractCache[i])) { return i; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } private static bool ContractMatches(DataContract contract, DataContract cachedContract) { return (cachedContract != null && cachedContract.UnderlyingType == contract.UnderlyingType); } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef? id; typeHandle = GetDataContractAdapterTypeHandle(typeHandle); s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < int.MaxValue / 2) ? value * 2 : int.MaxValue; if (newSize <= value) { DiagnosticUtility.DebugAssert("DataContract cache overflow"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } Array.Resize<DataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract? dataContract = s_dataContractCache[id]; if (dataContract == null) { lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; if (dataContract == null) { if (type == null) type = Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract != null) { AssignDataContractToId(dataContract, id); return dataContract; } dataContract = CreateDataContract(type); } } } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateDataContract(Type type) { type = UnwrapNullableType(type); Type originalType = type; type = GetDataContractAdapterType(type); DataContract? dataContract = GetBuiltInDataContract(type); if (dataContract == null) { if (type.IsArray) dataContract = new CollectionDataContract(type); else if (type.IsEnum) dataContract = new EnumDataContract(type); else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) dataContract = new XmlDataContract(type); else if (Globals.TypeOfScriptObject_IsAssignableFrom(type)) dataContract = Globals.CreateScriptObjectClassDataContract(); else { //if (type.ContainsGenericParameters) // ThrowInvalidDataContractException(SR.Format(SR.TypeMustNotBeOpenGeneric, type), type); if (!CollectionDataContract.TryCreate(type, out dataContract)) { if (!type.IsSerializable && !type.IsDefined(Globals.TypeOfDataContractAttribute, false) && !ClassDataContract.IsNonAttributedTypeValidForSerialization(type) && !ClassDataContract.IsKnownSerializableType(type)) { ThrowInvalidDataContractException(SR.Format(SR.TypeNotSerializable, type), type); } dataContract = new ClassDataContract(type); if (type != originalType) { var originalDataContract = new ClassDataContract(originalType); if (dataContract.StableName != originalDataContract.StableName) { // for non-DC types, type adapters will not have the same stable name (contract name). dataContract.StableName = originalDataContract.StableName; } } } } } return dataContract; } [MethodImpl(MethodImplOptions.NoInlining)] private static void AssignDataContractToId(DataContract dataContract, int id) { lock (s_cacheLock) { s_dataContractCache[id] = dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract? dataContract = null; lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; if (dataContract == null) { if (type == null) type = Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract)) { ThrowInvalidDataContractException(SR.Format(SR.TypeNotSerializable, type), type); } } } return dataContract; } // This method returns adapter types used at runtime to create DataContract. [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static Type GetDataContractAdapterType(Type type) { // Replace the DataTimeOffset ISerializable type passed in with the internal DateTimeOffsetAdapter DataContract type. // DateTimeOffsetAdapter is used for serialization/deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust and to ensure correct schema import/export scenarios. if (type == Globals.TypeOfDateTimeOffset) { return Globals.TypeOfDateTimeOffsetAdapter; } if (type == Globals.TypeOfMemoryStream) { return Globals.TypeOfMemoryStreamAdapter; } if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePair) { return Globals.TypeOfKeyValuePairAdapter.MakeGenericType(type.GetGenericArguments()); } return type; } // Maps adapted types back to the original type // Any change to this method should be reflected in GetDataContractAdapterType internal static Type GetDataContractOriginalType(Type type) { if (type == Globals.TypeOfDateTimeOffsetAdapter) { return Globals.TypeOfDateTimeOffset; } if (type == Globals.TypeOfMemoryStreamAdapter) { return Globals.TypeOfMemoryStream; } return type; } private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHandle typeHandle) { if (Globals.TypeOfDateTimeOffset.TypeHandle.Equals(typeHandle)) { return Globals.TypeOfDateTimeOffsetAdapter.TypeHandle; } if (Globals.TypeOfMemoryStream.TypeHandle.Equals(typeHandle)) { return Globals.TypeOfMemoryStreamAdapter.TypeHandle; } return typeHandle; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(Type type) { if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type)) type = Globals.TypeOfObject; lock (s_initBuiltInContractsLock) { if (s_typeToBuiltInContract == null) s_typeToBuiltInContract = new Dictionary<Type, DataContract?>(); DataContract? dataContract; if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract)) { TryCreateBuiltInDataContract(type, out dataContract); s_typeToBuiltInContract.Add(type, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string name, string ns) { lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(name, ns); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { TryCreateBuiltInDataContract(name, ns, out dataContract); s_nameToBuiltInContract.Add(qname, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string typeName) { if (!typeName.StartsWith("System.", StringComparison.Ordinal)) return null; lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(typeName); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { Type? type = null; string name = typeName.Substring(7); if (name == "Char") type = typeof(char); else if (name == "Boolean") type = typeof(bool); else if (name == "SByte") type = typeof(sbyte); else if (name == "Byte") type = typeof(byte); else if (name == "Int16") type = typeof(short); else if (name == "UInt16") type = typeof(ushort); else if (name == "Int32") type = typeof(int); else if (name == "UInt32") type = typeof(uint); else if (name == "Int64") type = typeof(long); else if (name == "UInt64") type = typeof(ulong); else if (name == "Single") type = typeof(float); else if (name == "Double") type = typeof(double); else if (name == "Decimal") type = typeof(decimal); else if (name == "DateTime") type = typeof(DateTime); else if (name == "String") type = typeof(string); else if (name == "Byte[]") type = typeof(byte[]); else if (name == "Object") type = typeof(object); else if (name == "TimeSpan") type = typeof(TimeSpan); else if (name == "Guid") type = typeof(Guid); else if (name == "Uri") type = typeof(Uri); else if (name == "Xml.XmlQualifiedName") type = typeof(XmlQualifiedName); else if (name == "Enum") type = typeof(Enum); else if (name == "ValueType") type = typeof(ValueType); else if (name == "Array") type = typeof(Array); else if (name == "Xml.XmlElement") type = typeof(XmlElement); else if (name == "Xml.XmlNode[]") type = typeof(XmlNode[]); if (type != null) TryCreateBuiltInDataContract(type, out dataContract); s_nameToBuiltInContract.Add(qname, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static bool TryCreateBuiltInDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX { dataContract = null; return false; } dataContract = null; switch (type.GetTypeCode()) { case TypeCode.Boolean: dataContract = new BooleanDataContract(); break; case TypeCode.Byte: dataContract = new UnsignedByteDataContract(); break; case TypeCode.Char: dataContract = new CharDataContract(); break; case TypeCode.DateTime: dataContract = new DateTimeDataContract(); break; case TypeCode.Decimal: dataContract = new DecimalDataContract(); break; case TypeCode.Double: dataContract = new DoubleDataContract(); break; case TypeCode.Int16: dataContract = new ShortDataContract(); break; case TypeCode.Int32: dataContract = new IntDataContract(); break; case TypeCode.Int64: dataContract = new LongDataContract(); break; case TypeCode.SByte: dataContract = new SignedByteDataContract(); break; case TypeCode.Single: dataContract = new FloatDataContract(); break; case TypeCode.String: dataContract = new StringDataContract(); break; case TypeCode.UInt16: dataContract = new UnsignedShortDataContract(); break; case TypeCode.UInt32: dataContract = new UnsignedIntDataContract(); break; case TypeCode.UInt64: dataContract = new UnsignedLongDataContract(); break; default: if (type == typeof(byte[])) dataContract = new ByteArrayDataContract(); else if (type == typeof(object)) dataContract = new ObjectDataContract(); else if (type == typeof(Uri)) dataContract = new UriDataContract(); else if (type == typeof(XmlQualifiedName)) dataContract = new QNameDataContract(); else if (type == typeof(TimeSpan)) dataContract = new TimeSpanDataContract(); else if (type == typeof(Guid)) dataContract = new GuidDataContract(); else if (type == typeof(Enum) || type == typeof(ValueType)) { dataContract = new SpecialTypeDataContract(type, DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace); } else if (type == typeof(Array)) dataContract = new CollectionDataContract(type); else if (type == typeof(XmlElement) || type == typeof(XmlNode[])) dataContract = new XmlDataContract(type); break; } return dataContract != null; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = null; if (ns == DictionaryGlobals.SchemaNamespace.Value) { if (DictionaryGlobals.BooleanLocalName.Value == name) dataContract = new BooleanDataContract(); else if (DictionaryGlobals.SignedByteLocalName.Value == name) dataContract = new SignedByteDataContract(); else if (DictionaryGlobals.UnsignedByteLocalName.Value == name) dataContract = new UnsignedByteDataContract(); else if (DictionaryGlobals.ShortLocalName.Value == name) dataContract = new ShortDataContract(); else if (DictionaryGlobals.UnsignedShortLocalName.Value == name) dataContract = new UnsignedShortDataContract(); else if (DictionaryGlobals.IntLocalName.Value == name) dataContract = new IntDataContract(); else if (DictionaryGlobals.UnsignedIntLocalName.Value == name) dataContract = new UnsignedIntDataContract(); else if (DictionaryGlobals.LongLocalName.Value == name) dataContract = new LongDataContract(); else if (DictionaryGlobals.integerLocalName.Value == name) dataContract = new IntegerDataContract(); else if (DictionaryGlobals.positiveIntegerLocalName.Value == name) dataContract = new PositiveIntegerDataContract(); else if (DictionaryGlobals.negativeIntegerLocalName.Value == name) dataContract = new NegativeIntegerDataContract(); else if (DictionaryGlobals.nonPositiveIntegerLocalName.Value == name) dataContract = new NonPositiveIntegerDataContract(); else if (DictionaryGlobals.nonNegativeIntegerLocalName.Value == name) dataContract = new NonNegativeIntegerDataContract(); else if (DictionaryGlobals.UnsignedLongLocalName.Value == name) dataContract = new UnsignedLongDataContract(); else if (DictionaryGlobals.FloatLocalName.Value == name) dataContract = new FloatDataContract(); else if (DictionaryGlobals.DoubleLocalName.Value == name) dataContract = new DoubleDataContract(); else if (DictionaryGlobals.DecimalLocalName.Value == name) dataContract = new DecimalDataContract(); else if (DictionaryGlobals.DateTimeLocalName.Value == name) dataContract = new DateTimeDataContract(); else if (DictionaryGlobals.StringLocalName.Value == name) dataContract = new StringDataContract(); else if (DictionaryGlobals.timeLocalName.Value == name) dataContract = new TimeDataContract(); else if (DictionaryGlobals.dateLocalName.Value == name) dataContract = new DateDataContract(); else if (DictionaryGlobals.hexBinaryLocalName.Value == name) dataContract = new HexBinaryDataContract(); else if (DictionaryGlobals.gYearMonthLocalName.Value == name) dataContract = new GYearMonthDataContract(); else if (DictionaryGlobals.gYearLocalName.Value == name) dataContract = new GYearDataContract(); else if (DictionaryGlobals.gMonthDayLocalName.Value == name) dataContract = new GMonthDayDataContract(); else if (DictionaryGlobals.gDayLocalName.Value == name) dataContract = new GDayDataContract(); else if (DictionaryGlobals.gMonthLocalName.Value == name) dataContract = new GMonthDataContract(); else if (DictionaryGlobals.normalizedStringLocalName.Value == name) dataContract = new NormalizedStringDataContract(); else if (DictionaryGlobals.tokenLocalName.Value == name) dataContract = new TokenDataContract(); else if (DictionaryGlobals.languageLocalName.Value == name) dataContract = new LanguageDataContract(); else if (DictionaryGlobals.NameLocalName.Value == name) dataContract = new NameDataContract(); else if (DictionaryGlobals.NCNameLocalName.Value == name) dataContract = new NCNameDataContract(); else if (DictionaryGlobals.XSDIDLocalName.Value == name) dataContract = new IDDataContract(); else if (DictionaryGlobals.IDREFLocalName.Value == name) dataContract = new IDREFDataContract(); else if (DictionaryGlobals.IDREFSLocalName.Value == name) dataContract = new IDREFSDataContract(); else if (DictionaryGlobals.ENTITYLocalName.Value == name) dataContract = new ENTITYDataContract(); else if (DictionaryGlobals.ENTITIESLocalName.Value == name) dataContract = new ENTITIESDataContract(); else if (DictionaryGlobals.NMTOKENLocalName.Value == name) dataContract = new NMTOKENDataContract(); else if (DictionaryGlobals.NMTOKENSLocalName.Value == name) dataContract = new NMTOKENDataContract(); else if (DictionaryGlobals.ByteArrayLocalName.Value == name) dataContract = new ByteArrayDataContract(); else if (DictionaryGlobals.ObjectLocalName.Value == name) dataContract = new ObjectDataContract(); else if (DictionaryGlobals.TimeSpanLocalName.Value == name) dataContract = new XsDurationDataContract(); else if (DictionaryGlobals.UriLocalName.Value == name) dataContract = new UriDataContract(); else if (DictionaryGlobals.QNameLocalName.Value == name) dataContract = new QNameDataContract(); } else if (ns == DictionaryGlobals.SerializationNamespace.Value) { if (DictionaryGlobals.TimeSpanLocalName.Value == name) dataContract = new TimeSpanDataContract(); else if (DictionaryGlobals.GuidLocalName.Value == name) dataContract = new GuidDataContract(); else if (DictionaryGlobals.CharLocalName.Value == name) dataContract = new CharDataContract(); else if ("ArrayOfanyType" == name) dataContract = new CollectionDataContract(typeof(Array)); } else if (ns == DictionaryGlobals.AsmxTypesNamespace.Value) { if (DictionaryGlobals.CharLocalName.Value == name) dataContract = new AsmxCharDataContract(); else if (DictionaryGlobals.GuidLocalName.Value == name) dataContract = new AsmxGuidDataContract(); } else if (ns == Globals.DataContractXmlNamespace) { if (name == "XmlElement") dataContract = new XmlDataContract(typeof(XmlElement)); else if (name == "ArrayOfXmlNode") dataContract = new XmlDataContract(typeof(XmlNode[])); } return dataContract != null; } internal static string GetNamespace(string key) { lock (s_namespacesLock) { if (s_namespaces == null) s_namespaces = new Dictionary<string, string>(); string? value; if (s_namespaces.TryGetValue(key, out value)) return value; try { s_namespaces.Add(key, key); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } return key; } } internal static XmlDictionaryString GetClrTypeString(string key) { lock (s_clrTypeStringsLock) { if (s_clrTypeStrings == null) { s_clrTypeStringsDictionary = new XmlDictionary(); s_clrTypeStrings = new Dictionary<string, XmlDictionaryString>(); try { s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName!, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName)); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } XmlDictionaryString? value; if (s_clrTypeStrings.TryGetValue(key, out value)) return value; value = s_clrTypeStringsDictionary!.Add(key); try { s_clrTypeStrings.Add(key, value); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } return value; } } [DoesNotReturn] internal static void ThrowInvalidDataContractException(string? message, Type? type) { if (type != null) { lock (s_cacheLock) { s_typeHandleRef.Value = GetDataContractAdapterTypeHandle(type.TypeHandle); try { s_typeToIDCache.Remove(s_typeHandleRef); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message)); } internal DataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type) { _underlyingType = type; SetTypeForInitialization(type); _isValueType = type.IsValueType; } [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] internal Type UnderlyingType { get { return _underlyingType; } set { _underlyingType = value; } } internal Type OriginalUnderlyingType { get { if (_originalUnderlyingType == null) { _originalUnderlyingType = GetDataContractOriginalType(this._underlyingType); } return _originalUnderlyingType; } set { _originalUnderlyingType = value; } } internal virtual bool IsBuiltInDataContract { get { return false; } } internal Type TypeForInitialization { get { return _typeForInitialization; } } [MemberNotNull(nameof(_typeForInitialization))] private void SetTypeForInitialization(Type classType) { //if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false)) { _typeForInitialization = classType; } } internal bool IsReference { get { return _isReference; } set { _isReference = value; } } internal bool IsValueType { get { return _isValueType; } set { _isValueType = value; } } internal XmlQualifiedName StableName { get { return _stableName; } set { _stableName = value; } } internal virtual DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return null; } set { /* do nothing */ } } internal virtual bool IsISerializable { get { return false; } set { ThrowInvalidDataContractException(SR.RequiresClassDataContractToSetIsISerializable); } } internal XmlDictionaryString Name { get { return _name; } set { _name = value; } } public XmlDictionaryString Namespace { get { return _ns; } set { _ns = value; } } internal virtual bool HasRoot { get { return true; } set { } } internal virtual XmlDictionaryString? TopLevelElementName { get { return _name; } set { Debug.Assert(value != null); _name = value; } } internal virtual XmlDictionaryString? TopLevelElementNamespace { get { return _ns; } set { Debug.Assert(value != null); _ns = value; } } internal virtual bool CanContainReferences { get { return true; } } internal virtual bool IsPrimitive { get { return false; } } internal MethodInfo? ParseMethod { get { if (!_parseMethodSet) { MethodInfo? method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) }); if (method != null && method.ReturnType == UnderlyingType) { _parseMethod = method; } _parseMethodSet = true; } return _parseMethod; } } internal void SetDataContractName(XmlQualifiedName stableName) { XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(stableName.Name); this.Namespace = dictionary.Add(stableName.Namespace); this.StableName = stableName; } internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString ns) { this.Name = name; this.Namespace = ns; this.StableName = CreateQualifiedName(name.Value, ns.Value); } [DoesNotReturn] internal void ThrowInvalidDataContractException(string message) { ThrowInvalidDataContractException(message, UnderlyingType); } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsTypeSerializable(Type type) { return IsTypeSerializable(type, new HashSet<Type>()); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsTypeSerializable(Type type, HashSet<Type> previousCollectionTypes) { Type? itemType; if (type.IsSerializable || type.IsEnum || type.IsDefined(Globals.TypeOfDataContractAttribute, false) || type.IsInterface || type.IsPointer || //Special casing DBNull as its considered a Primitive but is no longer Serializable type == Globals.TypeOfDBNull || Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return true; } if (CollectionDataContract.IsCollection(type, out itemType)) { ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes); if (IsTypeSerializable(itemType, previousCollectionTypes)) { return true; } } return DataContract.GetBuiltInDataContract(type) != null || ClassDataContract.IsNonAttributedTypeValidForSerialization(type); } private static void ValidatePreviousCollectionTypes(Type collectionType, Type itemType, HashSet<Type> previousCollectionTypes) { previousCollectionTypes.Add(collectionType); while (itemType.IsArray) { itemType = itemType.GetElementType()!; } if (previousCollectionTypes.Contains(itemType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.RecursiveCollectionType, GetClrTypeFullName(itemType)))); } } internal static Type UnwrapRedundantNullableType(Type type) { Type nullableType = type; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullableType = type; type = type.GetGenericArguments()[0]; } return nullableType; } internal static Type UnwrapNullableType(Type type) { while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) type = type.GetGenericArguments()[0]; return type; } private static bool IsAlpha(char ch) { return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'); } private static bool IsDigit(char ch) { return (ch >= '0' && ch <= '9'); } private static bool IsAsciiLocalName(string localName) { if (localName.Length == 0) return false; if (!IsAlpha(localName[0])) return false; for (int i = 1; i < localName.Length; i++) { char ch = localName[i]; if (!IsAlpha(ch) && !IsDigit(ch)) return false; } return true; } internal static string EncodeLocalName(string localName) { if (IsAsciiLocalName(localName)) return localName; if (IsValidNCName(localName)) return localName; return XmlConvert.EncodeLocalName(localName); } internal static bool IsValidNCName(string name) { try { XmlConvert.VerifyNCName(name); return true; } catch (XmlException) { return false; } catch (Exception) { return false; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetStableName(Type type) { return GetStableName(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract) { type = UnwrapRedundantNullableType(type); XmlQualifiedName? stableName; if (TryGetBuiltInXmlAndArrayTypeStableName(type, out stableName)) { hasDataContract = false; } else { DataContractAttribute? dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { stableName = GetDCTypeStableName(type, dataContractAttribute); hasDataContract = true; } else { stableName = GetNonDCTypeStableName(type); hasDataContract = false; } } return stableName; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) { string? name, ns; if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; if (name == null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); name = DataContract.EncodeLocalName(name); } else name = GetDefaultStableLocalName(type); if (dataContractAttribute.IsNamespaceSetExplicitly) { ns = dataContractAttribute.Namespace; if (ns == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } else ns = GetDefaultDataContractNamespace(type); return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetNonDCTypeStableName(Type type) { string? name, ns; Type? itemType; if (CollectionDataContract.IsCollection(type, out itemType)) return GetCollectionStableName(type, itemType, out _); name = GetDefaultStableLocalName(type); // ensures that ContractNamespaceAttribute is honored when used with non-attributed types if (ClassDataContract.IsNonAttributedTypeValidForSerialization(type)) { ns = GetDefaultDataContractNamespace(type); } else { ns = GetDefaultStableNamespace(type); } return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWhen(true)] out XmlQualifiedName? stableName) { stableName = null; DataContract? builtInContract = GetBuiltInDataContract(type); if (builtInContract != null) { stableName = builtInContract.StableName; } else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { XmlQualifiedName xmlTypeStableName; SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out _, out _); stableName = xmlTypeStableName; } else if (type.IsArray) { stableName = GetCollectionStableName(type, type.GetElementType()!, out _); } return stableName != null; } internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataContractAttribute? dataContractAttribute) { dataContractAttribute = null; object[] dataContractAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, false).ToArray(); if (dataContractAttributes != null && dataContractAttributes.Length > 0) { #if DEBUG if (dataContractAttributes.Length > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TooManyDataContracts, DataContract.GetClrTypeFullName(type)))); #endif dataContractAttribute = (DataContractAttribute)dataContractAttributes[0]; } return dataContractAttribute != null; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute? collectionContractAttribute) { string? name, ns; object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false).ToArray(); if (collectionContractAttributes != null && collectionContractAttributes.Length > 0) { #if DEBUG if (collectionContractAttributes.Length > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TooManyCollectionContracts, DataContract.GetClrTypeFullName(type)))); #endif collectionContractAttribute = (CollectionDataContractAttribute)collectionContractAttributes[0]; if (collectionContractAttribute.IsNameSetExplicitly) { name = collectionContractAttribute.Name; if (name == null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); name = DataContract.EncodeLocalName(name); } else name = GetDefaultStableLocalName(type); if (collectionContractAttribute.IsNamespaceSetExplicitly) { ns = collectionContractAttribute.Namespace; if (ns == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } else ns = GetDefaultDataContractNamespace(type); } else { collectionContractAttribute = null; string arrayOfPrefix = Globals.ArrayPrefix + GetArrayPrefix(ref itemType); XmlQualifiedName elementStableName = GetStableName(itemType); name = arrayOfPrefix + elementStableName.Name; ns = GetCollectionNamespace(elementStableName.Namespace); } return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string GetArrayPrefix(ref Type itemType) { string arrayOfPrefix = string.Empty; while (itemType.IsArray) { if (DataContract.GetBuiltInDataContract(itemType) != null) break; arrayOfPrefix += Globals.ArrayPrefix; itemType = itemType.GetElementType()!; } return arrayOfPrefix; } internal static string GetCollectionNamespace(string elementNs) { return IsBuiltInNamespace(elementNs) ? Globals.CollectionsNamespace : elementNs; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetDefaultStableName(Type type) { return CreateQualifiedName(GetDefaultStableLocalName(type), GetDefaultStableNamespace(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string GetDefaultStableLocalName(Type type) { if (type.IsGenericParameter) return "{" + type.GenericParameterPosition + "}"; string typeName; string? arrayPrefix = null; if (type.IsArray) arrayPrefix = GetArrayPrefix(ref type); if (type.DeclaringType == null) typeName = type.Name; else { int nsLen = (type.Namespace == null) ? 0 : type.Namespace.Length; if (nsLen > 0) nsLen++; //include the . following namespace typeName = DataContract.GetClrTypeFullName(type).Substring(nsLen).Replace('+', '.'); } if (arrayPrefix != null) typeName = arrayPrefix + typeName; if (type.IsGenericType) { StringBuilder localName = new StringBuilder(); StringBuilder namespaces = new StringBuilder(); bool parametersFromBuiltInNamespaces = true; int iParam = typeName.IndexOf('['); if (iParam >= 0) typeName = typeName.Substring(0, iParam); IList<int> nestedParamCounts = GetDataContractNameForGenericName(typeName, localName); bool isTypeOpenGeneric = type.IsGenericTypeDefinition; Type[] genParams = type.GetGenericArguments(); for (int i = 0; i < genParams.Length; i++) { Type genParam = genParams[i]; if (isTypeOpenGeneric) localName.Append('{').Append(i).Append('}'); else { XmlQualifiedName qname = DataContract.GetStableName(genParam); localName.Append(qname.Name); namespaces.Append(' ').Append(qname.Namespace); if (parametersFromBuiltInNamespaces) parametersFromBuiltInNamespaces = IsBuiltInNamespace(qname.Namespace); } } if (isTypeOpenGeneric) localName.Append("{#}"); else if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces) { foreach (int count in nestedParamCounts) namespaces.Insert(0, count.ToString(CultureInfo.InvariantCulture)).Insert(0, " "); localName.Append(GetNamespacesDigest(namespaces.ToString())); } typeName = localName.ToString(); } return DataContract.EncodeLocalName(typeName); } private static string GetDefaultDataContractNamespace(Type type) { string? clrNs = type.Namespace; if (clrNs == null) clrNs = string.Empty; string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) ns = GetDefaultStableNamespace(type); else CheckExplicitDataContractNamespaceUri(ns, type); return ns; } internal static List<int> GetDataContractNameForGenericName(string typeName, StringBuilder? localName) { List<int> nestedParamCounts = new List<int>(); for (int startIndex = 0, endIndex; ;) { endIndex = typeName.IndexOf('`', startIndex); if (endIndex < 0) { if (localName != null) localName.Append(typeName.AsSpan(startIndex)); nestedParamCounts.Add(0); break; } if (localName != null) { string tempLocalName = typeName.Substring(startIndex, endIndex - startIndex); localName.Append((tempLocalName.Equals("KeyValuePairAdapter") ? "KeyValuePair" : tempLocalName)); } while ((startIndex = typeName.IndexOf('.', startIndex + 1, endIndex - startIndex - 1)) >= 0) nestedParamCounts.Add(0); startIndex = typeName.IndexOf('.', endIndex); if (startIndex < 0) { nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1), provider: CultureInfo.InvariantCulture)); break; } else nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1, startIndex - endIndex - 1), provider: CultureInfo.InvariantCulture)); } if (localName != null) localName.Append("Of"); return nestedParamCounts; } internal static bool IsBuiltInNamespace(string ns) { return (ns == Globals.SchemaNamespace || ns == Globals.SerializationNamespace); } internal static string GetDefaultStableNamespace(Type type) { if (type.IsGenericParameter) return "{ns}"; return GetDefaultStableNamespace(type.Namespace); } internal static XmlQualifiedName CreateQualifiedName(string localName, string ns) { return new XmlQualifiedName(localName, GetNamespace(ns)); } internal static string GetDefaultStableNamespace(string? clrNs) { if (clrNs == null) clrNs = string.Empty; return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static void GetDefaultStableName(string fullTypeName, out string localName, out string ns) { CodeTypeReference typeReference = new CodeTypeReference(fullTypeName); GetDefaultStableName(typeReference, out localName, out ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns) { string fullTypeName = typeReference.BaseType; DataContract? dataContract = GetBuiltInDataContract(fullTypeName); if (dataContract != null) { localName = dataContract.StableName.Name; ns = dataContract.StableName.Namespace; return; } GetClrNameAndNamespace(fullTypeName, out localName, out ns); if (typeReference.TypeArguments.Count > 0) { StringBuilder localNameBuilder = new StringBuilder(); StringBuilder argNamespacesBuilder = new StringBuilder(); bool parametersFromBuiltInNamespaces = true; List<int> nestedParamCounts = GetDataContractNameForGenericName(localName, localNameBuilder); foreach (CodeTypeReference typeArg in typeReference.TypeArguments) { string typeArgName, typeArgNs; GetDefaultStableName(typeArg, out typeArgName, out typeArgNs); localNameBuilder.Append(typeArgName); argNamespacesBuilder.Append(' ').Append(typeArgNs); if (parametersFromBuiltInNamespaces) { parametersFromBuiltInNamespaces = IsBuiltInNamespace(typeArgNs); } } if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces) { foreach (int count in nestedParamCounts) { argNamespacesBuilder.Insert(0, count).Insert(0, ' '); } localNameBuilder.Append(GetNamespacesDigest(argNamespacesBuilder.ToString())); } localName = localNameBuilder.ToString(); } localName = DataContract.EncodeLocalName(localName); ns = GetDefaultStableNamespace(ns); } private static void CheckExplicitDataContractNamespaceUri(string dataContractNs, Type type) { if (dataContractNs.Length > 0) { string trimmedNs = dataContractNs.Trim(); // Code similar to XmlConvert.ToUri (string.Empty is a valid uri but not " ") if (trimmedNs.Length == 0 || trimmedNs.IndexOf("##", StringComparison.Ordinal) != -1) ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type); dataContractNs = trimmedNs; } Uri? uri; if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri)) { if (uri.ToString() == Globals.SerializationNamespace) ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceReserved, Globals.SerializationNamespace), type); } else ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type); } internal static string GetClrTypeFullName(Type type) { return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName!; } internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns) { int nsEnd = fullTypeName.LastIndexOf('.'); if (nsEnd < 0) { ns = string.Empty; localName = fullTypeName.Replace('+', '.'); } else { ns = fullTypeName.Substring(0, nsEnd); localName = fullTypeName.Substring(nsEnd + 1).Replace('+', '.'); } int iParam = localName.IndexOf('['); if (iParam >= 0) localName = localName.Substring(0, iParam); } internal static string GetDataContractNamespaceFromUri(string uriString) { return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString; } private static string? GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes) { string? dataContractNs = null; for (int i = 0; i < nsAttributes.Length; i++) { ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i]; string? clrNsInAttribute = nsAttribute.ClrNamespace; if (clrNsInAttribute == null) clrNsInAttribute = string.Empty; if (clrNsInAttribute == clrNs) { if (nsAttribute.ContractNamespace == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGlobalDataContractNamespace, clrNs))); if (dataContractNs != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.DataContractNamespaceAlreadySet, dataContractNs, nsAttribute.ContractNamespace, clrNs))); dataContractNs = nsAttribute.ContractNamespace; } } return dataContractNs; } private static string GetNamespacesDigest(string namespaces) { byte[] namespaceBytes = Encoding.UTF8.GetBytes(namespaces); byte[] digestBytes = ComputeHash(namespaceBytes); char[] digestChars = new char[24]; const int digestLen = 6; int digestCharsLen = Convert.ToBase64CharArray(digestBytes, 0, digestLen, digestChars, 0); StringBuilder digest = new StringBuilder(); for (int i = 0; i < digestCharsLen; i++) { char ch = digestChars[i]; switch (ch) { case '=': break; case '/': digest.Append("_S"); break; case '+': digest.Append("_P"); break; default: digest.Append(ch); break; } } return digest.ToString(); } // An incomplete implementation of MD5 necessary for back-compat. // "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" // THIS HASH MAY ONLY BE USED FOR BACKWARDS-COMPATIBLE NAME GENERATION. DO NOT USE FOR SECURITY PURPOSES. private static byte[] ComputeHash(byte[] namespaces) { int[] shifts = new int[] { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; uint[] sines = new uint[] { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; int blocks = (namespaces.Length + 8) / 64 + 1; uint aa = 0x67452301; uint bb = 0xefcdab89; uint cc = 0x98badcfe; uint dd = 0x10325476; for (int i = 0; i < blocks; i++) { byte[] block = namespaces; int offset = i * 64; if (offset + 64 > namespaces.Length) { block = new byte[64]; for (int j = offset; j < namespaces.Length; j++) { block[j - offset] = namespaces[j]; } if (offset <= namespaces.Length) { block[namespaces.Length - offset] = 0x80; } if (i == blocks - 1) { unchecked { block[56] = (byte)(namespaces.Length << 3); block[57] = (byte)(namespaces.Length >> 5); block[58] = (byte)(namespaces.Length >> 13); block[59] = (byte)(namespaces.Length >> 21); } } offset = 0; } uint a = aa; uint b = bb; uint c = cc; uint d = dd; uint f; int g; for (int j = 0; j < 64; j++) { if (j < 16) { f = b & c | ~b & d; g = j; } else if (j < 32) { f = b & d | c & ~d; g = 5 * j + 1; } else if (j < 48) { f = b ^ c ^ d; g = 3 * j + 5; } else { f = c ^ (b | ~d); g = 7 * j; } g = (g & 0x0f) * 4 + offset; uint hold = d; d = c; c = b; b = unchecked(a + f + sines[j] + BinaryPrimitives.ReadUInt32LittleEndian(block.AsSpan(g))); b = b << shifts[j & 3 | j >> 2 & ~3] | b >> 32 - shifts[j & 3 | j >> 2 & ~3]; b = unchecked(b + c); a = hold; } unchecked { aa += a; bb += b; if (i < blocks - 1) { cc += c; dd += d; } } } unchecked { return new byte[] { (byte)aa, (byte)(aa >> 8), (byte)(aa >> 16), (byte)(aa >> 24), (byte)bb, (byte)(bb >> 8) }; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string ExpandGenericParameters(string format, Type type) { GenericNameProvider genericNameProviderForType = new GenericNameProvider(type); return ExpandGenericParameters(format, genericNameProviderForType); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider) { string? digest = null; StringBuilder typeName = new StringBuilder(); IList<int> nestedParameterCounts = genericNameProvider.GetNestedParameterCounts(); for (int i = 0; i < format.Length; i++) { char ch = format[i]; if (ch == '{') { i++; int start = i; for (; i < format.Length; i++) if (format[i] == '}') break; if (i == format.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GenericNameBraceMismatch, format, genericNameProvider.GetGenericTypeName()))); if (format[start] == '#' && i == (start + 1)) { if (nestedParameterCounts.Count > 1 || !genericNameProvider.ParametersFromBuiltInNamespaces) { if (digest == null) { StringBuilder namespaces = new StringBuilder(genericNameProvider.GetNamespaces()); foreach (int count in nestedParameterCounts) namespaces.Insert(0, count.ToString(CultureInfo.InvariantCulture)).Insert(0, " "); digest = GetNamespacesDigest(namespaces.ToString()); } typeName.Append(digest); } } else { int paramIndex; if (!int.TryParse(format.AsSpan(start, i - start), out paramIndex) || paramIndex < 0 || paramIndex >= genericNameProvider.GetParameterCount()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GenericParameterNotValid, format.Substring(start, i - start), genericNameProvider.GetGenericTypeName(), genericNameProvider.GetParameterCount() - 1))); typeName.Append(genericNameProvider.GetParameterName(paramIndex)); } } else typeName.Append(ch); } return typeName.ToString(); } internal static bool IsTypeNullable(Type type) { return !type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContractDictionary? ImportKnownTypeAttributes(Type type) { DataContractDictionary? knownDataContracts = null; Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>(); ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts); return knownDataContracts; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void ImportKnownTypeAttributes(Type? type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary? knownDataContracts) { while (type != null && DataContract.IsTypeSerializable(type)) { if (typesChecked.ContainsKey(type)) return; typesChecked.Add(type, type); object[] knownTypeAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, false).ToArray(); if (knownTypeAttributes != null) { KnownTypeAttribute kt; bool useMethod = false, useType = false; for (int i = 0; i < knownTypeAttributes.Length; ++i) { kt = (KnownTypeAttribute)knownTypeAttributes[i]; if (kt.Type != null) { if (useMethod) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type); } CheckAndAdd(kt.Type, typesChecked, ref knownDataContracts); useType = true; } else { if (useMethod || useType) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type); } string? methodName = kt.MethodName; if (methodName == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type); } if (methodName.Length == 0) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type); MethodInfo? method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Type.EmptyTypes); if (method == null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type); if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType)) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type); object? types = method.Invoke(null, Array.Empty<object>()); if (types == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type); } foreach (Type ty in (IEnumerable<Type>)types) { if (ty == null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeValidMethodTypes, DataContract.GetClrTypeFullName(type)), type); CheckAndAdd(ty, typesChecked, ref knownDataContracts); } useMethod = true; } } } //For Json we need to add KeyValuePair<K,T> to KnownTypes if the UnderLyingType is a Dictionary<K,T> try { CollectionDataContract? collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract; if (collectionDataContract != null && collectionDataContract.IsDictionary && collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments())); if (knownDataContracts == null) { knownDataContracts = new DataContractDictionary(); } knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } } catch (InvalidDataContractException) { //Ignore any InvalidDataContractException as this phase is a workaround for lack of ISerializable. //InvalidDataContractException may happen as we walk the type hierarchy back to Object and encounter //types that may not be valid DC. This step is purely for KeyValuePair and shouldn't fail the (de)serialization. //Any IDCE in this case fails the serialization/deserialization process which is not the optimal experience. } type = type.BaseType; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, [NotNullIfNotNull("nameToDataContractTable")] ref DataContractDictionary? nameToDataContractTable) { type = DataContract.UnwrapNullableType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContract? alreadyExistingContract; if (nameToDataContractTable == null) { nameToDataContractTable = new DataContractDictionary(); } else if (nameToDataContractTable.TryGetValue(dataContract.StableName, out alreadyExistingContract)) { // Don't throw duplicate if its a KeyValuePair<K,T> as it could have been added by Dictionary<K,T> if (DataContractCriticalHelper.GetDataContractAdapterType(alreadyExistingContract.UnderlyingType) != DataContractCriticalHelper.GetDataContractAdapterType(type) && !(alreadyExistingContract is ClassDataContract && ((ClassDataContract)alreadyExistingContract).IsKeyValuePairAdapter)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.DupContractInKnownTypes, type, alreadyExistingContract.UnderlyingType, dataContract.StableName.Namespace, dataContract.StableName.Name))); return; } nameToDataContractTable.Add(dataContract.StableName, dataContract); ImportKnownTypeAttributes(type, typesChecked, ref nameToDataContractTable); } /// <SecurityNote> /// Review - checks type visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool IsTypeVisible(Type t) { if (!t.IsVisible && !IsTypeVisibleInSerializationModule(t)) return false; foreach (Type genericType in t.GetGenericArguments()) { if (!genericType.IsGenericParameter && !IsTypeVisible(genericType)) return false; } return true; } /// <SecurityNote> /// Review - checks constructor visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor) { return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor); } /// <SecurityNote> /// Review - checks method visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool MethodRequiresMemberAccess(MethodInfo? method) { return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method); } /// <SecurityNote> /// Review - checks field visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool FieldRequiresMemberAccess(FieldInfo? field) { return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field); } /// <SecurityNote> /// Review - checks type visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private static bool IsTypeVisibleInSerializationModule(Type type) { return (type.Module.Equals(typeof(DataContract).Module) || IsAssemblyFriendOfSerialization(type.Assembly)) && !type.IsNestedPrivate; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private static bool IsMemberVisibleInSerializationModule(MemberInfo member) { if (!IsTypeVisibleInSerializationModule(member.DeclaringType!)) return false; if (member is MethodInfo) { MethodInfo method = (MethodInfo)member; return (method.IsAssembly || method.IsFamilyOrAssembly); } else if (member is FieldInfo) { FieldInfo field = (FieldInfo)member; return (field.IsAssembly || field.IsFamilyOrAssembly) && IsTypeVisible(field.FieldType); } else if (member is ConstructorInfo) { ConstructorInfo constructor = (ConstructorInfo)member; return (constructor.IsAssembly || constructor.IsFamilyOrAssembly); } return false; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool IsAssemblyFriendOfSerialization(Assembly assembly) { InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute)); foreach (InternalsVisibleToAttribute internalsVisibleAttribute in internalsVisibleAttributes) { string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName; if (internalsVisibleAttributeAssemblyName.Trim().Equals("System.Runtime.Serialization") || Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.FullSRSInternalsVisiblePattern)) { return true; } } return false; } internal static string SanitizeTypeName(string typeName) { return typeName.Replace('.', '_'); } } internal interface IGenericNameProvider { int GetParameterCount(); IList<int> GetNestedParameterCounts(); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] string GetParameterName(int paramIndex); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] string GetNamespaces(); string GetGenericTypeName(); bool ParametersFromBuiltInNamespaces { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get; } } internal sealed class GenericNameProvider : IGenericNameProvider { private readonly string _genericTypeName; private readonly object[] _genericParams; //Type or DataContract private readonly IList<int> _nestedParamCounts; internal GenericNameProvider(Type type) : this(DataContract.GetClrTypeFullName(type.GetGenericTypeDefinition()), type.GetGenericArguments()) { } internal GenericNameProvider(string genericTypeName, object[] genericParams) { _genericTypeName = genericTypeName; _genericParams = new object[genericParams.Length]; genericParams.CopyTo(_genericParams, 0); string name; DataContract.GetClrNameAndNamespace(genericTypeName, out name, out _); _nestedParamCounts = DataContract.GetDataContractNameForGenericName(name, null); } public int GetParameterCount() { return _genericParams.Length; } public IList<int> GetNestedParameterCounts() { return _nestedParamCounts; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public string GetParameterName(int paramIndex) { return GetStableName(paramIndex).Name; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public string GetNamespaces() { StringBuilder namespaces = new StringBuilder(); for (int j = 0; j < GetParameterCount(); j++) namespaces.Append(' ').Append(GetStableName(j).Namespace); return namespaces.ToString(); } public string GetGenericTypeName() { return _genericTypeName; } public bool ParametersFromBuiltInNamespaces { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { bool parametersFromBuiltInNamespaces = true; for (int j = 0; j < GetParameterCount(); j++) { if (parametersFromBuiltInNamespaces) parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(GetStableName(j).Namespace); else break; } return parametersFromBuiltInNamespaces; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlQualifiedName GetStableName(int i) { object o = _genericParams[i]; XmlQualifiedName? qname = o as XmlQualifiedName; if (qname == null) { Type? paramType = o as Type; if (paramType != null) _genericParams[i] = qname = DataContract.GetStableName(paramType); else _genericParams[i] = qname = ((DataContract)o).StableName; } return qname; } } internal sealed class TypeHandleRefEqualityComparer : IEqualityComparer<TypeHandleRef> { public bool Equals(TypeHandleRef? x, TypeHandleRef? y) { return x!.Value.Equals(y!.Value); } public int GetHashCode(TypeHandleRef obj) { return obj.Value.GetHashCode(); } } internal sealed class TypeHandleRef { private RuntimeTypeHandle _value; public TypeHandleRef() { } public TypeHandleRef(RuntimeTypeHandle value) { _value = value; } public RuntimeTypeHandle Value { get { return _value; } set { _value = value; } } } internal sealed class IntRef { private readonly int _value; public IntRef(int value) { _value = value; } public int Value { get { return _value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.Serialization { using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Text.RegularExpressions; using System.Runtime.CompilerServices; using System.Linq; using Xml.Schema; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; internal abstract class DataContract { private XmlDictionaryString _name; private XmlDictionaryString _ns; // this the global dictionary for data contracts introduced for multi-file. private static readonly Dictionary<Type, DataContract> s_dataContracts = new Dictionary<Type, DataContract>(); internal const string SerializerTrimmerWarning = "Data Contract Serialization and Deserialization might require types that cannot be statically analyzed. Make sure all of the " + "required types are preserved."; public static Dictionary<Type, DataContract> GetDataContracts() { return s_dataContracts; } private readonly DataContractCriticalHelper _helper; internal DataContract(DataContractCriticalHelper helper) { _helper = helper; _name = helper.Name; _ns = helper.Namespace; } private static DataContract? GetGeneratedDataContract(Type type) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method DataContract? result; return s_dataContracts.TryGetValue(type, out result) ? result : null; } internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract? dataContract) { dataContract = GetGeneratedDataContract(type); return dataContract != null; } internal static DataContract? GetDataContractFromGeneratedAssembly(Type? type) { return null; } internal MethodInfo? ParseMethod { get { return _helper.ParseMethod; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(Type type) { return GetDataContract(type.TypeHandle, type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { return GetDataContract(typeHandle, type, SerializationMode.SharedContract); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { int id = GetId(typeHandle); DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); return dataContract.GetValidContract(mode); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle, SerializationMode mode) { DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); return dataContract.GetValidContract(mode); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); dataContract = dataContract.GetValidContract(mode); if (dataContract is ClassDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)), SR.Format(SR.NoSetMethodForProperty, string.Empty, string.Empty)))); } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); } internal static DataContract GetDataContractForInitialization(int id) { return DataContractCriticalHelper.GetDataContractForInitialization(id); } internal static int GetIdForInitialization(ClassDataContract classContract) { return DataContractCriticalHelper.GetIdForInitialization(classContract); } internal static int GetId(RuntimeTypeHandle typeHandle) { return DataContractCriticalHelper.GetId(typeHandle); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(Type type) { return DataContractCriticalHelper.GetBuiltInDataContract(type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string name, string ns) { return DataContractCriticalHelper.GetBuiltInDataContract(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string typeName) { return DataContractCriticalHelper.GetBuiltInDataContract(typeName); } internal static string GetNamespace(string key) { return DataContractCriticalHelper.GetNamespace(key); } internal static XmlDictionaryString GetClrTypeString(string key) { return DataContractCriticalHelper.GetClrTypeString(key); } [DoesNotReturn] internal static void ThrowInvalidDataContractException(string? message, Type? type) { DataContractCriticalHelper.ThrowInvalidDataContractException(message, type); } protected DataContractCriticalHelper Helper { get { return _helper; } } [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] public Type UnderlyingType { get { return _helper.UnderlyingType; } set { _helper.UnderlyingType = value; } } public Type OriginalUnderlyingType { get { return _helper.OriginalUnderlyingType; } set { _helper.OriginalUnderlyingType = value; } } public virtual bool IsBuiltInDataContract { get { return _helper.IsBuiltInDataContract; } set { } } internal Type TypeForInitialization { get { return _helper.TypeForInitialization; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } public virtual object ReadXmlElement(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } public bool IsValueType { get { return _helper.IsValueType; } set { _helper.IsValueType = value; } } public bool IsReference { get { return _helper.IsReference; } set { _helper.IsReference = value; } } public XmlQualifiedName StableName { get { return _helper.StableName; } set { _helper.StableName = value; } } public virtual DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } public virtual bool IsISerializable { get { return _helper.IsISerializable; } set { _helper.IsISerializable = value; } } public XmlDictionaryString Name { get { return _name; } set { _name = value; } } public virtual XmlDictionaryString Namespace { get { return _ns; } set { _ns = value; } } public virtual bool HasRoot { get { return true; } set { } } public virtual XmlDictionaryString? TopLevelElementName { get { return _helper.TopLevelElementName; } set { _helper.TopLevelElementName = value; } } public virtual XmlDictionaryString? TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } set { _helper.TopLevelElementNamespace = value; } } internal virtual bool CanContainReferences { get { return true; } } internal virtual bool IsPrimitive { get { return false; } } internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive) writer.WriteStartElement(Globals.SerPrefix, name, ns); else writer.WriteStartElement(name, ns); } internal virtual DataContract GetValidContract(SerializationMode mode) { return this; } internal virtual DataContract GetValidContract() { return this; } internal virtual bool IsValidContract(SerializationMode mode) { return true; } internal class DataContractCriticalHelper { private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private static DataContract[] s_dataContractCache = new DataContract[32]; private static int s_dataContractID; private static Dictionary<Type, DataContract?>? s_typeToBuiltInContract; private static Dictionary<XmlQualifiedName, DataContract?>? s_nameToBuiltInContract; private static Dictionary<string, string>? s_namespaces; private static Dictionary<string, XmlDictionaryString>? s_clrTypeStrings; private static XmlDictionary? s_clrTypeStringsDictionary; private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly object s_cacheLock = new object(); private static readonly object s_createDataContractLock = new object(); private static readonly object s_initBuiltInContractsLock = new object(); private static readonly object s_namespacesLock = new object(); private static readonly object s_clrTypeStringsLock = new object(); [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] private Type _underlyingType; private Type? _originalUnderlyingType; private bool _isReference; private bool _isValueType; private XmlQualifiedName _stableName = null!; // StableName is always set in concrete ctors set except for the "invalid" CollectionDataContract private XmlDictionaryString _name = null!; // Name is always set in concrete ctors set except for the "invalid" CollectionDataContract private XmlDictionaryString _ns = null!; // Namespace is always set in concrete ctors set except for the "invalid" CollectionDataContract private MethodInfo? _parseMethod; private bool _parseMethodSet; /// <SecurityNote> /// Critical - in deserialization, we initialize an object instance passing this Type to GetUninitializedObject method /// </SecurityNote> private Type _typeForInitialization; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateDataContract(id, typeHandle, type); AssignDataContractToId(dataContract, id); } else { return dataContract.GetValidContract(); } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type); s_dataContractCache[id] = dataContract; } return dataContract; } internal static DataContract GetDataContractForInitialization(int id) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } return dataContract; } internal static int GetIdForInitialization(ClassDataContract classContract) { int id = DataContract.GetId(classContract.TypeForInitialization!.TypeHandle); if (id < s_dataContractCache.Length && ContractMatches(classContract, s_dataContractCache[id])) { return id; } int currentDataContractId = DataContractCriticalHelper.s_dataContractID; for (int i = 0; i < currentDataContractId; i++) { if (ContractMatches(classContract, s_dataContractCache[i])) { return i; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } private static bool ContractMatches(DataContract contract, DataContract cachedContract) { return (cachedContract != null && cachedContract.UnderlyingType == contract.UnderlyingType); } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef? id; typeHandle = GetDataContractAdapterTypeHandle(typeHandle); s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < int.MaxValue / 2) ? value * 2 : int.MaxValue; if (newSize <= value) { DiagnosticUtility.DebugAssert("DataContract cache overflow"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow)); } Array.Resize<DataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract? dataContract = s_dataContractCache[id]; if (dataContract == null) { lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; if (dataContract == null) { if (type == null) type = Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract != null) { AssignDataContractToId(dataContract, id); return dataContract; } dataContract = CreateDataContract(type); } } } return dataContract; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateDataContract(Type type) { type = UnwrapNullableType(type); Type originalType = type; type = GetDataContractAdapterType(type); DataContract? dataContract = GetBuiltInDataContract(type); if (dataContract == null) { if (type.IsArray) dataContract = new CollectionDataContract(type); else if (type.IsEnum) dataContract = new EnumDataContract(type); else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) dataContract = new XmlDataContract(type); else if (Globals.TypeOfScriptObject_IsAssignableFrom(type)) dataContract = Globals.CreateScriptObjectClassDataContract(); else { //if (type.ContainsGenericParameters) // ThrowInvalidDataContractException(SR.Format(SR.TypeMustNotBeOpenGeneric, type), type); if (!CollectionDataContract.TryCreate(type, out dataContract)) { if (!type.IsSerializable && !type.IsDefined(Globals.TypeOfDataContractAttribute, false) && !ClassDataContract.IsNonAttributedTypeValidForSerialization(type) && !ClassDataContract.IsKnownSerializableType(type)) { ThrowInvalidDataContractException(SR.Format(SR.TypeNotSerializable, type), type); } dataContract = new ClassDataContract(type); if (type != originalType) { var originalDataContract = new ClassDataContract(originalType); if (dataContract.StableName != originalDataContract.StableName) { // for non-DC types, type adapters will not have the same stable name (contract name). dataContract.StableName = originalDataContract.StableName; } } } } } return dataContract; } [MethodImpl(MethodImplOptions.NoInlining)] private static void AssignDataContractToId(DataContract dataContract, int id) { lock (s_cacheLock) { s_dataContractCache[id] = dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract? dataContract = null; lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; if (dataContract == null) { if (type == null) type = Type.GetTypeFromHandle(typeHandle)!; type = UnwrapNullableType(type); type = GetDataContractAdapterType(type); if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract)) { ThrowInvalidDataContractException(SR.Format(SR.TypeNotSerializable, type), type); } } } return dataContract; } // This method returns adapter types used at runtime to create DataContract. [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static Type GetDataContractAdapterType(Type type) { // Replace the DataTimeOffset ISerializable type passed in with the internal DateTimeOffsetAdapter DataContract type. // DateTimeOffsetAdapter is used for serialization/deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust and to ensure correct schema import/export scenarios. if (type == Globals.TypeOfDateTimeOffset) { return Globals.TypeOfDateTimeOffsetAdapter; } if (type == Globals.TypeOfMemoryStream) { return Globals.TypeOfMemoryStreamAdapter; } if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePair) { return Globals.TypeOfKeyValuePairAdapter.MakeGenericType(type.GetGenericArguments()); } return type; } // Maps adapted types back to the original type // Any change to this method should be reflected in GetDataContractAdapterType internal static Type GetDataContractOriginalType(Type type) { if (type == Globals.TypeOfDateTimeOffsetAdapter) { return Globals.TypeOfDateTimeOffset; } if (type == Globals.TypeOfMemoryStreamAdapter) { return Globals.TypeOfMemoryStream; } return type; } private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHandle typeHandle) { if (Globals.TypeOfDateTimeOffset.TypeHandle.Equals(typeHandle)) { return Globals.TypeOfDateTimeOffsetAdapter.TypeHandle; } if (Globals.TypeOfMemoryStream.TypeHandle.Equals(typeHandle)) { return Globals.TypeOfMemoryStreamAdapter.TypeHandle; } return typeHandle; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(Type type) { if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type)) type = Globals.TypeOfObject; lock (s_initBuiltInContractsLock) { if (s_typeToBuiltInContract == null) s_typeToBuiltInContract = new Dictionary<Type, DataContract?>(); DataContract? dataContract; if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract)) { TryCreateBuiltInDataContract(type, out dataContract); s_typeToBuiltInContract.Add(type, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string name, string ns) { lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(name, ns); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { TryCreateBuiltInDataContract(name, ns, out dataContract); s_nameToBuiltInContract.Add(qname, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static DataContract? GetBuiltInDataContract(string typeName) { if (!typeName.StartsWith("System.", StringComparison.Ordinal)) return null; lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>(); DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(typeName); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { Type? type = null; string name = typeName.Substring(7); if (name == "Char") type = typeof(char); else if (name == "Boolean") type = typeof(bool); else if (name == "SByte") type = typeof(sbyte); else if (name == "Byte") type = typeof(byte); else if (name == "Int16") type = typeof(short); else if (name == "UInt16") type = typeof(ushort); else if (name == "Int32") type = typeof(int); else if (name == "UInt32") type = typeof(uint); else if (name == "Int64") type = typeof(long); else if (name == "UInt64") type = typeof(ulong); else if (name == "Single") type = typeof(float); else if (name == "Double") type = typeof(double); else if (name == "Decimal") type = typeof(decimal); else if (name == "DateTime") type = typeof(DateTime); else if (name == "String") type = typeof(string); else if (name == "Byte[]") type = typeof(byte[]); else if (name == "Object") type = typeof(object); else if (name == "TimeSpan") type = typeof(TimeSpan); else if (name == "Guid") type = typeof(Guid); else if (name == "Uri") type = typeof(Uri); else if (name == "Xml.XmlQualifiedName") type = typeof(XmlQualifiedName); else if (name == "Enum") type = typeof(Enum); else if (name == "ValueType") type = typeof(ValueType); else if (name == "Array") type = typeof(Array); else if (name == "Xml.XmlElement") type = typeof(XmlElement); else if (name == "Xml.XmlNode[]") type = typeof(XmlNode[]); if (type != null) TryCreateBuiltInDataContract(type, out dataContract); s_nameToBuiltInContract.Add(qname, dataContract); } return dataContract; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static bool TryCreateBuiltInDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX { dataContract = null; return false; } dataContract = null; switch (type.GetTypeCode()) { case TypeCode.Boolean: dataContract = new BooleanDataContract(); break; case TypeCode.Byte: dataContract = new UnsignedByteDataContract(); break; case TypeCode.Char: dataContract = new CharDataContract(); break; case TypeCode.DateTime: dataContract = new DateTimeDataContract(); break; case TypeCode.Decimal: dataContract = new DecimalDataContract(); break; case TypeCode.Double: dataContract = new DoubleDataContract(); break; case TypeCode.Int16: dataContract = new ShortDataContract(); break; case TypeCode.Int32: dataContract = new IntDataContract(); break; case TypeCode.Int64: dataContract = new LongDataContract(); break; case TypeCode.SByte: dataContract = new SignedByteDataContract(); break; case TypeCode.Single: dataContract = new FloatDataContract(); break; case TypeCode.String: dataContract = new StringDataContract(); break; case TypeCode.UInt16: dataContract = new UnsignedShortDataContract(); break; case TypeCode.UInt32: dataContract = new UnsignedIntDataContract(); break; case TypeCode.UInt64: dataContract = new UnsignedLongDataContract(); break; default: if (type == typeof(byte[])) dataContract = new ByteArrayDataContract(); else if (type == typeof(object)) dataContract = new ObjectDataContract(); else if (type == typeof(Uri)) dataContract = new UriDataContract(); else if (type == typeof(XmlQualifiedName)) dataContract = new QNameDataContract(); else if (type == typeof(TimeSpan)) dataContract = new TimeSpanDataContract(); else if (type == typeof(Guid)) dataContract = new GuidDataContract(); else if (type == typeof(Enum) || type == typeof(ValueType)) { dataContract = new SpecialTypeDataContract(type, DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace); } else if (type == typeof(Array)) dataContract = new CollectionDataContract(type); else if (type == typeof(XmlElement) || type == typeof(XmlNode[])) dataContract = new XmlDataContract(type); break; } return dataContract != null; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = null; if (ns == DictionaryGlobals.SchemaNamespace.Value) { if (DictionaryGlobals.BooleanLocalName.Value == name) dataContract = new BooleanDataContract(); else if (DictionaryGlobals.SignedByteLocalName.Value == name) dataContract = new SignedByteDataContract(); else if (DictionaryGlobals.UnsignedByteLocalName.Value == name) dataContract = new UnsignedByteDataContract(); else if (DictionaryGlobals.ShortLocalName.Value == name) dataContract = new ShortDataContract(); else if (DictionaryGlobals.UnsignedShortLocalName.Value == name) dataContract = new UnsignedShortDataContract(); else if (DictionaryGlobals.IntLocalName.Value == name) dataContract = new IntDataContract(); else if (DictionaryGlobals.UnsignedIntLocalName.Value == name) dataContract = new UnsignedIntDataContract(); else if (DictionaryGlobals.LongLocalName.Value == name) dataContract = new LongDataContract(); else if (DictionaryGlobals.integerLocalName.Value == name) dataContract = new IntegerDataContract(); else if (DictionaryGlobals.positiveIntegerLocalName.Value == name) dataContract = new PositiveIntegerDataContract(); else if (DictionaryGlobals.negativeIntegerLocalName.Value == name) dataContract = new NegativeIntegerDataContract(); else if (DictionaryGlobals.nonPositiveIntegerLocalName.Value == name) dataContract = new NonPositiveIntegerDataContract(); else if (DictionaryGlobals.nonNegativeIntegerLocalName.Value == name) dataContract = new NonNegativeIntegerDataContract(); else if (DictionaryGlobals.UnsignedLongLocalName.Value == name) dataContract = new UnsignedLongDataContract(); else if (DictionaryGlobals.FloatLocalName.Value == name) dataContract = new FloatDataContract(); else if (DictionaryGlobals.DoubleLocalName.Value == name) dataContract = new DoubleDataContract(); else if (DictionaryGlobals.DecimalLocalName.Value == name) dataContract = new DecimalDataContract(); else if (DictionaryGlobals.DateTimeLocalName.Value == name) dataContract = new DateTimeDataContract(); else if (DictionaryGlobals.StringLocalName.Value == name) dataContract = new StringDataContract(); else if (DictionaryGlobals.timeLocalName.Value == name) dataContract = new TimeDataContract(); else if (DictionaryGlobals.dateLocalName.Value == name) dataContract = new DateDataContract(); else if (DictionaryGlobals.hexBinaryLocalName.Value == name) dataContract = new HexBinaryDataContract(); else if (DictionaryGlobals.gYearMonthLocalName.Value == name) dataContract = new GYearMonthDataContract(); else if (DictionaryGlobals.gYearLocalName.Value == name) dataContract = new GYearDataContract(); else if (DictionaryGlobals.gMonthDayLocalName.Value == name) dataContract = new GMonthDayDataContract(); else if (DictionaryGlobals.gDayLocalName.Value == name) dataContract = new GDayDataContract(); else if (DictionaryGlobals.gMonthLocalName.Value == name) dataContract = new GMonthDataContract(); else if (DictionaryGlobals.normalizedStringLocalName.Value == name) dataContract = new NormalizedStringDataContract(); else if (DictionaryGlobals.tokenLocalName.Value == name) dataContract = new TokenDataContract(); else if (DictionaryGlobals.languageLocalName.Value == name) dataContract = new LanguageDataContract(); else if (DictionaryGlobals.NameLocalName.Value == name) dataContract = new NameDataContract(); else if (DictionaryGlobals.NCNameLocalName.Value == name) dataContract = new NCNameDataContract(); else if (DictionaryGlobals.XSDIDLocalName.Value == name) dataContract = new IDDataContract(); else if (DictionaryGlobals.IDREFLocalName.Value == name) dataContract = new IDREFDataContract(); else if (DictionaryGlobals.IDREFSLocalName.Value == name) dataContract = new IDREFSDataContract(); else if (DictionaryGlobals.ENTITYLocalName.Value == name) dataContract = new ENTITYDataContract(); else if (DictionaryGlobals.ENTITIESLocalName.Value == name) dataContract = new ENTITIESDataContract(); else if (DictionaryGlobals.NMTOKENLocalName.Value == name) dataContract = new NMTOKENDataContract(); else if (DictionaryGlobals.NMTOKENSLocalName.Value == name) dataContract = new NMTOKENDataContract(); else if (DictionaryGlobals.ByteArrayLocalName.Value == name) dataContract = new ByteArrayDataContract(); else if (DictionaryGlobals.ObjectLocalName.Value == name) dataContract = new ObjectDataContract(); else if (DictionaryGlobals.TimeSpanLocalName.Value == name) dataContract = new XsDurationDataContract(); else if (DictionaryGlobals.UriLocalName.Value == name) dataContract = new UriDataContract(); else if (DictionaryGlobals.QNameLocalName.Value == name) dataContract = new QNameDataContract(); } else if (ns == DictionaryGlobals.SerializationNamespace.Value) { if (DictionaryGlobals.TimeSpanLocalName.Value == name) dataContract = new TimeSpanDataContract(); else if (DictionaryGlobals.GuidLocalName.Value == name) dataContract = new GuidDataContract(); else if (DictionaryGlobals.CharLocalName.Value == name) dataContract = new CharDataContract(); else if ("ArrayOfanyType" == name) dataContract = new CollectionDataContract(typeof(Array)); } else if (ns == DictionaryGlobals.AsmxTypesNamespace.Value) { if (DictionaryGlobals.CharLocalName.Value == name) dataContract = new AsmxCharDataContract(); else if (DictionaryGlobals.GuidLocalName.Value == name) dataContract = new AsmxGuidDataContract(); } else if (ns == Globals.DataContractXmlNamespace) { if (name == "XmlElement") dataContract = new XmlDataContract(typeof(XmlElement)); else if (name == "ArrayOfXmlNode") dataContract = new XmlDataContract(typeof(XmlNode[])); } return dataContract != null; } internal static string GetNamespace(string key) { lock (s_namespacesLock) { if (s_namespaces == null) s_namespaces = new Dictionary<string, string>(); string? value; if (s_namespaces.TryGetValue(key, out value)) return value; try { s_namespaces.Add(key, key); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } return key; } } internal static XmlDictionaryString GetClrTypeString(string key) { lock (s_clrTypeStringsLock) { if (s_clrTypeStrings == null) { s_clrTypeStringsDictionary = new XmlDictionary(); s_clrTypeStrings = new Dictionary<string, XmlDictionaryString>(); try { s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName!, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName)); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } XmlDictionaryString? value; if (s_clrTypeStrings.TryGetValue(key, out value)) return value; value = s_clrTypeStringsDictionary!.Add(key); try { s_clrTypeStrings.Add(key, value); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } return value; } } [DoesNotReturn] internal static void ThrowInvalidDataContractException(string? message, Type? type) { if (type != null) { lock (s_cacheLock) { s_typeHandleRef.Value = GetDataContractAdapterTypeHandle(type.TypeHandle); try { s_typeToIDCache.Remove(s_typeHandleRef); } catch (Exception ex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message)); } internal DataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type) { _underlyingType = type; SetTypeForInitialization(type); _isValueType = type.IsValueType; } [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] internal Type UnderlyingType { get { return _underlyingType; } set { _underlyingType = value; } } internal Type OriginalUnderlyingType { get { if (_originalUnderlyingType == null) { _originalUnderlyingType = GetDataContractOriginalType(this._underlyingType); } return _originalUnderlyingType; } set { _originalUnderlyingType = value; } } internal virtual bool IsBuiltInDataContract { get { return false; } } internal Type TypeForInitialization { get { return _typeForInitialization; } } [MemberNotNull(nameof(_typeForInitialization))] private void SetTypeForInitialization(Type classType) { //if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false)) { _typeForInitialization = classType; } } internal bool IsReference { get { return _isReference; } set { _isReference = value; } } internal bool IsValueType { get { return _isValueType; } set { _isValueType = value; } } internal XmlQualifiedName StableName { get { return _stableName; } set { _stableName = value; } } internal virtual DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return null; } set { /* do nothing */ } } internal virtual bool IsISerializable { get { return false; } set { ThrowInvalidDataContractException(SR.RequiresClassDataContractToSetIsISerializable); } } internal XmlDictionaryString Name { get { return _name; } set { _name = value; } } public XmlDictionaryString Namespace { get { return _ns; } set { _ns = value; } } internal virtual bool HasRoot { get { return true; } set { } } internal virtual XmlDictionaryString? TopLevelElementName { get { return _name; } set { Debug.Assert(value != null); _name = value; } } internal virtual XmlDictionaryString? TopLevelElementNamespace { get { return _ns; } set { Debug.Assert(value != null); _ns = value; } } internal virtual bool CanContainReferences { get { return true; } } internal virtual bool IsPrimitive { get { return false; } } internal MethodInfo? ParseMethod { get { if (!_parseMethodSet) { MethodInfo? method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) }); if (method != null && method.ReturnType == UnderlyingType) { _parseMethod = method; } _parseMethodSet = true; } return _parseMethod; } } internal void SetDataContractName(XmlQualifiedName stableName) { XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(stableName.Name); this.Namespace = dictionary.Add(stableName.Namespace); this.StableName = stableName; } internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString ns) { this.Name = name; this.Namespace = ns; this.StableName = CreateQualifiedName(name.Value, ns.Value); } [DoesNotReturn] internal void ThrowInvalidDataContractException(string message) { ThrowInvalidDataContractException(message, UnderlyingType); } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsTypeSerializable(Type type) { return IsTypeSerializable(type, new HashSet<Type>()); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsTypeSerializable(Type type, HashSet<Type> previousCollectionTypes) { Type? itemType; if (type.IsSerializable || type.IsEnum || type.IsDefined(Globals.TypeOfDataContractAttribute, false) || type.IsInterface || type.IsPointer || //Special casing DBNull as its considered a Primitive but is no longer Serializable type == Globals.TypeOfDBNull || Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return true; } if (CollectionDataContract.IsCollection(type, out itemType)) { ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes); if (IsTypeSerializable(itemType, previousCollectionTypes)) { return true; } } return DataContract.GetBuiltInDataContract(type) != null || ClassDataContract.IsNonAttributedTypeValidForSerialization(type); } private static void ValidatePreviousCollectionTypes(Type collectionType, Type itemType, HashSet<Type> previousCollectionTypes) { previousCollectionTypes.Add(collectionType); while (itemType.IsArray) { itemType = itemType.GetElementType()!; } if (previousCollectionTypes.Contains(itemType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.RecursiveCollectionType, GetClrTypeFullName(itemType)))); } } internal static Type UnwrapRedundantNullableType(Type type) { Type nullableType = type; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullableType = type; type = type.GetGenericArguments()[0]; } return nullableType; } internal static Type UnwrapNullableType(Type type) { while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) type = type.GetGenericArguments()[0]; return type; } private static bool IsAlpha(char ch) { return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'); } private static bool IsDigit(char ch) { return (ch >= '0' && ch <= '9'); } private static bool IsAsciiLocalName(string localName) { if (localName.Length == 0) return false; if (!IsAlpha(localName[0])) return false; for (int i = 1; i < localName.Length; i++) { char ch = localName[i]; if (!IsAlpha(ch) && !IsDigit(ch)) return false; } return true; } internal static string EncodeLocalName(string localName) { if (IsAsciiLocalName(localName)) return localName; if (IsValidNCName(localName)) return localName; return XmlConvert.EncodeLocalName(localName); } internal static bool IsValidNCName(string name) { try { XmlConvert.VerifyNCName(name); return true; } catch (XmlException) { return false; } catch (Exception) { return false; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetStableName(Type type) { return GetStableName(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract) { type = UnwrapRedundantNullableType(type); XmlQualifiedName? stableName; if (TryGetBuiltInXmlAndArrayTypeStableName(type, out stableName)) { hasDataContract = false; } else { DataContractAttribute? dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { stableName = GetDCTypeStableName(type, dataContractAttribute); hasDataContract = true; } else { stableName = GetNonDCTypeStableName(type); hasDataContract = false; } } return stableName; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) { string? name, ns; if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; if (name == null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); name = DataContract.EncodeLocalName(name); } else name = GetDefaultStableLocalName(type); if (dataContractAttribute.IsNamespaceSetExplicitly) { ns = dataContractAttribute.Namespace; if (ns == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidDataContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } else ns = GetDefaultDataContractNamespace(type); return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetNonDCTypeStableName(Type type) { string? name, ns; Type? itemType; if (CollectionDataContract.IsCollection(type, out itemType)) return GetCollectionStableName(type, itemType, out _); name = GetDefaultStableLocalName(type); // ensures that ContractNamespaceAttribute is honored when used with non-attributed types if (ClassDataContract.IsNonAttributedTypeValidForSerialization(type)) { ns = GetDefaultDataContractNamespace(type); } else { ns = GetDefaultStableNamespace(type); } return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWhen(true)] out XmlQualifiedName? stableName) { stableName = null; DataContract? builtInContract = GetBuiltInDataContract(type); if (builtInContract != null) { stableName = builtInContract.StableName; } else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { XmlQualifiedName xmlTypeStableName; SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out _, out _); stableName = xmlTypeStableName; } else if (type.IsArray) { stableName = GetCollectionStableName(type, type.GetElementType()!, out _); } return stableName != null; } internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataContractAttribute? dataContractAttribute) { dataContractAttribute = null; object[] dataContractAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, false).ToArray(); if (dataContractAttributes != null && dataContractAttributes.Length > 0) { #if DEBUG if (dataContractAttributes.Length > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TooManyDataContracts, DataContract.GetClrTypeFullName(type)))); #endif dataContractAttribute = (DataContractAttribute)dataContractAttributes[0]; } return dataContractAttribute != null; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute? collectionContractAttribute) { string? name, ns; object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false).ToArray(); if (collectionContractAttributes != null && collectionContractAttributes.Length > 0) { #if DEBUG if (collectionContractAttributes.Length > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TooManyCollectionContracts, DataContract.GetClrTypeFullName(type)))); #endif collectionContractAttribute = (CollectionDataContractAttribute)collectionContractAttributes[0]; if (collectionContractAttribute.IsNameSetExplicitly) { name = collectionContractAttribute.Name; if (name == null || name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type)))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); name = DataContract.EncodeLocalName(name); } else name = GetDefaultStableLocalName(type); if (collectionContractAttribute.IsNamespaceSetExplicitly) { ns = collectionContractAttribute.Namespace; if (ns == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractNamespace, DataContract.GetClrTypeFullName(type)))); CheckExplicitDataContractNamespaceUri(ns, type); } else ns = GetDefaultDataContractNamespace(type); } else { collectionContractAttribute = null; string arrayOfPrefix = Globals.ArrayPrefix + GetArrayPrefix(ref itemType); XmlQualifiedName elementStableName = GetStableName(itemType); name = arrayOfPrefix + elementStableName.Name; ns = GetCollectionNamespace(elementStableName.Namespace); } return CreateQualifiedName(name, ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string GetArrayPrefix(ref Type itemType) { string arrayOfPrefix = string.Empty; while (itemType.IsArray) { if (DataContract.GetBuiltInDataContract(itemType) != null) break; arrayOfPrefix += Globals.ArrayPrefix; itemType = itemType.GetElementType()!; } return arrayOfPrefix; } internal static string GetCollectionNamespace(string elementNs) { return IsBuiltInNamespace(elementNs) ? Globals.CollectionsNamespace : elementNs; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetDefaultStableName(Type type) { return CreateQualifiedName(GetDefaultStableLocalName(type), GetDefaultStableNamespace(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string GetDefaultStableLocalName(Type type) { if (type.IsGenericParameter) return "{" + type.GenericParameterPosition + "}"; string typeName; string? arrayPrefix = null; if (type.IsArray) arrayPrefix = GetArrayPrefix(ref type); if (type.DeclaringType == null) typeName = type.Name; else { int nsLen = (type.Namespace == null) ? 0 : type.Namespace.Length; if (nsLen > 0) nsLen++; //include the . following namespace typeName = DataContract.GetClrTypeFullName(type).Substring(nsLen).Replace('+', '.'); } if (arrayPrefix != null) typeName = arrayPrefix + typeName; if (type.IsGenericType) { StringBuilder localName = new StringBuilder(); StringBuilder namespaces = new StringBuilder(); bool parametersFromBuiltInNamespaces = true; int iParam = typeName.IndexOf('['); if (iParam >= 0) typeName = typeName.Substring(0, iParam); IList<int> nestedParamCounts = GetDataContractNameForGenericName(typeName, localName); bool isTypeOpenGeneric = type.IsGenericTypeDefinition; Type[] genParams = type.GetGenericArguments(); for (int i = 0; i < genParams.Length; i++) { Type genParam = genParams[i]; if (isTypeOpenGeneric) localName.Append('{').Append(i).Append('}'); else { XmlQualifiedName qname = DataContract.GetStableName(genParam); localName.Append(qname.Name); namespaces.Append(' ').Append(qname.Namespace); if (parametersFromBuiltInNamespaces) parametersFromBuiltInNamespaces = IsBuiltInNamespace(qname.Namespace); } } if (isTypeOpenGeneric) localName.Append("{#}"); else if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces) { foreach (int count in nestedParamCounts) namespaces.Insert(0, count.ToString(CultureInfo.InvariantCulture)).Insert(0, " "); localName.Append(GetNamespacesDigest(namespaces.ToString())); } typeName = localName.ToString(); } return DataContract.EncodeLocalName(typeName); } private static string GetDefaultDataContractNamespace(Type type) { string? clrNs = type.Namespace; if (clrNs == null) clrNs = string.Empty; string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) ns = GetDefaultStableNamespace(type); else CheckExplicitDataContractNamespaceUri(ns, type); return ns; } internal static List<int> GetDataContractNameForGenericName(string typeName, StringBuilder? localName) { List<int> nestedParamCounts = new List<int>(); for (int startIndex = 0, endIndex; ;) { endIndex = typeName.IndexOf('`', startIndex); if (endIndex < 0) { if (localName != null) localName.Append(typeName.AsSpan(startIndex)); nestedParamCounts.Add(0); break; } if (localName != null) { string tempLocalName = typeName.Substring(startIndex, endIndex - startIndex); localName.Append((tempLocalName.Equals("KeyValuePairAdapter") ? "KeyValuePair" : tempLocalName)); } while ((startIndex = typeName.IndexOf('.', startIndex + 1, endIndex - startIndex - 1)) >= 0) nestedParamCounts.Add(0); startIndex = typeName.IndexOf('.', endIndex); if (startIndex < 0) { nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1), provider: CultureInfo.InvariantCulture)); break; } else nestedParamCounts.Add(int.Parse(typeName.AsSpan(endIndex + 1, startIndex - endIndex - 1), provider: CultureInfo.InvariantCulture)); } if (localName != null) localName.Append("Of"); return nestedParamCounts; } internal static bool IsBuiltInNamespace(string ns) { return (ns == Globals.SchemaNamespace || ns == Globals.SerializationNamespace); } internal static string GetDefaultStableNamespace(Type type) { if (type.IsGenericParameter) return "{ns}"; return GetDefaultStableNamespace(type.Namespace); } internal static XmlQualifiedName CreateQualifiedName(string localName, string ns) { return new XmlQualifiedName(localName, GetNamespace(ns)); } internal static string GetDefaultStableNamespace(string? clrNs) { if (clrNs == null) clrNs = string.Empty; return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static void GetDefaultStableName(string fullTypeName, out string localName, out string ns) { CodeTypeReference typeReference = new CodeTypeReference(fullTypeName); GetDefaultStableName(typeReference, out localName, out ns); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns) { string fullTypeName = typeReference.BaseType; DataContract? dataContract = GetBuiltInDataContract(fullTypeName); if (dataContract != null) { localName = dataContract.StableName.Name; ns = dataContract.StableName.Namespace; return; } GetClrNameAndNamespace(fullTypeName, out localName, out ns); if (typeReference.TypeArguments.Count > 0) { StringBuilder localNameBuilder = new StringBuilder(); StringBuilder argNamespacesBuilder = new StringBuilder(); bool parametersFromBuiltInNamespaces = true; List<int> nestedParamCounts = GetDataContractNameForGenericName(localName, localNameBuilder); foreach (CodeTypeReference typeArg in typeReference.TypeArguments) { string typeArgName, typeArgNs; GetDefaultStableName(typeArg, out typeArgName, out typeArgNs); localNameBuilder.Append(typeArgName); argNamespacesBuilder.Append(' ').Append(typeArgNs); if (parametersFromBuiltInNamespaces) { parametersFromBuiltInNamespaces = IsBuiltInNamespace(typeArgNs); } } if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces) { foreach (int count in nestedParamCounts) { argNamespacesBuilder.Insert(0, count).Insert(0, ' '); } localNameBuilder.Append(GetNamespacesDigest(argNamespacesBuilder.ToString())); } localName = localNameBuilder.ToString(); } localName = DataContract.EncodeLocalName(localName); ns = GetDefaultStableNamespace(ns); } private static void CheckExplicitDataContractNamespaceUri(string dataContractNs, Type type) { if (dataContractNs.Length > 0) { string trimmedNs = dataContractNs.Trim(); // Code similar to XmlConvert.ToUri (string.Empty is a valid uri but not " ") if (trimmedNs.Length == 0 || trimmedNs.IndexOf("##", StringComparison.Ordinal) != -1) ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type); dataContractNs = trimmedNs; } Uri? uri; if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri)) { if (uri.ToString() == Globals.SerializationNamespace) ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceReserved, Globals.SerializationNamespace), type); } else ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type); } internal static string GetClrTypeFullName(Type type) { return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName!; } internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns) { int nsEnd = fullTypeName.LastIndexOf('.'); if (nsEnd < 0) { ns = string.Empty; localName = fullTypeName.Replace('+', '.'); } else { ns = fullTypeName.Substring(0, nsEnd); localName = fullTypeName.Substring(nsEnd + 1).Replace('+', '.'); } int iParam = localName.IndexOf('['); if (iParam >= 0) localName = localName.Substring(0, iParam); } internal static string GetDataContractNamespaceFromUri(string uriString) { return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString; } private static string? GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes) { string? dataContractNs = null; for (int i = 0; i < nsAttributes.Length; i++) { ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i]; string? clrNsInAttribute = nsAttribute.ClrNamespace; if (clrNsInAttribute == null) clrNsInAttribute = string.Empty; if (clrNsInAttribute == clrNs) { if (nsAttribute.ContractNamespace == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGlobalDataContractNamespace, clrNs))); if (dataContractNs != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.DataContractNamespaceAlreadySet, dataContractNs, nsAttribute.ContractNamespace, clrNs))); dataContractNs = nsAttribute.ContractNamespace; } } return dataContractNs; } private static string GetNamespacesDigest(string namespaces) { byte[] namespaceBytes = Encoding.UTF8.GetBytes(namespaces); byte[] digestBytes = ComputeHash(namespaceBytes); char[] digestChars = new char[24]; const int digestLen = 6; int digestCharsLen = Convert.ToBase64CharArray(digestBytes, 0, digestLen, digestChars, 0); StringBuilder digest = new StringBuilder(); for (int i = 0; i < digestCharsLen; i++) { char ch = digestChars[i]; switch (ch) { case '=': break; case '/': digest.Append("_S"); break; case '+': digest.Append("_P"); break; default: digest.Append(ch); break; } } return digest.ToString(); } // An incomplete implementation of MD5 necessary for back-compat. // "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" // THIS HASH MAY ONLY BE USED FOR BACKWARDS-COMPATIBLE NAME GENERATION. DO NOT USE FOR SECURITY PURPOSES. private static byte[] ComputeHash(byte[] namespaces) { int[] shifts = new int[] { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; uint[] sines = new uint[] { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; int blocks = (namespaces.Length + 8) / 64 + 1; uint aa = 0x67452301; uint bb = 0xefcdab89; uint cc = 0x98badcfe; uint dd = 0x10325476; for (int i = 0; i < blocks; i++) { byte[] block = namespaces; int offset = i * 64; if (offset + 64 > namespaces.Length) { block = new byte[64]; for (int j = offset; j < namespaces.Length; j++) { block[j - offset] = namespaces[j]; } if (offset <= namespaces.Length) { block[namespaces.Length - offset] = 0x80; } if (i == blocks - 1) { unchecked { block[56] = (byte)(namespaces.Length << 3); block[57] = (byte)(namespaces.Length >> 5); block[58] = (byte)(namespaces.Length >> 13); block[59] = (byte)(namespaces.Length >> 21); } } offset = 0; } uint a = aa; uint b = bb; uint c = cc; uint d = dd; uint f; int g; for (int j = 0; j < 64; j++) { if (j < 16) { f = b & c | ~b & d; g = j; } else if (j < 32) { f = b & d | c & ~d; g = 5 * j + 1; } else if (j < 48) { f = b ^ c ^ d; g = 3 * j + 5; } else { f = c ^ (b | ~d); g = 7 * j; } g = (g & 0x0f) * 4 + offset; uint hold = d; d = c; c = b; b = unchecked(a + f + sines[j] + BinaryPrimitives.ReadUInt32LittleEndian(block.AsSpan(g))); b = b << shifts[j & 3 | j >> 2 & ~3] | b >> 32 - shifts[j & 3 | j >> 2 & ~3]; b = unchecked(b + c); a = hold; } unchecked { aa += a; bb += b; if (i < blocks - 1) { cc += c; dd += d; } } } unchecked { return new byte[] { (byte)aa, (byte)(aa >> 8), (byte)(aa >> 16), (byte)(aa >> 24), (byte)bb, (byte)(bb >> 8) }; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static string ExpandGenericParameters(string format, Type type) { GenericNameProvider genericNameProviderForType = new GenericNameProvider(type); return ExpandGenericParameters(format, genericNameProviderForType); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider) { string? digest = null; StringBuilder typeName = new StringBuilder(); IList<int> nestedParameterCounts = genericNameProvider.GetNestedParameterCounts(); for (int i = 0; i < format.Length; i++) { char ch = format[i]; if (ch == '{') { i++; int start = i; for (; i < format.Length; i++) if (format[i] == '}') break; if (i == format.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GenericNameBraceMismatch, format, genericNameProvider.GetGenericTypeName()))); if (format[start] == '#' && i == (start + 1)) { if (nestedParameterCounts.Count > 1 || !genericNameProvider.ParametersFromBuiltInNamespaces) { if (digest == null) { StringBuilder namespaces = new StringBuilder(genericNameProvider.GetNamespaces()); foreach (int count in nestedParameterCounts) namespaces.Insert(0, count.ToString(CultureInfo.InvariantCulture)).Insert(0, " "); digest = GetNamespacesDigest(namespaces.ToString()); } typeName.Append(digest); } } else { int paramIndex; if (!int.TryParse(format.AsSpan(start, i - start), out paramIndex) || paramIndex < 0 || paramIndex >= genericNameProvider.GetParameterCount()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GenericParameterNotValid, format.Substring(start, i - start), genericNameProvider.GetGenericTypeName(), genericNameProvider.GetParameterCount() - 1))); typeName.Append(genericNameProvider.GetParameterName(paramIndex)); } } else typeName.Append(ch); } return typeName.ToString(); } internal static bool IsTypeNullable(Type type) { return !type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContractDictionary? ImportKnownTypeAttributes(Type type) { DataContractDictionary? knownDataContracts = null; Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>(); ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts); return knownDataContracts; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void ImportKnownTypeAttributes(Type? type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary? knownDataContracts) { while (type != null && DataContract.IsTypeSerializable(type)) { if (typesChecked.ContainsKey(type)) return; typesChecked.Add(type, type); object[] knownTypeAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, false).ToArray(); if (knownTypeAttributes != null) { KnownTypeAttribute kt; bool useMethod = false, useType = false; for (int i = 0; i < knownTypeAttributes.Length; ++i) { kt = (KnownTypeAttribute)knownTypeAttributes[i]; if (kt.Type != null) { if (useMethod) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type); } CheckAndAdd(kt.Type, typesChecked, ref knownDataContracts); useType = true; } else { if (useMethod || useType) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type); } string? methodName = kt.MethodName; if (methodName == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type); } if (methodName.Length == 0) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type); MethodInfo? method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Type.EmptyTypes); if (method == null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type); if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType)) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type); object? types = method.Invoke(null, Array.Empty<object>()); if (types == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type); } foreach (Type ty in (IEnumerable<Type>)types) { if (ty == null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeValidMethodTypes, DataContract.GetClrTypeFullName(type)), type); CheckAndAdd(ty, typesChecked, ref knownDataContracts); } useMethod = true; } } } //For Json we need to add KeyValuePair<K,T> to KnownTypes if the UnderLyingType is a Dictionary<K,T> try { CollectionDataContract? collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract; if (collectionDataContract != null && collectionDataContract.IsDictionary && collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GetGenericArguments())); if (knownDataContracts == null) { knownDataContracts = new DataContractDictionary(); } knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } } catch (InvalidDataContractException) { //Ignore any InvalidDataContractException as this phase is a workaround for lack of ISerializable. //InvalidDataContractException may happen as we walk the type hierarchy back to Object and encounter //types that may not be valid DC. This step is purely for KeyValuePair and shouldn't fail the (de)serialization. //Any IDCE in this case fails the serialization/deserialization process which is not the optimal experience. } type = type.BaseType; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, [NotNullIfNotNull("nameToDataContractTable")] ref DataContractDictionary? nameToDataContractTable) { type = DataContract.UnwrapNullableType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContract? alreadyExistingContract; if (nameToDataContractTable == null) { nameToDataContractTable = new DataContractDictionary(); } else if (nameToDataContractTable.TryGetValue(dataContract.StableName, out alreadyExistingContract)) { // Don't throw duplicate if its a KeyValuePair<K,T> as it could have been added by Dictionary<K,T> if (DataContractCriticalHelper.GetDataContractAdapterType(alreadyExistingContract.UnderlyingType) != DataContractCriticalHelper.GetDataContractAdapterType(type) && !(alreadyExistingContract is ClassDataContract && ((ClassDataContract)alreadyExistingContract).IsKeyValuePairAdapter)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.DupContractInKnownTypes, type, alreadyExistingContract.UnderlyingType, dataContract.StableName.Namespace, dataContract.StableName.Name))); return; } nameToDataContractTable.Add(dataContract.StableName, dataContract); ImportKnownTypeAttributes(type, typesChecked, ref nameToDataContractTable); } /// <SecurityNote> /// Review - checks type visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool IsTypeVisible(Type t) { if (!t.IsVisible && !IsTypeVisibleInSerializationModule(t)) return false; foreach (Type genericType in t.GetGenericArguments()) { if (!genericType.IsGenericParameter && !IsTypeVisible(genericType)) return false; } return true; } /// <SecurityNote> /// Review - checks constructor visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor) { return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor); } /// <SecurityNote> /// Review - checks method visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool MethodRequiresMemberAccess(MethodInfo? method) { return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method); } /// <SecurityNote> /// Review - checks field visibility to calculate if access to it requires MemberAccessPermission. /// note: does local check for visibility, assuming that the declaring Type visibility has been checked. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool FieldRequiresMemberAccess(FieldInfo? field) { return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field); } /// <SecurityNote> /// Review - checks type visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private static bool IsTypeVisibleInSerializationModule(Type type) { return (type.Module.Equals(typeof(DataContract).Module) || IsAssemblyFriendOfSerialization(type.Assembly)) && !type.IsNestedPrivate; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private static bool IsMemberVisibleInSerializationModule(MemberInfo member) { if (!IsTypeVisibleInSerializationModule(member.DeclaringType!)) return false; if (member is MethodInfo) { MethodInfo method = (MethodInfo)member; return (method.IsAssembly || method.IsFamilyOrAssembly); } else if (member is FieldInfo) { FieldInfo field = (FieldInfo)member; return (field.IsAssembly || field.IsFamilyOrAssembly) && IsTypeVisible(field.FieldType); } else if (member is ConstructorInfo) { ConstructorInfo constructor = (ConstructorInfo)member; return (constructor.IsAssembly || constructor.IsFamilyOrAssembly); } return false; } /// <SecurityNote> /// Review - checks member visibility to calculate if access to it requires MemberAccessPermission. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal static bool IsAssemblyFriendOfSerialization(Assembly assembly) { InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute)); foreach (InternalsVisibleToAttribute internalsVisibleAttribute in internalsVisibleAttributes) { string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName; if (internalsVisibleAttributeAssemblyName.Trim().Equals("System.Runtime.Serialization") || Globals.FullSRSInternalsVisibleRegex().IsMatch(internalsVisibleAttributeAssemblyName)) { return true; } } return false; } internal static string SanitizeTypeName(string typeName) { return typeName.Replace('.', '_'); } } internal interface IGenericNameProvider { int GetParameterCount(); IList<int> GetNestedParameterCounts(); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] string GetParameterName(int paramIndex); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] string GetNamespaces(); string GetGenericTypeName(); bool ParametersFromBuiltInNamespaces { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get; } } internal sealed class GenericNameProvider : IGenericNameProvider { private readonly string _genericTypeName; private readonly object[] _genericParams; //Type or DataContract private readonly IList<int> _nestedParamCounts; internal GenericNameProvider(Type type) : this(DataContract.GetClrTypeFullName(type.GetGenericTypeDefinition()), type.GetGenericArguments()) { } internal GenericNameProvider(string genericTypeName, object[] genericParams) { _genericTypeName = genericTypeName; _genericParams = new object[genericParams.Length]; genericParams.CopyTo(_genericParams, 0); string name; DataContract.GetClrNameAndNamespace(genericTypeName, out name, out _); _nestedParamCounts = DataContract.GetDataContractNameForGenericName(name, null); } public int GetParameterCount() { return _genericParams.Length; } public IList<int> GetNestedParameterCounts() { return _nestedParamCounts; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public string GetParameterName(int paramIndex) { return GetStableName(paramIndex).Name; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public string GetNamespaces() { StringBuilder namespaces = new StringBuilder(); for (int j = 0; j < GetParameterCount(); j++) namespaces.Append(' ').Append(GetStableName(j).Namespace); return namespaces.ToString(); } public string GetGenericTypeName() { return _genericTypeName; } public bool ParametersFromBuiltInNamespaces { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { bool parametersFromBuiltInNamespaces = true; for (int j = 0; j < GetParameterCount(); j++) { if (parametersFromBuiltInNamespaces) parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(GetStableName(j).Namespace); else break; } return parametersFromBuiltInNamespaces; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlQualifiedName GetStableName(int i) { object o = _genericParams[i]; XmlQualifiedName? qname = o as XmlQualifiedName; if (qname == null) { Type? paramType = o as Type; if (paramType != null) _genericParams[i] = qname = DataContract.GetStableName(paramType); else _genericParams[i] = qname = ((DataContract)o).StableName; } return qname; } } internal sealed class TypeHandleRefEqualityComparer : IEqualityComparer<TypeHandleRef> { public bool Equals(TypeHandleRef? x, TypeHandleRef? y) { return x!.Value.Equals(y!.Value); } public int GetHashCode(TypeHandleRef obj) { return obj.Value.GetHashCode(); } } internal sealed class TypeHandleRef { private RuntimeTypeHandle _value; public TypeHandleRef() { } public TypeHandleRef(RuntimeTypeHandle value) { _value = value; } public RuntimeTypeHandle Value { get { return _value; } set { _value = value; } } } internal sealed class IntRef { private readonly int _value; public IntRef(int value) { _value = value; } public int Value { get { return _value; } } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Runtime.Serialization { internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName? s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName? s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type? s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type? s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type? s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type? s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type? s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type? s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type? s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type? s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type? s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type? s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type? s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type? s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type? s_typeOfMemoryStream; internal static Type TypeOfMemoryStream { get { if (s_typeOfMemoryStream == null) s_typeOfMemoryStream = typeof(MemoryStream); return s_typeOfMemoryStream; } } private static Type? s_typeOfMemoryStreamAdapter; internal static Type TypeOfMemoryStreamAdapter { get { if (s_typeOfMemoryStreamAdapter == null) s_typeOfMemoryStreamAdapter = typeof(MemoryStreamAdapter); return s_typeOfMemoryStreamAdapter; } } private static Type? s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type? s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type? s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type? s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type? s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type? s_typeOfIObjectReference; internal static Type TypeOfIObjectReference { get { if (s_typeOfIObjectReference == null) s_typeOfIObjectReference = typeof(IObjectReference); return s_typeOfIObjectReference; } } private static Type? s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type? s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type? s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type? s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type? s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type? s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type? s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type? s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type? s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type? s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type? s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type? s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type? s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type? s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type? s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type? s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type? s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type? s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type? s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type? s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type? s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type? s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get { if (s_typeOfXmlSchemaType == null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } return s_typeOfXmlSchemaType; } } private static Type? s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); private static Type? s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); private static Type? s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type? s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type? s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type? s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); private static Type? s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type? s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type? s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type? s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type? s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type? s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type? s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type? s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type? s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type? s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type? s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type? s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type? s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type? s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type? s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type? s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type? s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type? s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type? s_typeOfHashtable; internal static Type TypeOfHashtable { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type? s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type? s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static Type? s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } } private static Uri? s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } private static readonly Type? s_typeOfScriptObject; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?> <xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='anyType' nillable='true' type='xs:anyType' /> <xs:element name='anyURI' nillable='true' type='xs:anyURI' /> <xs:element name='base64Binary' nillable='true' type='xs:base64Binary' /> <xs:element name='boolean' nillable='true' type='xs:boolean' /> <xs:element name='byte' nillable='true' type='xs:byte' /> <xs:element name='dateTime' nillable='true' type='xs:dateTime' /> <xs:element name='decimal' nillable='true' type='xs:decimal' /> <xs:element name='double' nillable='true' type='xs:double' /> <xs:element name='float' nillable='true' type='xs:float' /> <xs:element name='int' nillable='true' type='xs:int' /> <xs:element name='long' nillable='true' type='xs:long' /> <xs:element name='QName' nillable='true' type='xs:QName' /> <xs:element name='short' nillable='true' type='xs:short' /> <xs:element name='string' nillable='true' type='xs:string' /> <xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' /> <xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' /> <xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' /> <xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' /> <xs:element name='char' nillable='true' type='tns:char' /> <xs:simpleType name='char'> <xs:restriction base='xs:int'/> </xs:simpleType> <xs:element name='duration' nillable='true' type='tns:duration' /> <xs:simpleType name='duration'> <xs:restriction base='xs:duration'> <xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' /> <xs:minInclusive value='-P10675199DT2H48M5.4775808S' /> <xs:maxInclusive value='P10675199DT2H48M5.4775807S' /> </xs:restriction> </xs:simpleType> <xs:element name='guid' nillable='true' type='tns:guid' /> <xs:simpleType name='guid'> <xs:restriction base='xs:string'> <xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' /> </xs:restriction> </xs:simpleType> <xs:attribute name='FactoryType' type='xs:QName' /> <xs:attribute name='Id' type='xs:ID' /> <xs:attribute name='Ref' type='xs:IDREF' /> </xs:schema> "; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Runtime.Serialization { internal static partial class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName? s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName? s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type? s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type? s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type? s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type? s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type? s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type? s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type? s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type? s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type? s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type? s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type? s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type? s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type? s_typeOfMemoryStream; internal static Type TypeOfMemoryStream { get { if (s_typeOfMemoryStream == null) s_typeOfMemoryStream = typeof(MemoryStream); return s_typeOfMemoryStream; } } private static Type? s_typeOfMemoryStreamAdapter; internal static Type TypeOfMemoryStreamAdapter { get { if (s_typeOfMemoryStreamAdapter == null) s_typeOfMemoryStreamAdapter = typeof(MemoryStreamAdapter); return s_typeOfMemoryStreamAdapter; } } private static Type? s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type? s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type? s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type? s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type? s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type? s_typeOfIObjectReference; internal static Type TypeOfIObjectReference { get { if (s_typeOfIObjectReference == null) s_typeOfIObjectReference = typeof(IObjectReference); return s_typeOfIObjectReference; } } private static Type? s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type? s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type? s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type? s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type? s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type? s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type? s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type? s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type? s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type? s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type? s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type? s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type? s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type? s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type? s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type? s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type? s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type? s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type? s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type? s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type? s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type? s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get { if (s_typeOfXmlSchemaType == null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } return s_typeOfXmlSchemaType; } } private static Type? s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); private static Type? s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); private static Type? s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type? s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type? s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type? s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); private static Type? s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type? s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type? s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type? s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type? s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type? s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type? s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type? s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type? s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type? s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type? s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type? s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type? s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type? s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type? s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type? s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type? s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type? s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type? s_typeOfHashtable; internal static Type TypeOfHashtable { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type? s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type? s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static Type? s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } } private static Uri? s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } private static readonly Type? s_typeOfScriptObject; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; [RegexGenerator(FullSRSInternalsVisiblePattern)] public static partial Regex FullSRSInternalsVisibleRegex(); public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?> <xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='anyType' nillable='true' type='xs:anyType' /> <xs:element name='anyURI' nillable='true' type='xs:anyURI' /> <xs:element name='base64Binary' nillable='true' type='xs:base64Binary' /> <xs:element name='boolean' nillable='true' type='xs:boolean' /> <xs:element name='byte' nillable='true' type='xs:byte' /> <xs:element name='dateTime' nillable='true' type='xs:dateTime' /> <xs:element name='decimal' nillable='true' type='xs:decimal' /> <xs:element name='double' nillable='true' type='xs:double' /> <xs:element name='float' nillable='true' type='xs:float' /> <xs:element name='int' nillable='true' type='xs:int' /> <xs:element name='long' nillable='true' type='xs:long' /> <xs:element name='QName' nillable='true' type='xs:QName' /> <xs:element name='short' nillable='true' type='xs:short' /> <xs:element name='string' nillable='true' type='xs:string' /> <xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' /> <xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' /> <xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' /> <xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' /> <xs:element name='char' nillable='true' type='tns:char' /> <xs:simpleType name='char'> <xs:restriction base='xs:int'/> </xs:simpleType> <xs:element name='duration' nillable='true' type='tns:duration' /> <xs:simpleType name='duration'> <xs:restriction base='xs:duration'> <xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' /> <xs:minInclusive value='-P10675199DT2H48M5.4775808S' /> <xs:maxInclusive value='P10675199DT2H48M5.4775807S' /> </xs:restriction> </xs:simpleType> <xs:element name='guid' nillable='true' type='tns:guid' /> <xs:simpleType name='guid'> <xs:restriction base='xs:string'> <xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' /> </xs:restriction> </xs:simpleType> <xs:attribute name='FactoryType' type='xs:QName' /> <xs:attribute name='Id' type='xs:ID' /> <xs:attribute name='Ref' type='xs:IDREF' /> </xs:schema> "; } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.IO.Tests { [PlatformSpecific(TestPlatforms.Windows)] public class PathTests_Windows : PathTestsBase { [Fact] public void GetDirectoryName_DevicePath() { if (PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\?\C:", Path.GetDirectoryName(@"\\?\C:\foo")); } else { Assert.Equal(@"\\?\C:\", Path.GetDirectoryName(@"\\?\C:\foo")); } } [Theory, MemberData(nameof(TestData_GetDirectoryName_Windows))] public void GetDirectoryName(string path, string expected) { Assert.Equal(expected, Path.GetDirectoryName(path)); } [Theory, InlineData("B:", ""), InlineData("A:.", ".")] public static void GetFileName_Volume(string path, string expected) { // With a valid drive letter followed by a colon, we have a root, but only on Windows. Assert.Equal(expected, Path.GetFileName(path)); } [Theory, MemberData(nameof(TestData_GetPathRoot_Windows)), MemberData(nameof(TestData_GetPathRoot_Unc)), MemberData(nameof(TestData_GetPathRoot_DevicePaths))] public void GetPathRoot_Windows(string value, string expected) { Assert.Equal(expected, Path.GetPathRoot(value)); if (value.Length != expected.Length) { // The string overload normalizes the separators Assert.Equal(expected, Path.GetPathRoot(value.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))); // UNCs and device paths will have their semantics changed if we double up separators if (!value.StartsWith(@"\\")) Assert.Equal(expected, Path.GetPathRoot(value.Replace(@"\", @"\\"))); } } public static IEnumerable<string[]> GetTempPath_SetEnvVar_Data() { yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp" }; yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\" }; yield return new string[] { @"C:\", @"C:\" }; yield return new string[] { @"C:\tmp\", @"C:\tmp" }; yield return new string[] { @"C:\tmp\", @"C:\tmp\" }; } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void GetTempPath_SetEnvVar() { RemoteExecutor.Invoke(() => { foreach (string[] tempPath in GetTempPath_SetEnvVar_Data()) { GetTempPath_SetEnvVar_Helper("TMP", tempPath[0], tempPath[1]); } }).Dispose(); } [Theory, MemberData(nameof(TestData_Spaces))] public void GetFullPath_TrailingSpacesCut(string component) { // Windows cuts off any simple white space added to a path string path = "C:\\Test" + component; Assert.Equal("C:\\Test", Path.GetFullPath(path)); } [Fact] public void GetFullPath_NormalizedLongPathTooLong() { // Try out a long path that normalizes down to more than MaxPath string curDir = Directory.GetCurrentDirectory(); const int Iters = 260; var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4)); for (int i = 0; i < Iters; i++) { longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.'); } if (PathFeatures.AreAllLongPathsAvailable()) { // Now no longer throws unless over ~32K Assert.NotNull(Path.GetFullPath(longPath.ToString())); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString())); } } [Theory, InlineData(@"C:..."), InlineData(@"C:...\somedir"), InlineData(@"\.. .\"), InlineData(@"\. .\"), InlineData(@"\ .\")] public void GetFullPath_LegacyArgumentExceptionPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // We didn't allow these paths on < 4.6.2 AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { // These paths are legitimate Windows paths that can be created without extended syntax. // We now allow them through. Path.GetFullPath(path); } } [Fact] public void GetFullPath_MaxPathNotTooLong() { string value = @"C:\" + new string('a', 255) + @"\"; if (PathFeatures.AreAllLongPathsAvailable()) { // Shouldn't throw anymore Path.GetFullPath(value); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(value)); } } [Fact] public void GetFullPath_PathTooLong() { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\")); } [Theory, InlineData(@"C:\", @"C:\"), InlineData(@"C:\.", @"C:\"), InlineData(@"C:\..", @"C:\"), InlineData(@"C:\..\..", @"C:\"), InlineData(@"C:\A\..", @"C:\"), InlineData(@"C:\..\..\A\..", @"C:\")] public void GetFullPath_RelativeRoot(string path, string expected) { Assert.Equal(Path.GetFullPath(path), expected); } [Fact] public void GetFullPath_StrangeButLegalPaths() { // These are legal and creatable without using extended syntax if you use a trailing slash // (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from // being blocked when they hit these paths. string curDir = Directory.GetCurrentDirectory(); if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy path Path.GetFullePath() ignores . when there is less or more that two, when there is .. in the path it returns one directory up. Assert.Equal( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } else { Assert.NotEqual( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } } [Theory, InlineData(@"\\?\C:\ "), InlineData(@"\\?\C:\ \ "), InlineData(@"\\?\C:\ ."), InlineData(@"\\?\C:\ .."), InlineData(@"\\?\C:\..."), InlineData(@"\\?\GLOBALROOT\"), InlineData(@"\\?\"), InlineData(@"\\?\."), InlineData(@"\\?\.."), InlineData(@"\\?\\"), InlineData(@"\\?\C:\\"), InlineData(@"\\?\C:\|"), InlineData(@"\\?\C:\."), InlineData(@"\\?\C:\.."), InlineData(@"\\?\C:\Foo1\."), InlineData(@"\\?\C:\Foo2\.."), InlineData(@"\\?\UNC\"), InlineData(@"\\?\UNC\server1"), InlineData(@"\\?\UNC\server2\"), InlineData(@"\\?\UNC\server3\\"), InlineData(@"\\?\UNC\server4\.."), InlineData(@"\\?\UNC\server5\share\."), InlineData(@"\\?\UNC\server6\share\.."), InlineData(@"\\?\UNC\a\b\\"), InlineData(@"\\.\"), InlineData(@"\\.\."), InlineData(@"\\.\.."), InlineData(@"\\.\\"), InlineData(@"\\.\C:\\"), InlineData(@"\\.\C:\|"), InlineData(@"\\.\C:\."), InlineData(@"\\.\C:\.."), InlineData(@"\\.\C:\Foo1\."), InlineData(@"\\.\C:\Foo2\..")] public void GetFullPath_ValidExtendedPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy Path doesn't support any of these paths. AssertExtensions.ThrowsAny<ArgumentException, NotSupportedException>(() => Path.GetFullPath(path)); return; } // None of these should throw if (path.StartsWith(@"\\?\")) { Assert.Equal(path, Path.GetFullPath(path)); } else { Path.GetFullPath(path); } } [Theory, InlineData(@"\\.\UNC\"), InlineData(@"\\.\UNC\LOCALHOST"), InlineData(@"\\.\UNC\localHOST\"), InlineData(@"\\.\UNC\LOcaLHOST\\"), InlineData(@"\\.\UNC\lOCALHOST\.."), InlineData(@"\\.\UNC\LOCALhost\share\."), InlineData(@"\\.\UNC\loCALHOST\share\.."), InlineData(@"\\.\UNC\a\b\\")] public static void GetFullPath_ValidLegacy_ValidExtendedPaths(string path) { // should not throw Path.GetFullPath(path); } [Theory, // https://github.com/dotnet/runtime/issues/18664 InlineData(@"\\LOCALHOST\share\test.txt.~SS", @"\\LOCALHOST\share\test.txt.~SS"), InlineData(@"\\LOCALHOST\share1", @"\\LOCALHOST\share1"), InlineData(@"\\LOCALHOST\share3\dir", @"\\LOCALHOST\share3\dir"), InlineData(@"\\LOCALHOST\share4\.", @"\\LOCALHOST\share4"), InlineData(@"\\LOCALHOST\share5\..", @"\\LOCALHOST\share5"), InlineData(@"\\LOCALHOST\share6\ ", @"\\LOCALHOST\share6\"), InlineData(@"\\LOCALHOST\ share7\", @"\\LOCALHOST\ share7\"), InlineData(@"\\?\UNC\LOCALHOST\share8\test.txt.~SS", @"\\?\UNC\LOCALHOST\share8\test.txt.~SS"), InlineData(@"\\?\UNC\LOCALHOST\share9", @"\\?\UNC\LOCALHOST\share9"), InlineData(@"\\?\UNC\LOCALHOST\shareA\dir", @"\\?\UNC\LOCALHOST\shareA\dir"), InlineData(@"\\?\UNC\LOCALHOST\shareB\. ", @"\\?\UNC\LOCALHOST\shareB\. "), InlineData(@"\\?\UNC\LOCALHOST\shareC\.. ", @"\\?\UNC\LOCALHOST\shareC\.. "), InlineData(@"\\?\UNC\LOCALHOST\shareD\ ", @"\\?\UNC\LOCALHOST\shareD\ "), InlineData(@"\\.\UNC\LOCALHOST\ shareE\", @"\\.\UNC\LOCALHOST\ shareE\"), InlineData(@"\\.\UNC\LOCALHOST\shareF\test.txt.~SS", @"\\.\UNC\LOCALHOST\shareF\test.txt.~SS"), InlineData(@"\\.\UNC\LOCALHOST\shareG", @"\\.\UNC\LOCALHOST\shareG"), InlineData(@"\\.\UNC\LOCALHOST\shareH\dir", @"\\.\UNC\LOCALHOST\shareH\dir"), InlineData(@"\\.\UNC\LOCALHOST\shareK\ ", @"\\.\UNC\LOCALHOST\shareK\"), InlineData(@"\\.\UNC\LOCALHOST\ shareL\", @"\\.\UNC\LOCALHOST\ shareL\")] public void GetFullPath_UNC_Valid(string path, string expected) { if (path.StartsWith(@"\\?\") && PathFeatures.IsUsingLegacyPathNormalization()) { AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { Assert.Equal(expected, Path.GetFullPath(path)); } } [Theory, InlineData(@"\\.\UNC\LOCALHOST\shareI\. ", @"\\.\UNC\LOCALHOST\shareI\", @"\\.\UNC\LOCALHOST\shareI"), InlineData(@"\\.\UNC\LOCALHOST\shareJ\.. ", @"\\.\UNC\LOCALHOST\shareJ\", @"\\.\UNC\LOCALHOST")] public static void GetFullPath_Windows_UNC_Valid_LegacyPathSupport(string path, string normalExpected, string legacyExpected) { string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected; Assert.Equal(expected, Path.GetFullPath(path)); } [Fact] public static void GetFullPath_Windows_83Paths() { // Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened. string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt"); File.Create(tempFilePath).Dispose(); try { // Get its short name var sb = new StringBuilder(260); if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name { string shortName = sb.ToString(); // Make sure the shortened name expands back to the original one // Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); Assert.Equal(tempFilePath, shortName); // Should work with device paths that aren't well-formed extended syntax if (!PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName)); Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName)); // Shouldn't mess with well-formed extended syntax Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName)); } // Validate case where short name doesn't expand to a real file string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp"; Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName)); // Same thing, but with a long path that normalizes down to a short enough one const int Iters = 1000; var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2)); for (int i = 0; i < Iters; i++) { shortLongName.Append(Path.DirectorySeparatorChar).Append('.'); } Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString())); } } finally { File.Delete(tempFilePath); } } [Theory, MemberData(nameof(TestData_GetPathRoot_Windows)), MemberData(nameof(TestData_GetPathRoot_Unc)), MemberData(nameof(TestData_GetPathRoot_DevicePaths))] public void GetPathRoot_Span(string value, string expected) { Assert.Equal(expected, new string(Path.GetPathRoot(value.AsSpan()))); Assert.True(Path.IsPathRooted(value.AsSpan())); } [Theory, MemberData(nameof(TestData_UnicodeWhiteSpace))] public void GetFullPath_UnicodeWhiteSpaceStays(string component) { // When not .NET Framework full path should not cut off component string path = "C:\\Test" + component; Assert.Equal(path, Path.GetFullPath(path)); } [Theory, MemberData(nameof(TestData_Periods))] public void GetFullPath_TrailingPeriodsCut(string component) { // Windows cuts off any simple white space added to a path string path = "C:\\Test" + component; Assert.Equal("C:\\Test", Path.GetFullPath(path)); } public static TheoryData<string, string, string> GetFullPath_Windows_FullyQualified => new TheoryData<string, string, string> { { @"C:\git\runtime", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime\\\.", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\somedir\..", @"C:\git\runtime", @"C:\" }, { @"C:\", @"C:\git\runtime", @"C:\" }, { @"..\..\..\..", @"C:\git\runtime", @"C:\" }, { @"C:\\\", @"C:\git\runtime", @"C:\" }, { @"C:\..\..\", @"C:\git\runtime", @"C:\" }, { @"C:\..\git\..\.\", @"C:\git\runtime", @"C:\" }, { @"C:\git\runtime\..\..\..\", @"C:\git\runtime", @"C:\" }, { @"C:\.\runtime\", @"C:\git\runtime", @"C:\runtime\" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_FullyQualified))] public void GetFullPath_BasicExpansions_Windows(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_PathIsDevicePath => new TheoryData<string, string, string> { // Device Paths with \\?\ wont get normalized i.e. relative segments wont get removed. { @"\\?\C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"\\?\C:\git\runtime.\.\.\.\.\." }, { @"\\?\C:\git\runtime\\\.", @"C:\git\runtime", @"\\?\C:\git\runtime\\\." }, { @"\\?\C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"\\?\C:\git\runtime\..\runtime\.\..\runtime" }, { @"\\?\\somedir\..", @"C:\git\runtime", @"\\?\\somedir\.." }, { @"\\?\", @"C:\git\runtime", @"\\?\" }, { @"\\?\..\..\..\..", @"C:\git\runtime", @"\\?\..\..\..\.." }, { @"\\?\\\\" , @"C:\git\runtime", @"\\?\\\\" }, { @"\\?\C:\Foo." , @"C:\git\runtime", @"\\?\C:\Foo." }, { @"\\?\C:\Foo " , @"C:\git\runtime", @"\\?\C:\Foo " }, { @"\\.\C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\C:\git\runtime\\\.", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\\somedir\..", @"C:\git\runtime", @"\\.\" }, { @"\\.\", @"C:\git\runtime", @"\\.\" }, { @"\\.\..\..\..\..", @"C:\git\runtime", @"\\.\" }, { @"\\.\", @"C:\git\runtime", @"\\.\" }, { @"\\.\C:\Foo." , @"C:\git\runtime", @"\\.\C:\Foo" }, { @"\\.\C:\Foo " , @"C:\git\runtime", @"\\.\C:\Foo" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_PathIsDevicePath))] public void GetFullPath_BasicExpansions_Windows_PathIsDevicePath(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); Assert.Equal(expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(expected, Path.GetFullPath(path, @"\\?\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_UNC => new TheoryData<string, string, string> { { @"foo", @"", @"foo" }, { @"foo", @"server1", @"server1\foo" }, { @"\foo", @"server2", @"server2\foo" }, { @"foo", @"server3\", @"server3\foo" }, { @"..\foo", @"server4", @"server4\..\foo" }, { @".\foo", @"server5\share", @"server5\share\foo" }, { @"..\foo", @"server6\share", @"server6\share\foo" }, { @"\foo", @"a\b\\", @"a\b\foo" }, { @"foo", @"LOCALHOST\share8\test.txt.~SS", @"LOCALHOST\share8\test.txt.~SS\foo" }, { @"foo", @"LOCALHOST\share9", @"LOCALHOST\share9\foo" }, { @"foo", @"LOCALHOST\shareA\dir", @"LOCALHOST\shareA\dir\foo" }, { @". \foo", @"LOCALHOST\shareB\", @"LOCALHOST\shareB\. \foo" }, { @".. \foo", @"LOCALHOST\shareC\", @"LOCALHOST\shareC\.. \foo" }, { @" \foo", @"LOCALHOST\shareD\", @"LOCALHOST\shareD\ \foo" }, { "foo", @"LOCALHOST\ shareE\", @"LOCALHOST\ shareE\foo" }, { "foo", @"LOCALHOST\shareF\test.txt.~SS", @"LOCALHOST\shareF\test.txt.~SS\foo" }, { "foo", @"LOCALHOST\shareG", @"LOCALHOST\shareG\foo" }, { "foo", @"LOCALHOST\shareH\dir", @"LOCALHOST\shareH\dir\foo" }, { "foo", @"LOCALHOST\shareK\", @"LOCALHOST\shareK\foo" }, { "foo", @"LOCALHOST\ shareL\", @"LOCALHOST\ shareL\foo" }, // Relative segments eating into the root { @".\..\foo\..\", @"server\share", @"server\share\" }, { @"..\foo\tmp\..\..\", @"server\share", @"server\share\" }, { @"..\..\..\foo", @"server\share", @"server\share\foo" }, { @"..\foo\..\..\tmp", @"server\share", @"server\share\tmp" }, { @"..\foo", @"server\share", @"server\share\foo" }, { @"...\\foo", @"server\share", @"server\share\...\foo" }, { @"...\..\.\foo", @"server\share", @"server\share\foo" }, { @"..\foo\tmp\..\..\..\..\..\", @"server\share", @"server\share\" }, { @"..\..\..\..\foo", @"server\share", @"server\share\foo" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_UNC))] public void GetFullPath_CommonUnc_Windows(string path, string basePath, string expected) { Assert.Equal(@"\\" + expected, Path.GetFullPath(path, @"\\" + basePath)); Assert.Equal(@"\\.\UNC\" + expected, Path.GetFullPath(path, @"\\.\UNC\" + basePath)); Assert.Equal(@"\\?\UNC\" + expected, Path.GetFullPath(path, @"\\?\UNC\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_CommonDevicePaths => new TheoryData<string, string, string> { // Device paths { "foo", @"C:\ ", @"C:\ \foo" }, { @" \ \foo", @"C:\", @"C:\ \ \foo" }, { @" .\foo", @"C:\", @"C:\ .\foo" }, { @" ..\foo", @"C:\", @"C:\ ..\foo" }, { @"...\foo", @"C:\", @"C:\...\foo" }, { @"foo", @"C:\\", @"C:\foo" }, { @"foo.", @"C:\\", @"C:\foo." }, { @"foo \git", @"C:\\", @"C:\foo \git" }, { @"foo. \git", @"C:\\", @"C:\foo. \git" }, { @" foo \git", @"C:\\", @"C:\ foo \git" }, { @"foo ", @"C:\\", @"C:\foo " }, { @"|\foo", @"C:\", @"C:\|\foo" }, { @".\foo", @"C:\", @"C:\foo" }, { @"..\foo", @"C:\", @"C:\foo" }, { @"\Foo1\.\foo", @"C:\", @"C:\Foo1\foo" }, { @"\Foo2\..\foo", @"C:\", @"C:\foo" }, { @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"foo", @"", @"foo" }, { @".\foo", @"", @".\foo" }, { @"..\foo", @"", @"..\foo" }, { @"C:", @"", @"C:\"}, // Relative segments eating into the root { @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"..\..\foo\..\..\", @"", @"..\" }, { @".\..\..\..\..\foo", @"", @".\foo" }, { @"..\foo\..\..\..\", @"", @"..\" }, { @"\.\.\..\", @"C:\", @"C:\"}, { @"..\..\..\foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"foo\..\..\", @"", @"foo\" }, { @".\.\foo\..\", @"", @".\" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_CommonDevicePaths))] public void GetFullPath_CommonDevice_Windows(string path, string basePath, string expected) { Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_CommonRootedWindowsData => new TheoryData<string, string, string> { { "", @"C:\git\runtime", @"C:\git\runtime" }, { "..", @"C:\git\runtime", @"C:\git" }, // Current drive rooted { @"\tmp\bar", @"C:\git\runtime", @"C:\tmp\bar" }, { @"\.\bar", @"C:\git\runtime", @"C:\bar" }, { @"\tmp\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\bar\..", @"C:\git\runtime", @"C:\tmp" }, { @"\tmp\bar\..", @"C:\git\runtime", @"C:\tmp" }, { @"\", @"C:\git\runtime", @"C:\" }, { @"..\..\tmp\bar", @"C:\git\runtime", @"C:\tmp\bar" }, { @"..\..\.\bar", @"C:\git\runtime", @"C:\bar" }, { @"..\..\..\..\tmp\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\..\bar..\..\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\..\bar\..", @"C:\git\runtime", @"C:\" }, { @"\.\.\..\..\", @"C:\git\runtime", @"C:\" }, // Specific drive rooted { @"C:tmp\foo\..", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:tmp\foo\.", @"C:\git\runtime", @"C:\git\runtime\tmp\foo" }, { @"C:tmp\foo\..", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:tmp", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:", @"C:\git\runtime", @"C:\git\runtime" }, { @"C", @"C:\git\runtime", @"C:\git\runtime\C" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\foo\.", @"C:\git\runtime", @"Z:\tmp\foo" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, // Relative segments eating into the root { @"C:..\..\..\tmp\foo\..", @"C:\git\runtime", @"C:\tmp" }, { @"C:tmp\..\..\foo\.", @"C:\git\runtime", @"C:\git\foo" }, { @"C:..\..\tmp\foo\..", @"C:\git\runtime", @"C:\tmp" }, { @"C:tmp\..\", @"C:\git\runtime", @"C:\git\runtime\" }, { @"C:", @"C:\git\runtime", @"C:\git\runtime" }, { @"C", @"C:\git\runtime", @"C:\git\runtime\C" }, { @"C:tmp\..\..\..\..\foo\..", @"C:\git\runtime", @"C:\" }, { @"C:tmp\..\..\foo\.", @"C:\", @"C:\foo" }, { @"C:..\..\tmp\..\foo\..", @"C:\", @"C:\" }, { @"C:tmp\..\", @"C:\", @"C:\" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\foo\.", @"C:\git\runtime", @"Z:\tmp\foo" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, { @"Z:..\..\..\tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\..\..\foo\.", @"C:\git\runtime", @"Z:\foo" }, { @"Z:..\..\tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\..\", @"C:\git\runtime", @"Z:\" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, { @"Z:tmp\..\..\..\..\foo\..", @"C:\git\runtime", @"Z:\" }, { @"Z:tmp\..\..\foo\.", @"C:\", @"Z:\foo" }, { @"Z:..\..\tmp\..\foo\..", @"C:\", @"Z:\" }, { @"Z:tmp\..\", @"C:\", @"Z:\" }, }; [Theory, MemberData(nameof(GetFullPath_CommonRootedWindowsData))] public void GetFullPath_CommonUnRooted_Windows(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath)); } [Fact] public void GetFullPath_ThrowsOnEmbeddedNulls() { AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath("/gi\0t", @"C:\foo\bar")); } public static TheoryData<string, string> TestData_TrimEndingDirectorySeparator => new TheoryData<string, string> { { @"C:\folder\", @"C:\folder" }, { @"C:/folder/", @"C:/folder" }, { @"/folder/", @"/folder" }, { @"\folder\", @"\folder" }, { @"folder\", @"folder" }, { @"folder/", @"folder" }, { @"C:\", @"C:\" }, { @"C:/", @"C:/" }, { @"", @"" }, { @"/", @"/" }, { @"\", @"\" }, { @"\\server\share\", @"\\server\share" }, { @"\\server\share\folder\", @"\\server\share\folder" }, { @"\\?\C:\", @"\\?\C:\" }, { @"\\?\C:\folder\", @"\\?\C:\folder" }, { @"\\?\UNC\", @"\\?\UNC\" }, { @"\\?\UNC\a\", @"\\?\UNC\a\" }, { @"\\?\UNC\a\folder\", @"\\?\UNC\a\folder" }, { null, null } }; public static TheoryData<string, bool> TestData_EndsInDirectorySeparator => new TheoryData<string, bool> { { @"\", true }, { @"/", true }, { @"C:\folder\", true }, { @"C:/folder/", true }, { @"C:\", true }, { @"C:/", true }, { @"\\", true }, { @"//", true }, { @"\\server\share\", true }, { @"\\?\UNC\a\", true }, { @"\\?\C:\", true }, { @"\\?\UNC\", true }, { @"folder\", true }, { @"folder", false }, { @"", false }, { null, false } }; [Theory, MemberData(nameof(TestData_TrimEndingDirectorySeparator))] public void TrimEndingDirectorySeparator_String(string path, string expected) { string trimmed = Path.TrimEndingDirectorySeparator(path); Assert.Equal(expected, trimmed); Assert.Same(trimmed, Path.TrimEndingDirectorySeparator(trimmed)); } [Theory, MemberData(nameof(TestData_TrimEndingDirectorySeparator))] public void TrimEndingDirectorySeparator_ReadOnlySpan(string path, string expected) { ReadOnlySpan<char> trimmed = Path.TrimEndingDirectorySeparator(path.AsSpan()); PathAssert.Equal(expected, trimmed); PathAssert.Equal(trimmed, Path.TrimEndingDirectorySeparator(trimmed)); } [Theory, MemberData(nameof(TestData_EndsInDirectorySeparator))] public void EndsInDirectorySeparator_String(string path, bool expected) { Assert.Equal(expected, Path.EndsInDirectorySeparator(path)); } [Theory, MemberData(nameof(TestData_EndsInDirectorySeparator))] public void EndsInDirectorySeparator_ReadOnlySpan(string path, bool expected) { Assert.Equal(expected, Path.EndsInDirectorySeparator(path.AsSpan())); } // Windows-only P/Invoke to create 8.3 short names from long names [DllImport("kernel32.dll", EntryPoint = "GetShortPathNameW", CharSet = CharSet.Unicode)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.IO.Tests { [PlatformSpecific(TestPlatforms.Windows)] public class PathTests_Windows : PathTestsBase { [Fact] public void GetDirectoryName_DevicePath() { if (PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\?\C:", Path.GetDirectoryName(@"\\?\C:\foo")); } else { Assert.Equal(@"\\?\C:\", Path.GetDirectoryName(@"\\?\C:\foo")); } } [Theory, MemberData(nameof(TestData_GetDirectoryName_Windows))] public void GetDirectoryName(string path, string expected) { Assert.Equal(expected, Path.GetDirectoryName(path)); } [Theory, InlineData("B:", ""), InlineData("A:.", ".")] public static void GetFileName_Volume(string path, string expected) { // With a valid drive letter followed by a colon, we have a root, but only on Windows. Assert.Equal(expected, Path.GetFileName(path)); } [Theory, MemberData(nameof(TestData_GetPathRoot_Windows)), MemberData(nameof(TestData_GetPathRoot_Unc)), MemberData(nameof(TestData_GetPathRoot_DevicePaths))] public void GetPathRoot_Windows(string value, string expected) { Assert.Equal(expected, Path.GetPathRoot(value)); if (value.Length != expected.Length) { // The string overload normalizes the separators Assert.Equal(expected, Path.GetPathRoot(value.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))); // UNCs and device paths will have their semantics changed if we double up separators if (!value.StartsWith(@"\\")) Assert.Equal(expected, Path.GetPathRoot(value.Replace(@"\", @"\\"))); } } public static IEnumerable<string[]> GetTempPath_SetEnvVar_Data() { yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp" }; yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\" }; yield return new string[] { @"C:\", @"C:\" }; yield return new string[] { @"C:\tmp\", @"C:\tmp" }; yield return new string[] { @"C:\tmp\", @"C:\tmp\" }; } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void GetTempPath_SetEnvVar() { RemoteExecutor.Invoke(() => { foreach (string[] tempPath in GetTempPath_SetEnvVar_Data()) { GetTempPath_SetEnvVar_Helper("TMP", tempPath[0], tempPath[1]); } }).Dispose(); } [Theory, MemberData(nameof(TestData_Spaces))] public void GetFullPath_TrailingSpacesCut(string component) { // Windows cuts off any simple white space added to a path string path = "C:\\Test" + component; Assert.Equal("C:\\Test", Path.GetFullPath(path)); } [Fact] public void GetFullPath_NormalizedLongPathTooLong() { // Try out a long path that normalizes down to more than MaxPath string curDir = Directory.GetCurrentDirectory(); const int Iters = 260; var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4)); for (int i = 0; i < Iters; i++) { longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.'); } if (PathFeatures.AreAllLongPathsAvailable()) { // Now no longer throws unless over ~32K Assert.NotNull(Path.GetFullPath(longPath.ToString())); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString())); } } [Theory, InlineData(@"C:..."), InlineData(@"C:...\somedir"), InlineData(@"\.. .\"), InlineData(@"\. .\"), InlineData(@"\ .\")] public void GetFullPath_LegacyArgumentExceptionPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // We didn't allow these paths on < 4.6.2 AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { // These paths are legitimate Windows paths that can be created without extended syntax. // We now allow them through. Path.GetFullPath(path); } } [Fact] public void GetFullPath_MaxPathNotTooLong() { string value = @"C:\" + new string('a', 255) + @"\"; if (PathFeatures.AreAllLongPathsAvailable()) { // Shouldn't throw anymore Path.GetFullPath(value); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(value)); } } [Fact] public void GetFullPath_PathTooLong() { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\")); } [Theory, InlineData(@"C:\", @"C:\"), InlineData(@"C:\.", @"C:\"), InlineData(@"C:\..", @"C:\"), InlineData(@"C:\..\..", @"C:\"), InlineData(@"C:\A\..", @"C:\"), InlineData(@"C:\..\..\A\..", @"C:\")] public void GetFullPath_RelativeRoot(string path, string expected) { Assert.Equal(Path.GetFullPath(path), expected); } [Fact] public void GetFullPath_StrangeButLegalPaths() { // These are legal and creatable without using extended syntax if you use a trailing slash // (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from // being blocked when they hit these paths. string curDir = Directory.GetCurrentDirectory(); if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy path Path.GetFullePath() ignores . when there is less or more that two, when there is .. in the path it returns one directory up. Assert.Equal( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } else { Assert.NotEqual( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } } [Theory, InlineData(@"\\?\C:\ "), InlineData(@"\\?\C:\ \ "), InlineData(@"\\?\C:\ ."), InlineData(@"\\?\C:\ .."), InlineData(@"\\?\C:\..."), InlineData(@"\\?\GLOBALROOT\"), InlineData(@"\\?\"), InlineData(@"\\?\."), InlineData(@"\\?\.."), InlineData(@"\\?\\"), InlineData(@"\\?\C:\\"), InlineData(@"\\?\C:\|"), InlineData(@"\\?\C:\."), InlineData(@"\\?\C:\.."), InlineData(@"\\?\C:\Foo1\."), InlineData(@"\\?\C:\Foo2\.."), InlineData(@"\\?\UNC\"), InlineData(@"\\?\UNC\server1"), InlineData(@"\\?\UNC\server2\"), InlineData(@"\\?\UNC\server3\\"), InlineData(@"\\?\UNC\server4\.."), InlineData(@"\\?\UNC\server5\share\."), InlineData(@"\\?\UNC\server6\share\.."), InlineData(@"\\?\UNC\a\b\\"), InlineData(@"\\.\"), InlineData(@"\\.\."), InlineData(@"\\.\.."), InlineData(@"\\.\\"), InlineData(@"\\.\C:\\"), InlineData(@"\\.\C:\|"), InlineData(@"\\.\C:\."), InlineData(@"\\.\C:\.."), InlineData(@"\\.\C:\Foo1\."), InlineData(@"\\.\C:\Foo2\..")] public void GetFullPath_ValidExtendedPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy Path doesn't support any of these paths. AssertExtensions.ThrowsAny<ArgumentException, NotSupportedException>(() => Path.GetFullPath(path)); return; } // None of these should throw if (path.StartsWith(@"\\?\")) { Assert.Equal(path, Path.GetFullPath(path)); } else { Path.GetFullPath(path); } } [Theory, InlineData(@"\\.\UNC\"), InlineData(@"\\.\UNC\LOCALHOST"), InlineData(@"\\.\UNC\localHOST\"), InlineData(@"\\.\UNC\LOcaLHOST\\"), InlineData(@"\\.\UNC\lOCALHOST\.."), InlineData(@"\\.\UNC\LOCALhost\share\."), InlineData(@"\\.\UNC\loCALHOST\share\.."), InlineData(@"\\.\UNC\a\b\\")] public static void GetFullPath_ValidLegacy_ValidExtendedPaths(string path) { // should not throw Path.GetFullPath(path); } [Theory, // https://github.com/dotnet/runtime/issues/18664 InlineData(@"\\LOCALHOST\share\test.txt.~SS", @"\\LOCALHOST\share\test.txt.~SS"), InlineData(@"\\LOCALHOST\share1", @"\\LOCALHOST\share1"), InlineData(@"\\LOCALHOST\share3\dir", @"\\LOCALHOST\share3\dir"), InlineData(@"\\LOCALHOST\share4\.", @"\\LOCALHOST\share4"), InlineData(@"\\LOCALHOST\share5\..", @"\\LOCALHOST\share5"), InlineData(@"\\LOCALHOST\share6\ ", @"\\LOCALHOST\share6\"), InlineData(@"\\LOCALHOST\ share7\", @"\\LOCALHOST\ share7\"), InlineData(@"\\?\UNC\LOCALHOST\share8\test.txt.~SS", @"\\?\UNC\LOCALHOST\share8\test.txt.~SS"), InlineData(@"\\?\UNC\LOCALHOST\share9", @"\\?\UNC\LOCALHOST\share9"), InlineData(@"\\?\UNC\LOCALHOST\shareA\dir", @"\\?\UNC\LOCALHOST\shareA\dir"), InlineData(@"\\?\UNC\LOCALHOST\shareB\. ", @"\\?\UNC\LOCALHOST\shareB\. "), InlineData(@"\\?\UNC\LOCALHOST\shareC\.. ", @"\\?\UNC\LOCALHOST\shareC\.. "), InlineData(@"\\?\UNC\LOCALHOST\shareD\ ", @"\\?\UNC\LOCALHOST\shareD\ "), InlineData(@"\\.\UNC\LOCALHOST\ shareE\", @"\\.\UNC\LOCALHOST\ shareE\"), InlineData(@"\\.\UNC\LOCALHOST\shareF\test.txt.~SS", @"\\.\UNC\LOCALHOST\shareF\test.txt.~SS"), InlineData(@"\\.\UNC\LOCALHOST\shareG", @"\\.\UNC\LOCALHOST\shareG"), InlineData(@"\\.\UNC\LOCALHOST\shareH\dir", @"\\.\UNC\LOCALHOST\shareH\dir"), InlineData(@"\\.\UNC\LOCALHOST\shareK\ ", @"\\.\UNC\LOCALHOST\shareK\"), InlineData(@"\\.\UNC\LOCALHOST\ shareL\", @"\\.\UNC\LOCALHOST\ shareL\")] public void GetFullPath_UNC_Valid(string path, string expected) { if (path.StartsWith(@"\\?\") && PathFeatures.IsUsingLegacyPathNormalization()) { AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { Assert.Equal(expected, Path.GetFullPath(path)); } } [Theory, InlineData(@"\\.\UNC\LOCALHOST\shareI\. ", @"\\.\UNC\LOCALHOST\shareI\", @"\\.\UNC\LOCALHOST\shareI"), InlineData(@"\\.\UNC\LOCALHOST\shareJ\.. ", @"\\.\UNC\LOCALHOST\shareJ\", @"\\.\UNC\LOCALHOST")] public static void GetFullPath_Windows_UNC_Valid_LegacyPathSupport(string path, string normalExpected, string legacyExpected) { string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected; Assert.Equal(expected, Path.GetFullPath(path)); } [Fact] public static void GetFullPath_Windows_83Paths() { // Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened. string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt"); File.Create(tempFilePath).Dispose(); try { // Get its short name var sb = new StringBuilder(260); if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name { string shortName = sb.ToString(); // Make sure the shortened name expands back to the original one // Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides tempFilePath = tempFilePath.Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null); shortName = Path.GetFullPath(shortName).Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null); Assert.Equal(tempFilePath, shortName); // Should work with device paths that aren't well-formed extended syntax if (!PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName)); Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName)); // Shouldn't mess with well-formed extended syntax Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName)); } // Validate case where short name doesn't expand to a real file string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp"; Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName)); // Same thing, but with a long path that normalizes down to a short enough one const int Iters = 1000; var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2)); for (int i = 0; i < Iters; i++) { shortLongName.Append(Path.DirectorySeparatorChar).Append('.'); } Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString())); } } finally { File.Delete(tempFilePath); } } [Theory, MemberData(nameof(TestData_GetPathRoot_Windows)), MemberData(nameof(TestData_GetPathRoot_Unc)), MemberData(nameof(TestData_GetPathRoot_DevicePaths))] public void GetPathRoot_Span(string value, string expected) { Assert.Equal(expected, new string(Path.GetPathRoot(value.AsSpan()))); Assert.True(Path.IsPathRooted(value.AsSpan())); } [Theory, MemberData(nameof(TestData_UnicodeWhiteSpace))] public void GetFullPath_UnicodeWhiteSpaceStays(string component) { // When not .NET Framework full path should not cut off component string path = "C:\\Test" + component; Assert.Equal(path, Path.GetFullPath(path)); } [Theory, MemberData(nameof(TestData_Periods))] public void GetFullPath_TrailingPeriodsCut(string component) { // Windows cuts off any simple white space added to a path string path = "C:\\Test" + component; Assert.Equal("C:\\Test", Path.GetFullPath(path)); } public static TheoryData<string, string, string> GetFullPath_Windows_FullyQualified => new TheoryData<string, string, string> { { @"C:\git\runtime", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime\\\.", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"C:\git\runtime" }, { @"C:\somedir\..", @"C:\git\runtime", @"C:\" }, { @"C:\", @"C:\git\runtime", @"C:\" }, { @"..\..\..\..", @"C:\git\runtime", @"C:\" }, { @"C:\\\", @"C:\git\runtime", @"C:\" }, { @"C:\..\..\", @"C:\git\runtime", @"C:\" }, { @"C:\..\git\..\.\", @"C:\git\runtime", @"C:\" }, { @"C:\git\runtime\..\..\..\", @"C:\git\runtime", @"C:\" }, { @"C:\.\runtime\", @"C:\git\runtime", @"C:\runtime\" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_FullyQualified))] public void GetFullPath_BasicExpansions_Windows(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_PathIsDevicePath => new TheoryData<string, string, string> { // Device Paths with \\?\ wont get normalized i.e. relative segments wont get removed. { @"\\?\C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"\\?\C:\git\runtime.\.\.\.\.\." }, { @"\\?\C:\git\runtime\\\.", @"C:\git\runtime", @"\\?\C:\git\runtime\\\." }, { @"\\?\C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"\\?\C:\git\runtime\..\runtime\.\..\runtime" }, { @"\\?\\somedir\..", @"C:\git\runtime", @"\\?\\somedir\.." }, { @"\\?\", @"C:\git\runtime", @"\\?\" }, { @"\\?\..\..\..\..", @"C:\git\runtime", @"\\?\..\..\..\.." }, { @"\\?\\\\" , @"C:\git\runtime", @"\\?\\\\" }, { @"\\?\C:\Foo." , @"C:\git\runtime", @"\\?\C:\Foo." }, { @"\\?\C:\Foo " , @"C:\git\runtime", @"\\?\C:\Foo " }, { @"\\.\C:\git\runtime.\.\.\.\.\.", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\C:\git\runtime\\\.", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\C:\git\runtime\..\runtime\.\..\runtime", @"C:\git\runtime", @"\\.\C:\git\runtime" }, { @"\\.\\somedir\..", @"C:\git\runtime", @"\\.\" }, { @"\\.\", @"C:\git\runtime", @"\\.\" }, { @"\\.\..\..\..\..", @"C:\git\runtime", @"\\.\" }, { @"\\.\", @"C:\git\runtime", @"\\.\" }, { @"\\.\C:\Foo." , @"C:\git\runtime", @"\\.\C:\Foo" }, { @"\\.\C:\Foo " , @"C:\git\runtime", @"\\.\C:\Foo" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_PathIsDevicePath))] public void GetFullPath_BasicExpansions_Windows_PathIsDevicePath(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); Assert.Equal(expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(expected, Path.GetFullPath(path, @"\\?\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_UNC => new TheoryData<string, string, string> { { @"foo", @"", @"foo" }, { @"foo", @"server1", @"server1\foo" }, { @"\foo", @"server2", @"server2\foo" }, { @"foo", @"server3\", @"server3\foo" }, { @"..\foo", @"server4", @"server4\..\foo" }, { @".\foo", @"server5\share", @"server5\share\foo" }, { @"..\foo", @"server6\share", @"server6\share\foo" }, { @"\foo", @"a\b\\", @"a\b\foo" }, { @"foo", @"LOCALHOST\share8\test.txt.~SS", @"LOCALHOST\share8\test.txt.~SS\foo" }, { @"foo", @"LOCALHOST\share9", @"LOCALHOST\share9\foo" }, { @"foo", @"LOCALHOST\shareA\dir", @"LOCALHOST\shareA\dir\foo" }, { @". \foo", @"LOCALHOST\shareB\", @"LOCALHOST\shareB\. \foo" }, { @".. \foo", @"LOCALHOST\shareC\", @"LOCALHOST\shareC\.. \foo" }, { @" \foo", @"LOCALHOST\shareD\", @"LOCALHOST\shareD\ \foo" }, { "foo", @"LOCALHOST\ shareE\", @"LOCALHOST\ shareE\foo" }, { "foo", @"LOCALHOST\shareF\test.txt.~SS", @"LOCALHOST\shareF\test.txt.~SS\foo" }, { "foo", @"LOCALHOST\shareG", @"LOCALHOST\shareG\foo" }, { "foo", @"LOCALHOST\shareH\dir", @"LOCALHOST\shareH\dir\foo" }, { "foo", @"LOCALHOST\shareK\", @"LOCALHOST\shareK\foo" }, { "foo", @"LOCALHOST\ shareL\", @"LOCALHOST\ shareL\foo" }, // Relative segments eating into the root { @".\..\foo\..\", @"server\share", @"server\share\" }, { @"..\foo\tmp\..\..\", @"server\share", @"server\share\" }, { @"..\..\..\foo", @"server\share", @"server\share\foo" }, { @"..\foo\..\..\tmp", @"server\share", @"server\share\tmp" }, { @"..\foo", @"server\share", @"server\share\foo" }, { @"...\\foo", @"server\share", @"server\share\...\foo" }, { @"...\..\.\foo", @"server\share", @"server\share\foo" }, { @"..\foo\tmp\..\..\..\..\..\", @"server\share", @"server\share\" }, { @"..\..\..\..\foo", @"server\share", @"server\share\foo" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_UNC))] public void GetFullPath_CommonUnc_Windows(string path, string basePath, string expected) { Assert.Equal(@"\\" + expected, Path.GetFullPath(path, @"\\" + basePath)); Assert.Equal(@"\\.\UNC\" + expected, Path.GetFullPath(path, @"\\.\UNC\" + basePath)); Assert.Equal(@"\\?\UNC\" + expected, Path.GetFullPath(path, @"\\?\UNC\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_Windows_CommonDevicePaths => new TheoryData<string, string, string> { // Device paths { "foo", @"C:\ ", @"C:\ \foo" }, { @" \ \foo", @"C:\", @"C:\ \ \foo" }, { @" .\foo", @"C:\", @"C:\ .\foo" }, { @" ..\foo", @"C:\", @"C:\ ..\foo" }, { @"...\foo", @"C:\", @"C:\...\foo" }, { @"foo", @"C:\\", @"C:\foo" }, { @"foo.", @"C:\\", @"C:\foo." }, { @"foo \git", @"C:\\", @"C:\foo \git" }, { @"foo. \git", @"C:\\", @"C:\foo. \git" }, { @" foo \git", @"C:\\", @"C:\ foo \git" }, { @"foo ", @"C:\\", @"C:\foo " }, { @"|\foo", @"C:\", @"C:\|\foo" }, { @".\foo", @"C:\", @"C:\foo" }, { @"..\foo", @"C:\", @"C:\foo" }, { @"\Foo1\.\foo", @"C:\", @"C:\Foo1\foo" }, { @"\Foo2\..\foo", @"C:\", @"C:\foo" }, { @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"foo", @"", @"foo" }, { @".\foo", @"", @".\foo" }, { @"..\foo", @"", @"..\foo" }, { @"C:", @"", @"C:\"}, // Relative segments eating into the root { @"foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"..\..\foo\..\..\", @"", @"..\" }, { @".\..\..\..\..\foo", @"", @".\foo" }, { @"..\foo\..\..\..\", @"", @"..\" }, { @"\.\.\..\", @"C:\", @"C:\"}, { @"..\..\..\foo", @"GLOBALROOT\", @"GLOBALROOT\foo" }, { @"foo\..\..\", @"", @"foo\" }, { @".\.\foo\..\", @"", @".\" }, }; [Theory, MemberData(nameof(GetFullPath_Windows_CommonDevicePaths))] public void GetFullPath_CommonDevice_Windows(string path, string basePath, string expected) { Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath)); } public static TheoryData<string, string, string> GetFullPath_CommonRootedWindowsData => new TheoryData<string, string, string> { { "", @"C:\git\runtime", @"C:\git\runtime" }, { "..", @"C:\git\runtime", @"C:\git" }, // Current drive rooted { @"\tmp\bar", @"C:\git\runtime", @"C:\tmp\bar" }, { @"\.\bar", @"C:\git\runtime", @"C:\bar" }, { @"\tmp\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\bar\..", @"C:\git\runtime", @"C:\tmp" }, { @"\tmp\bar\..", @"C:\git\runtime", @"C:\tmp" }, { @"\", @"C:\git\runtime", @"C:\" }, { @"..\..\tmp\bar", @"C:\git\runtime", @"C:\tmp\bar" }, { @"..\..\.\bar", @"C:\git\runtime", @"C:\bar" }, { @"..\..\..\..\tmp\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\..\bar..\..\..", @"C:\git\runtime", @"C:\" }, { @"\tmp\..\bar\..", @"C:\git\runtime", @"C:\" }, { @"\.\.\..\..\", @"C:\git\runtime", @"C:\" }, // Specific drive rooted { @"C:tmp\foo\..", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:tmp\foo\.", @"C:\git\runtime", @"C:\git\runtime\tmp\foo" }, { @"C:tmp\foo\..", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:tmp", @"C:\git\runtime", @"C:\git\runtime\tmp" }, { @"C:", @"C:\git\runtime", @"C:\git\runtime" }, { @"C", @"C:\git\runtime", @"C:\git\runtime\C" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\foo\.", @"C:\git\runtime", @"Z:\tmp\foo" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, // Relative segments eating into the root { @"C:..\..\..\tmp\foo\..", @"C:\git\runtime", @"C:\tmp" }, { @"C:tmp\..\..\foo\.", @"C:\git\runtime", @"C:\git\foo" }, { @"C:..\..\tmp\foo\..", @"C:\git\runtime", @"C:\tmp" }, { @"C:tmp\..\", @"C:\git\runtime", @"C:\git\runtime\" }, { @"C:", @"C:\git\runtime", @"C:\git\runtime" }, { @"C", @"C:\git\runtime", @"C:\git\runtime\C" }, { @"C:tmp\..\..\..\..\foo\..", @"C:\git\runtime", @"C:\" }, { @"C:tmp\..\..\foo\.", @"C:\", @"C:\foo" }, { @"C:..\..\tmp\..\foo\..", @"C:\", @"C:\" }, { @"C:tmp\..\", @"C:\", @"C:\" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\foo\.", @"C:\git\runtime", @"Z:\tmp\foo" }, { @"Z:tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, { @"Z:..\..\..\tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\..\..\foo\.", @"C:\git\runtime", @"Z:\foo" }, { @"Z:..\..\tmp\foo\..", @"C:\git\runtime", @"Z:\tmp" }, { @"Z:tmp\..\", @"C:\git\runtime", @"Z:\" }, { @"Z:", @"C:\git\runtime", @"Z:\" }, { @"Z", @"C:\git\runtime", @"C:\git\runtime\Z" }, { @"Z:tmp\..\..\..\..\foo\..", @"C:\git\runtime", @"Z:\" }, { @"Z:tmp\..\..\foo\.", @"C:\", @"Z:\foo" }, { @"Z:..\..\tmp\..\foo\..", @"C:\", @"Z:\" }, { @"Z:tmp\..\", @"C:\", @"Z:\" }, }; [Theory, MemberData(nameof(GetFullPath_CommonRootedWindowsData))] public void GetFullPath_CommonUnRooted_Windows(string path, string basePath, string expected) { Assert.Equal(expected, Path.GetFullPath(path, basePath)); Assert.Equal(@"\\.\" + expected, Path.GetFullPath(path, @"\\.\" + basePath)); Assert.Equal(@"\\?\" + expected, Path.GetFullPath(path, @"\\?\" + basePath)); } [Fact] public void GetFullPath_ThrowsOnEmbeddedNulls() { AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath("/gi\0t", @"C:\foo\bar")); } public static TheoryData<string, string> TestData_TrimEndingDirectorySeparator => new TheoryData<string, string> { { @"C:\folder\", @"C:\folder" }, { @"C:/folder/", @"C:/folder" }, { @"/folder/", @"/folder" }, { @"\folder\", @"\folder" }, { @"folder\", @"folder" }, { @"folder/", @"folder" }, { @"C:\", @"C:\" }, { @"C:/", @"C:/" }, { @"", @"" }, { @"/", @"/" }, { @"\", @"\" }, { @"\\server\share\", @"\\server\share" }, { @"\\server\share\folder\", @"\\server\share\folder" }, { @"\\?\C:\", @"\\?\C:\" }, { @"\\?\C:\folder\", @"\\?\C:\folder" }, { @"\\?\UNC\", @"\\?\UNC\" }, { @"\\?\UNC\a\", @"\\?\UNC\a\" }, { @"\\?\UNC\a\folder\", @"\\?\UNC\a\folder" }, { null, null } }; public static TheoryData<string, bool> TestData_EndsInDirectorySeparator => new TheoryData<string, bool> { { @"\", true }, { @"/", true }, { @"C:\folder\", true }, { @"C:/folder/", true }, { @"C:\", true }, { @"C:/", true }, { @"\\", true }, { @"//", true }, { @"\\server\share\", true }, { @"\\?\UNC\a\", true }, { @"\\?\C:\", true }, { @"\\?\UNC\", true }, { @"folder\", true }, { @"folder", false }, { @"", false }, { null, false } }; [Theory, MemberData(nameof(TestData_TrimEndingDirectorySeparator))] public void TrimEndingDirectorySeparator_String(string path, string expected) { string trimmed = Path.TrimEndingDirectorySeparator(path); Assert.Equal(expected, trimmed); Assert.Same(trimmed, Path.TrimEndingDirectorySeparator(trimmed)); } [Theory, MemberData(nameof(TestData_TrimEndingDirectorySeparator))] public void TrimEndingDirectorySeparator_ReadOnlySpan(string path, string expected) { ReadOnlySpan<char> trimmed = Path.TrimEndingDirectorySeparator(path.AsSpan()); PathAssert.Equal(expected, trimmed); PathAssert.Equal(trimmed, Path.TrimEndingDirectorySeparator(trimmed)); } [Theory, MemberData(nameof(TestData_EndsInDirectorySeparator))] public void EndsInDirectorySeparator_String(string path, bool expected) { Assert.Equal(expected, Path.EndsInDirectorySeparator(path)); } [Theory, MemberData(nameof(TestData_EndsInDirectorySeparator))] public void EndsInDirectorySeparator_ReadOnlySpan(string path, bool expected) { Assert.Equal(expected, Path.EndsInDirectorySeparator(path.AsSpan())); } // Windows-only P/Invoke to create 8.3 short names from long names [DllImport("kernel32.dll", EntryPoint = "GetShortPathNameW", CharSet = CharSet.Unicode)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer); } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <FeatureGenericMath>false</FeatureGenericMath> <NoWarn>$(NoWarn),1718,SYSLIB0013</NoWarn> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <Nullable>disable</Nullable> <!-- Disable nullability public only feature for NullabilityInfoContextTests --> <Features>$(Features.Replace('nullablePublicOnly', '')</Features> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(FeatureGenericMath)' == 'true'">$(DefineConstants);FEATURE_GENERIC_MATH</DefineConstants> </PropertyGroup> <ItemGroup> <RdXmlFile Include="default.rd.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\EnumTypes.cs" Link="Common\System\EnumTypes.cs" /> <Compile Include="$(CommonTestPath)System\MockType.cs" Link="Common\System\MockType.cs" /> <Compile Include="$(CommonTestPath)System\Collections\CollectionAsserts.cs" Link="Common\System\Collections\CollectionAsserts.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.Generic.Tests.cs" Link="Common\System\Collections\ICollection.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.Generic.Tests.cs" Link="Common\System\Collections\IList.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.Generic.cs" Link="Common\System\Collections\TestBase.Generic.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.NonGeneric.cs" Link="Common\System\Collections\TestBase.NonGeneric.cs" /> <Compile Include="$(CommonTestPath)Tests\System\StringTests.cs" Link="Common\System\StringTests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IDictionary.NonGeneric.Tests.cs" Link="Common\System\Collections\IDictionary.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.NonGeneric.Tests.cs" Link="Common\System\Collections\IList.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.NonGeneric.Tests.cs" Link="Common\System\Collections\ICollection.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.NonGeneric.Tests.cs" Link="Common\System\Collections\IEnumerable.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="System\AccessViolationExceptionTests.cs" /> <Compile Include="System\ActivatorTests.cs" /> <Compile Include="System\ActivatorTests.Generic.cs" /> <Compile Include="System\AmbiguousImplementationExceptionTests.cs" /> <Compile Include="System\ArgumentExceptionTests.cs" /> <Compile Include="System\ArgumentNullExceptionTests.cs" /> <Compile Include="System\ArgumentOutOfRangeExceptionTests.cs" /> <Compile Include="System\ArithmeticExceptionTests.cs" /> <Compile Include="System\ArrayTests.cs" /> <Compile Include="System\ArrayEnumeratorTests.cs" /> <Compile Include="System\ArraySegmentTests.cs" /> <Compile Include="System\ArrayTypeMismatchExceptionTests.cs" /> <Compile Include="System\ApplicationExceptionTests.cs" /> <Compile Include="System\AttributeTests.cs" /> <Compile Include="System\Attributes.cs" /> <Compile Include="System\AttributeUsageAttributeTests.cs" /> <Compile Include="System\BadImageFormatExceptionTests.cs" /> <Compile Include="System\BooleanTests.cs" /> <Compile Include="System\BufferTests.cs" /> <Compile Include="System\ByteTests.cs" /> <Compile Include="System\CharTests.cs" /> <Compile Include="System\CLSCompliantAttributeTests.cs" /> <Compile Include="System\DateOnlyTests.cs" /> <Compile Include="System\DateTimeTests.cs" /> <Compile Include="System\DateTimeOffsetTests.cs" /> <Compile Include="System\DBNullTests.cs" /> <Compile Include="System\DecimalTests.cs" /> <Compile Include="System\DelegateTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\StringSyntaxAttributeTests.cs" /> <Compile Include="System\DivideByZeroExceptionTests.cs" /> <Compile Include="System\DoubleTests.cs" /> <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" /> <Compile Include="System\EntryPointNotFoundExceptionTests.cs" /> <Compile Include="System\EnumTests.cs" /> <Compile Include="System\ExceptionTests.cs" /> <Compile Include="System\Exception.Helpers.cs" /> <Compile Include="System\ExecutionEngineExceptionTests.cs" /> <Compile Include="System\ExternalExceptionTests.cs" /> <Compile Include="System\EventArgsTests.cs" /> <Compile Include="System\FieldAccessExceptionTests.cs" /> <Compile Include="System\FlagsAttributeTests.cs" /> <Compile Include="System\FormattableStringTests.cs" /> <Compile Include="System\FormatExceptionTests.cs" /> <Compile Include="System\GCTests.cs" /> <Compile Include="System\GuidTests.cs" /> <Compile Include="System\HalfTests.cs" /> <Compile Include="System\HandleTests.cs" /> <Compile Include="System\HashCodeTests.cs" /> <Compile Include="System\IndexOutOfRangeExceptionTests.cs" /> <Compile Include="System\IndexTests.cs" /> <Compile Include="System\Int16Tests.cs" /> <Compile Include="System\Int32Tests.cs" /> <Compile Include="System\Int64Tests.cs" /> <Compile Include="System\IntPtrTests.cs" /> <Compile Include="System\InvalidCastExceptionTests.cs" /> <Compile Include="System\InvalidOperationExceptionTests.cs" /> <Compile Include="System\InvalidProgramExceptionTests.cs" /> <Compile Include="System\LazyTests.cs" /> <Compile Include="System\LazyOfTMetadataTests.cs" /> <Compile Include="System\MarshalByRefObjectTests.cs" /> <Compile Include="System\MemberAccessExceptionTests.cs" /> <Compile Include="System\MethodAccessExceptionTests.cs" /> <Compile Include="System\MissingFieldExceptionTests.cs" /> <Compile Include="System\MissingMemberExceptionTests.cs" /> <Compile Include="System\MissingMethodExceptionTests.cs" /> <Compile Include="System\MulticastDelegateTests.cs" /> <Compile Include="System\NotFiniteNumberExceptionTests.cs" /> <Compile Include="System\NotImplementedExceptionTests.cs" /> <Compile Include="System\NotSupportedExceptionTests.cs" /> <Compile Include="System\NullableMetadataTests.cs" /> <Compile Include="System\NullableTests.cs" /> <Compile Include="System\NullReferenceExceptionTests.cs" /> <Compile Include="System\ObjectTests.cs" /> <Compile Include="System\ObjectDisposedExceptionTests.cs" /> <Compile Include="System\ObsoleteAttributeTests.cs" /> <Compile Include="System\OutOfMemoryExceptionTests.cs" /> <Compile Include="System\OverflowExceptionTests.cs" /> <Compile Include="System\ParamArrayAttributeTests.cs" /> <Compile Include="System\PlatformNotSupportedExceptionTests.cs" /> <Compile Include="System\PseudoCustomAttributeTests.cs" /> <Compile Include="System\RangeTests.cs" /> <Compile Include="System\RankExceptionTests.cs" /> <Compile Include="System\Reflection\NullabilityInfoContextTests.cs" /> <Compile Include="System\SByteTests.cs" /> <Compile Include="System\SingleTests.cs" /> <Compile Include="System\StackOverflowExceptionTests.cs" /> <Compile Include="System\String.SplitTests.cs" /> <Compile Include="System\StringComparerTests.cs" /> <Compile Include="System\StringGetHashCodeTests.cs" /> <Compile Include="System\StringSplitExtensions.cs" /> <Compile Include="System\StringTests.cs" /> <Compile Include="System\SystemExceptionTests.cs" /> <Compile Include="System\TimeOnlyTests.cs" /> <Compile Include="System\TimeoutExceptionTests.cs" /> <Compile Include="System\TimeSpanTests.cs" /> <Compile Include="System\TimeZoneInfoTests.cs" /> <Compile Include="System\TimeZoneTests.cs" /> <Compile Include="System\TimeZoneNotFoundExceptionTests.cs" /> <Compile Include="System\TypedReferenceTests.cs" /> <Compile Include="System\TypeLoadExceptionTests.cs" /> <Compile Include="System\TypeUnloadedExceptionTests.cs" /> <Compile Include="System\TupleTests.cs" /> <Compile Include="System\UseResourceKeysTest.cs" /> <Compile Include="System\UInt16Tests.cs" /> <Compile Include="System\UInt32Tests.cs" /> <Compile Include="System\UInt64Tests.cs" /> <Compile Include="System\UIntPtrTests.cs" /> <Compile Include="System\UnitySerializationHolderTests.cs" /> <Compile Include="System\Uri.CreateStringTests.cs" /> <Compile Include="System\Uri.CreateUriTests.cs" /> <Compile Include="System\Uri.MethodsTests.cs" /> <Compile Include="System\ValueTypeTests.cs" /> <Compile Include="System\VersionTests.cs" /> <Compile Include="System\WeakReferenceTests.cs" /> <Compile Include="System\AppContext\AppContextTests.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.Validation.cs" /> <Compile Include="System\Collections\Generic\KeyNotFoundExceptionTests.cs" /> <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" /> <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" /> <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" /> <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" /> <Compile Include="System\Diagnostics\ConditionalAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\ConstantExpectedAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicallyAccessedMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicDependencyAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresAssemblyFilesAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresDynamicCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\SetsRequiredMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttributeTests.cs" /> <Compile Include="System\Diagnostics\StackTraceHiddenAttributeTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\EndOfStreamExceptionTests.cs" /> <Compile Include="System\IO\Exceptions.HResults.cs" /> <Compile Include="System\IO\FileLoadExceptionTests.cs" /> <Compile Include="System\IO\FileLoadException.InteropTests.cs" /> <Compile Include="System\IO\FileNotFoundExceptionTests.cs" /> <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\IOExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongException.InteropTests.cs" /> <Compile Include="System\Reflection\AssemblyAlgorithmIdAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCompanyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyConfigurationAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCopyrightAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCultureAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDefaultAliasAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDelaySignAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDescriptionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFileVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFlagsAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyInformationalVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyFileAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyNameAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyMetadataAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyProductAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblySignatureKeyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTitleAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTrademarkAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyVersionAttributeTests.cs" /> <Compile Include="System\Reflection\BindingFlagsDoNotWrap.cs" /> <Compile Include="System\Reflection\CustomAttributeDataTests.cs" /> <Compile Include="System\Reflection\CustomAttributesTestData.cs" /> <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" /> <Compile Include="System\Reflection\DefaultMemberAttributeTests.cs" /> <Compile Include="System\Reflection\InvokeRefReturn.cs" /> <Compile Include="System\Reflection\InvokeWithRefLikeArgs.cs" /> <Compile Include="System\Reflection\IsCollectibleTests.cs" /> <Compile Include="System\Reflection\MethodBaseTests.cs" /> <Compile Include="System\Reflection\MethodBodyTests.cs" /> <Compile Include="System\Reflection\ModuleTests.cs" /> <Compile Include="System\Reflection\ObfuscateAssemblyAttributeTests.cs" /> <Compile Include="System\Reflection\ObfuscationAttributeTests.cs" /> <Compile Include="System\Reflection\PointerTests.cs" /> <Compile Include="System\Reflection\ReflectionCacheTests.cs" /> <Compile Include="System\Reflection\ReflectionContextTests.cs" /> <Compile Include="System\Reflection\ReflectionTypeLoadExceptionTests.cs" /> <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" /> <Compile Include="System\Reflection\TypeDelegatorTests.cs" /> <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" /> <Compile Include="System\Reflection\TypeTests.GetMember.cs" /> <Compile Include="System\Runtime\DependentHandleTests.cs" /> <Compile Include="System\Runtime\JitInfoTests.cs" /> <Compile Include="System\Runtime\MemoryFailPointTests.cs" /> <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\AttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" /> <Compile Include="System\Runtime\CompilerServices\DefaultInterpolatedStringHandlerTests.cs" /> <Compile Include="System\Runtime\CompilerServices\FormattableStringFactoryTests.cs" /> <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" /> <Compile Include="System\Runtime\ConstrainedExecution\PrePrepareMethodAttributeTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" /> <Compile Include="System\Runtime\Serialization\OptionalFieldAttributeTests.cs" /> <Compile Include="System\Runtime\Serialization\SerializationExceptionTests.cs" /> <Compile Include="System\Runtime\Serialization\StreamingContextTests.cs" /> <Compile Include="System\Runtime\Versioning\OSPlatformAttributeTests.cs" /> <Compile Include="System\Runtime\Versioning\RequiresPreviewFeaturesAttributeTests.cs" /> <Compile Include="System\Security\SecurityAttributeTests.cs" /> <Compile Include="System\Security\SecurityExceptionTests.cs" /> <Compile Include="System\Text\StringBuilderTests.cs" /> <Compile Include="System\Text\StringBuilderInterpolationTests.cs" /> <Compile Include="System\Threading\PeriodicTimerTests.cs" /> <Compile Include="System\Threading\WaitHandleTests.cs" /> <Compile Include="System\Type\TypePropertyTests.cs" /> <Compile Include="System\Type\TypeTests.cs" /> <Compile Include="System\Type\TypeTests.Get.cs" /> <Compile Include="$(CommonTestPath)System\RandomDataGenerator.cs" Link="Common\System\RandomDataGenerator.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="System\ExitCodeTests.Unix.cs" /> </ItemGroup> <ItemGroup Condition="'$(FeatureGenericMath)' == 'true'"> <Compile Include="System\ByteTests.GenericMath.cs" /> <Compile Include="System\CharTests.GenericMath.cs" /> <Compile Include="System\DoubleTests.GenericMath.cs" /> <Compile Include="System\GenericMathHelpers.cs" /> <Compile Include="System\HalfTests.GenericMath.cs" /> <Compile Include="System\Int16Tests.GenericMath.cs" /> <Compile Include="System\Int32Tests.GenericMath.cs" /> <Compile Include="System\Int64Tests.GenericMath.cs" /> <Compile Include="System\IntPtrTests.GenericMath.cs" /> <Compile Include="System\SByteTests.GenericMath.cs" /> <Compile Include="System\SingleTests.GenericMath.cs" /> <Compile Include="System\UInt16Tests.GenericMath.cs" /> <Compile Include="System\UInt32Tests.GenericMath.cs" /> <Compile Include="System\UInt64Tests.GenericMath.cs" /> <Compile Include="System\UIntPtrTests.GenericMath.cs" /> </ItemGroup> <ItemGroup> <Compile Include="System\Reflection\SignatureTypes.cs" /> <Compile Include="System\Runtime\CompilerServices\CallerArgumentExpressionAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\MethodImplAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeFeatureTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeWrappedExceptionTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\ExceptionDispatchInfoTests.cs" /> <Compile Include="System\Text\ASCIIUtilityTests.cs" /> <Compile Include="System\Text\EncodingTests.cs" /> <Compile Include="System\Text\RuneTests.cs" /> <Compile Include="System\Text\RuneTests.TestData.cs" /> <Compile Include="System\Text\Unicode\Utf16UtilityTests.ValidateChars.cs" /> <Compile Include="System\Text\Unicode\Utf8Tests.cs" /> <Compile Include="System\Text\Unicode\Utf8UtilityTests.ValidateBytes.cs" /> <Compile Include="System\ArgIteratorTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealFormatterTestsBase.cs" Link="System\RealFormatterTestsBase.cs" /> <Compile Include="System\RealFormatterTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealParserTestsBase.cs" Link="System\RealParserTestsBase.cs" /> <Compile Include="System\RealParserTests.cs" /> <TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Serialization.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs" /> <EmbeddedResource Include="System\Reflection\EmbeddedImage.png"> <LogicalName>System.Reflection.Tests.EmbeddedImage.png</LogicalName> </EmbeddedResource> <EmbeddedResource Include="System\Reflection\EmbeddedTextFile.txt"> <LogicalName>System.Reflection.Tests.EmbeddedTextFile.txt</LogicalName> </EmbeddedResource> <Compile Include="$(CommonTestPath)System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" Link="Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="System.Runtime.Numerics.TestData" Version="$(SystemRuntimeNumericsTestDataVersion)" GeneratePathProperty="true" /> <ProjectReference Include="TestLoadAssembly\TestLoadAssembly.csproj" /> <ProjectReference Include="TestCollectibleAssembly\TestCollectibleAssembly.csproj" /> <ProjectReference Include="TestModule\System.Reflection.TestModule.ilproj" /> <ProjectReference Include="TestStructs\System.TestStructs.ilproj" /> <ProjectReference Include="$(CommonTestPath)TestUtilities.Unicode\TestUtilities.Unicode.csproj" /> <!-- Used during reflection in tests. --> <ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Threading.AccessControl\src\System.Threading.AccessControl.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <FeatureGenericMath>false</FeatureGenericMath> <NoWarn>$(NoWarn),1718,SYSLIB0013</NoWarn> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <Nullable>disable</Nullable> <!-- Disable nullability public only feature for NullabilityInfoContextTests --> <Features>$(Features.Replace('nullablePublicOnly', '')</Features> <EnableRegexGenerator>true</EnableRegexGenerator> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(FeatureGenericMath)' == 'true'">$(DefineConstants);FEATURE_GENERIC_MATH</DefineConstants> </PropertyGroup> <ItemGroup> <RdXmlFile Include="default.rd.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\EnumTypes.cs" Link="Common\System\EnumTypes.cs" /> <Compile Include="$(CommonTestPath)System\MockType.cs" Link="Common\System\MockType.cs" /> <Compile Include="$(CommonTestPath)System\Collections\CollectionAsserts.cs" Link="Common\System\Collections\CollectionAsserts.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.Generic.Tests.cs" Link="Common\System\Collections\ICollection.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.Generic.Tests.cs" Link="Common\System\Collections\IList.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.Generic.cs" Link="Common\System\Collections\TestBase.Generic.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.NonGeneric.cs" Link="Common\System\Collections\TestBase.NonGeneric.cs" /> <Compile Include="$(CommonTestPath)Tests\System\StringTests.cs" Link="Common\System\StringTests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IDictionary.NonGeneric.Tests.cs" Link="Common\System\Collections\IDictionary.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.NonGeneric.Tests.cs" Link="Common\System\Collections\IList.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.NonGeneric.Tests.cs" Link="Common\System\Collections\ICollection.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.NonGeneric.Tests.cs" Link="Common\System\Collections\IEnumerable.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="System\AccessViolationExceptionTests.cs" /> <Compile Include="System\ActivatorTests.cs" /> <Compile Include="System\ActivatorTests.Generic.cs" /> <Compile Include="System\AmbiguousImplementationExceptionTests.cs" /> <Compile Include="System\ArgumentExceptionTests.cs" /> <Compile Include="System\ArgumentNullExceptionTests.cs" /> <Compile Include="System\ArgumentOutOfRangeExceptionTests.cs" /> <Compile Include="System\ArithmeticExceptionTests.cs" /> <Compile Include="System\ArrayTests.cs" /> <Compile Include="System\ArrayEnumeratorTests.cs" /> <Compile Include="System\ArraySegmentTests.cs" /> <Compile Include="System\ArrayTypeMismatchExceptionTests.cs" /> <Compile Include="System\ApplicationExceptionTests.cs" /> <Compile Include="System\AttributeTests.cs" /> <Compile Include="System\Attributes.cs" /> <Compile Include="System\AttributeUsageAttributeTests.cs" /> <Compile Include="System\BadImageFormatExceptionTests.cs" /> <Compile Include="System\BooleanTests.cs" /> <Compile Include="System\BufferTests.cs" /> <Compile Include="System\ByteTests.cs" /> <Compile Include="System\CharTests.cs" /> <Compile Include="System\CLSCompliantAttributeTests.cs" /> <Compile Include="System\DateOnlyTests.cs" /> <Compile Include="System\DateTimeTests.cs" /> <Compile Include="System\DateTimeOffsetTests.cs" /> <Compile Include="System\DBNullTests.cs" /> <Compile Include="System\DecimalTests.cs" /> <Compile Include="System\DelegateTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\StringSyntaxAttributeTests.cs" /> <Compile Include="System\DivideByZeroExceptionTests.cs" /> <Compile Include="System\DoubleTests.cs" /> <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" /> <Compile Include="System\EntryPointNotFoundExceptionTests.cs" /> <Compile Include="System\EnumTests.cs" /> <Compile Include="System\ExceptionTests.cs" /> <Compile Include="System\Exception.Helpers.cs" /> <Compile Include="System\ExecutionEngineExceptionTests.cs" /> <Compile Include="System\ExternalExceptionTests.cs" /> <Compile Include="System\EventArgsTests.cs" /> <Compile Include="System\FieldAccessExceptionTests.cs" /> <Compile Include="System\FlagsAttributeTests.cs" /> <Compile Include="System\FormattableStringTests.cs" /> <Compile Include="System\FormatExceptionTests.cs" /> <Compile Include="System\GCTests.cs" /> <Compile Include="System\GuidTests.cs" /> <Compile Include="System\HalfTests.cs" /> <Compile Include="System\HandleTests.cs" /> <Compile Include="System\HashCodeTests.cs" /> <Compile Include="System\IndexOutOfRangeExceptionTests.cs" /> <Compile Include="System\IndexTests.cs" /> <Compile Include="System\Int16Tests.cs" /> <Compile Include="System\Int32Tests.cs" /> <Compile Include="System\Int64Tests.cs" /> <Compile Include="System\IntPtrTests.cs" /> <Compile Include="System\InvalidCastExceptionTests.cs" /> <Compile Include="System\InvalidOperationExceptionTests.cs" /> <Compile Include="System\InvalidProgramExceptionTests.cs" /> <Compile Include="System\LazyTests.cs" /> <Compile Include="System\LazyOfTMetadataTests.cs" /> <Compile Include="System\MarshalByRefObjectTests.cs" /> <Compile Include="System\MemberAccessExceptionTests.cs" /> <Compile Include="System\MethodAccessExceptionTests.cs" /> <Compile Include="System\MissingFieldExceptionTests.cs" /> <Compile Include="System\MissingMemberExceptionTests.cs" /> <Compile Include="System\MissingMethodExceptionTests.cs" /> <Compile Include="System\MulticastDelegateTests.cs" /> <Compile Include="System\NotFiniteNumberExceptionTests.cs" /> <Compile Include="System\NotImplementedExceptionTests.cs" /> <Compile Include="System\NotSupportedExceptionTests.cs" /> <Compile Include="System\NullableMetadataTests.cs" /> <Compile Include="System\NullableTests.cs" /> <Compile Include="System\NullReferenceExceptionTests.cs" /> <Compile Include="System\ObjectTests.cs" /> <Compile Include="System\ObjectDisposedExceptionTests.cs" /> <Compile Include="System\ObsoleteAttributeTests.cs" /> <Compile Include="System\OutOfMemoryExceptionTests.cs" /> <Compile Include="System\OverflowExceptionTests.cs" /> <Compile Include="System\ParamArrayAttributeTests.cs" /> <Compile Include="System\PlatformNotSupportedExceptionTests.cs" /> <Compile Include="System\PseudoCustomAttributeTests.cs" /> <Compile Include="System\RangeTests.cs" /> <Compile Include="System\RankExceptionTests.cs" /> <Compile Include="System\Reflection\NullabilityInfoContextTests.cs" /> <Compile Include="System\SByteTests.cs" /> <Compile Include="System\SingleTests.cs" /> <Compile Include="System\StackOverflowExceptionTests.cs" /> <Compile Include="System\String.SplitTests.cs" /> <Compile Include="System\StringComparerTests.cs" /> <Compile Include="System\StringGetHashCodeTests.cs" /> <Compile Include="System\StringSplitExtensions.cs" /> <Compile Include="System\StringTests.cs" /> <Compile Include="System\SystemExceptionTests.cs" /> <Compile Include="System\TimeOnlyTests.cs" /> <Compile Include="System\TimeoutExceptionTests.cs" /> <Compile Include="System\TimeSpanTests.cs" /> <Compile Include="System\TimeZoneInfoTests.cs" /> <Compile Include="System\TimeZoneTests.cs" /> <Compile Include="System\TimeZoneNotFoundExceptionTests.cs" /> <Compile Include="System\TypedReferenceTests.cs" /> <Compile Include="System\TypeLoadExceptionTests.cs" /> <Compile Include="System\TypeUnloadedExceptionTests.cs" /> <Compile Include="System\TupleTests.cs" /> <Compile Include="System\UseResourceKeysTest.cs" /> <Compile Include="System\UInt16Tests.cs" /> <Compile Include="System\UInt32Tests.cs" /> <Compile Include="System\UInt64Tests.cs" /> <Compile Include="System\UIntPtrTests.cs" /> <Compile Include="System\UnitySerializationHolderTests.cs" /> <Compile Include="System\Uri.CreateStringTests.cs" /> <Compile Include="System\Uri.CreateUriTests.cs" /> <Compile Include="System\Uri.MethodsTests.cs" /> <Compile Include="System\ValueTypeTests.cs" /> <Compile Include="System\VersionTests.cs" /> <Compile Include="System\WeakReferenceTests.cs" /> <Compile Include="System\AppContext\AppContextTests.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.Validation.cs" /> <Compile Include="System\Collections\Generic\KeyNotFoundExceptionTests.cs" /> <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" /> <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" /> <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" /> <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" /> <Compile Include="System\Diagnostics\ConditionalAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\ConstantExpectedAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicallyAccessedMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicDependencyAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresAssemblyFilesAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresDynamicCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\SetsRequiredMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttributeTests.cs" /> <Compile Include="System\Diagnostics\StackTraceHiddenAttributeTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\EndOfStreamExceptionTests.cs" /> <Compile Include="System\IO\Exceptions.HResults.cs" /> <Compile Include="System\IO\FileLoadExceptionTests.cs" /> <Compile Include="System\IO\FileLoadException.InteropTests.cs" /> <Compile Include="System\IO\FileNotFoundExceptionTests.cs" /> <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\IOExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongException.InteropTests.cs" /> <Compile Include="System\Reflection\AssemblyAlgorithmIdAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCompanyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyConfigurationAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCopyrightAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCultureAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDefaultAliasAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDelaySignAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDescriptionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFileVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFlagsAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyInformationalVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyFileAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyNameAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyMetadataAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyProductAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblySignatureKeyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTitleAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTrademarkAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyVersionAttributeTests.cs" /> <Compile Include="System\Reflection\BindingFlagsDoNotWrap.cs" /> <Compile Include="System\Reflection\CustomAttributeDataTests.cs" /> <Compile Include="System\Reflection\CustomAttributesTestData.cs" /> <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" /> <Compile Include="System\Reflection\DefaultMemberAttributeTests.cs" /> <Compile Include="System\Reflection\InvokeRefReturn.cs" /> <Compile Include="System\Reflection\InvokeWithRefLikeArgs.cs" /> <Compile Include="System\Reflection\IsCollectibleTests.cs" /> <Compile Include="System\Reflection\MethodBaseTests.cs" /> <Compile Include="System\Reflection\MethodBodyTests.cs" /> <Compile Include="System\Reflection\ModuleTests.cs" /> <Compile Include="System\Reflection\ObfuscateAssemblyAttributeTests.cs" /> <Compile Include="System\Reflection\ObfuscationAttributeTests.cs" /> <Compile Include="System\Reflection\PointerTests.cs" /> <Compile Include="System\Reflection\ReflectionCacheTests.cs" /> <Compile Include="System\Reflection\ReflectionContextTests.cs" /> <Compile Include="System\Reflection\ReflectionTypeLoadExceptionTests.cs" /> <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" /> <Compile Include="System\Reflection\TypeDelegatorTests.cs" /> <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" /> <Compile Include="System\Reflection\TypeTests.GetMember.cs" /> <Compile Include="System\Runtime\DependentHandleTests.cs" /> <Compile Include="System\Runtime\JitInfoTests.cs" /> <Compile Include="System\Runtime\MemoryFailPointTests.cs" /> <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\AttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" /> <Compile Include="System\Runtime\CompilerServices\DefaultInterpolatedStringHandlerTests.cs" /> <Compile Include="System\Runtime\CompilerServices\FormattableStringFactoryTests.cs" /> <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" /> <Compile Include="System\Runtime\ConstrainedExecution\PrePrepareMethodAttributeTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" /> <Compile Include="System\Runtime\Serialization\OptionalFieldAttributeTests.cs" /> <Compile Include="System\Runtime\Serialization\SerializationExceptionTests.cs" /> <Compile Include="System\Runtime\Serialization\StreamingContextTests.cs" /> <Compile Include="System\Runtime\Versioning\OSPlatformAttributeTests.cs" /> <Compile Include="System\Runtime\Versioning\RequiresPreviewFeaturesAttributeTests.cs" /> <Compile Include="System\Security\SecurityAttributeTests.cs" /> <Compile Include="System\Security\SecurityExceptionTests.cs" /> <Compile Include="System\Text\StringBuilderTests.cs" /> <Compile Include="System\Text\StringBuilderInterpolationTests.cs" /> <Compile Include="System\Threading\PeriodicTimerTests.cs" /> <Compile Include="System\Threading\WaitHandleTests.cs" /> <Compile Include="System\Type\TypePropertyTests.cs" /> <Compile Include="System\Type\TypeTests.cs" /> <Compile Include="System\Type\TypeTests.Get.cs" /> <Compile Include="$(CommonTestPath)System\RandomDataGenerator.cs" Link="Common\System\RandomDataGenerator.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="System\ExitCodeTests.Unix.cs" /> </ItemGroup> <ItemGroup Condition="'$(FeatureGenericMath)' == 'true'"> <Compile Include="System\ByteTests.GenericMath.cs" /> <Compile Include="System\CharTests.GenericMath.cs" /> <Compile Include="System\DoubleTests.GenericMath.cs" /> <Compile Include="System\GenericMathHelpers.cs" /> <Compile Include="System\HalfTests.GenericMath.cs" /> <Compile Include="System\Int16Tests.GenericMath.cs" /> <Compile Include="System\Int32Tests.GenericMath.cs" /> <Compile Include="System\Int64Tests.GenericMath.cs" /> <Compile Include="System\IntPtrTests.GenericMath.cs" /> <Compile Include="System\SByteTests.GenericMath.cs" /> <Compile Include="System\SingleTests.GenericMath.cs" /> <Compile Include="System\UInt16Tests.GenericMath.cs" /> <Compile Include="System\UInt32Tests.GenericMath.cs" /> <Compile Include="System\UInt64Tests.GenericMath.cs" /> <Compile Include="System\UIntPtrTests.GenericMath.cs" /> </ItemGroup> <ItemGroup> <Compile Include="System\Reflection\SignatureTypes.cs" /> <Compile Include="System\Runtime\CompilerServices\CallerArgumentExpressionAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\MethodImplAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeFeatureTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeWrappedExceptionTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\ExceptionDispatchInfoTests.cs" /> <Compile Include="System\Text\ASCIIUtilityTests.cs" /> <Compile Include="System\Text\EncodingTests.cs" /> <Compile Include="System\Text\RuneTests.cs" /> <Compile Include="System\Text\RuneTests.TestData.cs" /> <Compile Include="System\Text\Unicode\Utf16UtilityTests.ValidateChars.cs" /> <Compile Include="System\Text\Unicode\Utf8Tests.cs" /> <Compile Include="System\Text\Unicode\Utf8UtilityTests.ValidateBytes.cs" /> <Compile Include="System\ArgIteratorTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealFormatterTestsBase.cs" Link="System\RealFormatterTestsBase.cs" /> <Compile Include="System\RealFormatterTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealParserTestsBase.cs" Link="System\RealParserTestsBase.cs" /> <Compile Include="System\RealParserTests.cs" /> <TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Serialization.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs" /> <EmbeddedResource Include="System\Reflection\EmbeddedImage.png"> <LogicalName>System.Reflection.Tests.EmbeddedImage.png</LogicalName> </EmbeddedResource> <EmbeddedResource Include="System\Reflection\EmbeddedTextFile.txt"> <LogicalName>System.Reflection.Tests.EmbeddedTextFile.txt</LogicalName> </EmbeddedResource> <Compile Include="$(CommonTestPath)System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" Link="Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="System.Runtime.Numerics.TestData" Version="$(SystemRuntimeNumericsTestDataVersion)" GeneratePathProperty="true" /> <ProjectReference Include="TestLoadAssembly\TestLoadAssembly.csproj" /> <ProjectReference Include="TestCollectibleAssembly\TestCollectibleAssembly.csproj" /> <ProjectReference Include="TestModule\System.Reflection.TestModule.ilproj" /> <ProjectReference Include="TestStructs\System.TestStructs.ilproj" /> <ProjectReference Include="$(CommonTestPath)TestUtilities.Unicode\TestUtilities.Unicode.csproj" /> <!-- Used during reflection in tests. --> <ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Threading.AccessControl\src\System.Threading.AccessControl.csproj" /> </ItemGroup> </Project>
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System/ExceptionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Tests; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Tests { public static class ExceptionTests { private const int COR_E_EXCEPTION = unchecked((int)0x80131500); [Fact] public static void Ctor_Empty() { var exception = new Exception(); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, validateMessage: false); } [Fact] public static void Ctor_String() { string message = "something went wrong"; var exception = new Exception(message); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, message: message); } [Fact] public static void Ctor_String_Exception() { string message = "something went wrong"; var innerException = new Exception("Inner exception"); var exception = new Exception(message, innerException); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, innerException: innerException, message: message); } [Fact] public static void Exception_GetType() { Assert.Equal(typeof(Exception), (new Exception()).GetType()); Assert.Equal(typeof(NullReferenceException), (new NullReferenceException()).GetType()); } [Fact] public static void Exception_GetBaseException() { var ex = new Exception(); Assert.Same(ex.GetBaseException(), ex); var ex1 = new Exception("One level wrapper", ex); Assert.Same(ex1.GetBaseException(), ex); var ex2 = new Exception("Two level wrapper", ex); Assert.Same(ex2.GetBaseException(), ex); } [Fact] public static void Exception_TargetSite() { bool caught = false; try { throw new Exception(); } catch (Exception ex) { caught = true; Assert.Equal(MethodInfo.GetCurrentMethod(), ex.TargetSite); } Assert.True(caught); } static void RethrowException() { try { ThrowException(); } catch { throw; } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void Exception_TargetSite_OtherMethod() { Exception ex = Assert.ThrowsAny<Exception>(() => ThrowException()); Assert.Equal(nameof(ThrowException), ex.TargetSite.Name); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void Exception_TargetSite_Rethrow() { Exception ex = Assert.ThrowsAny<Exception>(() => RethrowException()); Assert.Equal(nameof(ThrowException), ex.TargetSite.Name); } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15140", TestRuntimes.Mono)] public static void ThrowStatementDoesNotResetExceptionStackLineSameMethod() { (string, string, int) rethrownExceptionStackFrame = (null, null, 0); try { ThrowAndRethrowSameMethod(out rethrownExceptionStackFrame); } catch (Exception ex) { VerifyCallStack(rethrownExceptionStackFrame, ex.StackTrace, 0); } } private static (string, string, int) ThrowAndRethrowSameMethod(out (string, string, int) rethrownExceptionStackFrame) { try { rethrownExceptionStackFrame = GetSourceInformation(1); throw new Exception("Boom!"); } catch { throw; } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(https://github.com/dotnet/runtime/issues/1871)] can't use ActiveIssue for archs [ActiveIssue("https://github.com/mono/mono/issues/15141", TestRuntimes.Mono)] public static void ThrowStatementDoesNotResetExceptionStackLineOtherMethod() { (string, string, int) rethrownExceptionStackFrame = (null, null, 0); try { ThrowAndRethrowOtherMethod(out rethrownExceptionStackFrame); } catch (Exception ex) { VerifyCallStack(rethrownExceptionStackFrame, ex.StackTrace, 1); } } private static void ThrowAndRethrowOtherMethod(out (string, string, int) rethrownExceptionStackFrame) { try { rethrownExceptionStackFrame = GetSourceInformation(1); ThrowException(); Assert.True(false, "Workaround for Linux Release builds (https://github.com/dotnet/corefx/pull/28059#issuecomment-378335456)"); } catch { throw; } rethrownExceptionStackFrame = (null, null, 0); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowException() { throw new Exception("Boom!"); } private static void VerifyCallStack( (string CallerMemberName, string SourceFilePath, int SourceLineNumber) expectedStackFrame, string reportedCallStack, int skipFrames) { try { string frameParserRegex; if (PlatformDetection.IsLineNumbersSupported) { frameParserRegex = @"\s+at\s.+\.(?<memberName>[^(.]+)\([^)]*\)\sin\s(?<filePath>.*)\:line\s(?<lineNumber>[\d]+)"; } else { frameParserRegex = @"\s+at\s.+\.(?<memberName>[^(.]+)"; } using (var sr = new StringReader(reportedCallStack)) { for (int i = 0; i < skipFrames; i++) sr.ReadLine(); string frame = sr.ReadLine(); Assert.NotNull(frame); var match = Regex.Match(frame, frameParserRegex); Assert.True(match.Success); Assert.Equal(expectedStackFrame.CallerMemberName, match.Groups["memberName"].Value); if (PlatformDetection.IsLineNumbersSupported) { Assert.Equal(expectedStackFrame.SourceFilePath, match.Groups["filePath"].Value); Assert.Equal(expectedStackFrame.SourceLineNumber, Convert.ToInt32(match.Groups["lineNumber"].Value)); } } } catch { Console.WriteLine("* ExceptionTests - reported call stack:\n{0}", reportedCallStack); throw; } } private static (string, string, int) GetSourceInformation( int offset, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { return (memberName, sourceFilePath, sourceLineNumber + offset); } } public class DerivedException : Exception { public override string Message { get => "DerivedException.Message"; } public override string ToString() { return "DerivedException.ToString()"; } #pragma warning disable SYSLIB0011 // BinaryFormatter serialization is obsolete and should not be used. [Fact] public static void Exception_SerializeObjectState() { var excp = new DerivedException(); Assert.Throws<PlatformNotSupportedException>(() => excp.SerializeObjectState += (exception, eventArgs) => eventArgs.AddSerializedState(null)); Assert.Throws<PlatformNotSupportedException>(() => excp.SerializeObjectState -= (exception, eventArgs) => eventArgs.AddSerializedState(null)); } #pragma warning restore SYSLIB0011 [Fact] public static void Exception_OverriddenToStringOnInnerException() { var inner = new DerivedException(); var excp = new Exception("msg", inner); Assert.Contains("DerivedException.ToString()", excp.ToString()); Assert.DoesNotContain("DerivedException.Message", excp.ToString()); } } public class ExceptionDataTests : IDictionary_NonGeneric_Tests { protected override IDictionary NonGenericIDictionaryFactory() => new Exception().Data; protected override Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(IndexOutOfRangeException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException); public override void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count) { if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) return; if (count == 0) { ICollection collection = NonGenericICollectionFactory(count); Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 }); collection.CopyTo(arr, 0); return; } base.ICollection_NonGeneric_CopyTo_NonZeroLowerBound(count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Tests; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Tests { public static class ExceptionTests { private const int COR_E_EXCEPTION = unchecked((int)0x80131500); [Fact] public static void Ctor_Empty() { var exception = new Exception(); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, validateMessage: false); } [Fact] public static void Ctor_String() { string message = "something went wrong"; var exception = new Exception(message); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, message: message); } [Fact] public static void Ctor_String_Exception() { string message = "something went wrong"; var innerException = new Exception("Inner exception"); var exception = new Exception(message, innerException); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_EXCEPTION, innerException: innerException, message: message); } [Fact] public static void Exception_GetType() { Assert.Equal(typeof(Exception), (new Exception()).GetType()); Assert.Equal(typeof(NullReferenceException), (new NullReferenceException()).GetType()); } [Fact] public static void Exception_GetBaseException() { var ex = new Exception(); Assert.Same(ex.GetBaseException(), ex); var ex1 = new Exception("One level wrapper", ex); Assert.Same(ex1.GetBaseException(), ex); var ex2 = new Exception("Two level wrapper", ex); Assert.Same(ex2.GetBaseException(), ex); } [Fact] public static void Exception_TargetSite() { bool caught = false; try { throw new Exception(); } catch (Exception ex) { caught = true; Assert.Equal(MethodInfo.GetCurrentMethod(), ex.TargetSite); } Assert.True(caught); } static void RethrowException() { try { ThrowException(); } catch { throw; } } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void Exception_TargetSite_OtherMethod() { Exception ex = Assert.ThrowsAny<Exception>(() => ThrowException()); Assert.Equal(nameof(ThrowException), ex.TargetSite.Name); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void Exception_TargetSite_Rethrow() { Exception ex = Assert.ThrowsAny<Exception>(() => RethrowException()); Assert.Equal(nameof(ThrowException), ex.TargetSite.Name); } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/15140", TestRuntimes.Mono)] public static void ThrowStatementDoesNotResetExceptionStackLineSameMethod() { (string, string, int) rethrownExceptionStackFrame = (null, null, 0); try { ThrowAndRethrowSameMethod(out rethrownExceptionStackFrame); } catch (Exception ex) { VerifyCallStack(rethrownExceptionStackFrame, ex.StackTrace, 0); } } private static (string, string, int) ThrowAndRethrowSameMethod(out (string, string, int) rethrownExceptionStackFrame) { try { rethrownExceptionStackFrame = GetSourceInformation(1); throw new Exception("Boom!"); } catch { throw; } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(https://github.com/dotnet/runtime/issues/1871)] can't use ActiveIssue for archs [ActiveIssue("https://github.com/mono/mono/issues/15141", TestRuntimes.Mono)] public static void ThrowStatementDoesNotResetExceptionStackLineOtherMethod() { (string, string, int) rethrownExceptionStackFrame = (null, null, 0); try { ThrowAndRethrowOtherMethod(out rethrownExceptionStackFrame); } catch (Exception ex) { VerifyCallStack(rethrownExceptionStackFrame, ex.StackTrace, 1); } } private static void ThrowAndRethrowOtherMethod(out (string, string, int) rethrownExceptionStackFrame) { try { rethrownExceptionStackFrame = GetSourceInformation(1); ThrowException(); Assert.True(false, "Workaround for Linux Release builds (https://github.com/dotnet/corefx/pull/28059#issuecomment-378335456)"); } catch { throw; } rethrownExceptionStackFrame = (null, null, 0); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowException() { throw new Exception("Boom!"); } private static void VerifyCallStack( (string CallerMemberName, string SourceFilePath, int SourceLineNumber) expectedStackFrame, string reportedCallStack, int skipFrames) { try { string frameParserRegex; if (PlatformDetection.IsLineNumbersSupported) { frameParserRegex = @"\s+at\s.+\.(?<memberName>[^(.]+)\([^)]*\)\sin\s(?<filePath>.*)\:line\s(?<lineNumber>[\d]+)"; } else { frameParserRegex = @"\s+at\s.+\.(?<memberName>[^(.]+)"; } using (var sr = new StringReader(reportedCallStack)) { for (int i = 0; i < skipFrames; i++) sr.ReadLine(); string frame = sr.ReadLine(); Assert.NotNull(frame); var match = Regex.Match(frame, frameParserRegex); Assert.True(match.Success); Assert.Equal(expectedStackFrame.CallerMemberName, match.Groups["memberName"].Value); if (PlatformDetection.IsLineNumbersSupported) { Assert.Equal(expectedStackFrame.SourceFilePath, match.Groups["filePath"].Value); Assert.Equal(expectedStackFrame.SourceLineNumber, Convert.ToInt32(match.Groups["lineNumber"].Value)); } } } catch { Console.WriteLine("* ExceptionTests - reported call stack:\n{0}", reportedCallStack); throw; } } private static (string, string, int) GetSourceInformation( int offset, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { return (memberName, sourceFilePath, sourceLineNumber + offset); } } public class DerivedException : Exception { public override string Message { get => "DerivedException.Message"; } public override string ToString() { return "DerivedException.ToString()"; } #pragma warning disable SYSLIB0011 // BinaryFormatter serialization is obsolete and should not be used. [Fact] public static void Exception_SerializeObjectState() { var excp = new DerivedException(); Assert.Throws<PlatformNotSupportedException>(() => excp.SerializeObjectState += (exception, eventArgs) => eventArgs.AddSerializedState(null)); Assert.Throws<PlatformNotSupportedException>(() => excp.SerializeObjectState -= (exception, eventArgs) => eventArgs.AddSerializedState(null)); } #pragma warning restore SYSLIB0011 [Fact] public static void Exception_OverriddenToStringOnInnerException() { var inner = new DerivedException(); var excp = new Exception("msg", inner); Assert.Contains("DerivedException.ToString()", excp.ToString()); Assert.DoesNotContain("DerivedException.Message", excp.ToString()); } } public class ExceptionDataTests : IDictionary_NonGeneric_Tests { protected override IDictionary NonGenericIDictionaryFactory() => new Exception().Data; protected override Type ICollection_NonGeneric_CopyTo_NonZeroLowerBound_ThrowType => typeof(IndexOutOfRangeException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectReferenceType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfIncorrectValueType_ThrowType => typeof(InvalidCastException); protected override Type ICollection_NonGeneric_CopyTo_ArrayOfEnumType_ThrowType => typeof(InvalidCastException); public override void ICollection_NonGeneric_CopyTo_NonZeroLowerBound(int count) { if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) return; if (count == 0) { ICollection collection = NonGenericICollectionFactory(count); Array arr = Array.CreateInstance(typeof(object), new int[1] { count }, new int[1] { 2 }); collection.CopyTo(arr, 0); return; } base.ICollection_NonGeneric_CopyTo_NonZeroLowerBound(count); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Runtime.ExceptionServices.Tests { public class ExceptionDispatchInfoTests { [Fact] public static void StaticThrow_NullArgument_ThrowArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.Throw(null)); } [Fact] public static void StaticThrow_UpdatesStackTraceAppropriately() { const string RethrowMessageSubstring = "End of stack trace"; var e = new FormatException(); for (int i = 0; i < 3; i++) { Assert.Same(e, Assert.Throws<FormatException>(() => ExceptionDispatchInfo.Throw(e))); Assert.Equal(i, Regex.Matches(e.StackTrace, RethrowMessageSubstring).Count); } } [Fact] public static void SetCurrentOrRemoteStackTrace_Invalid_Throws() { Exception e; // Null argument e = null; AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.SetCurrentStackTrace(e)); AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); AssertExtensions.Throws<ArgumentNullException>("stackTrace", () => ExceptionDispatchInfo.SetRemoteStackTrace(new Exception(), stackTrace: null)); // Previously set current stack e = new Exception(); ExceptionDispatchInfo.SetCurrentStackTrace(e); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetCurrentStackTrace(e)); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); // Previously thrown e = new Exception(); try { throw e; } catch { } Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetCurrentStackTrace(e)); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void SetCurrentStackTrace_IncludedInExceptionStackTrace() { Exception e; e = new Exception(); ABCDEFGHIJKLMNOPQRSTUVWXYZ(e); Assert.Contains(nameof(ABCDEFGHIJKLMNOPQRSTUVWXYZ), e.StackTrace, StringComparison.Ordinal); e = new Exception(); ABCDEFGHIJKLMNOPQRSTUVWXYZ(e); try { throw e; } catch { } Assert.Contains(nameof(ABCDEFGHIJKLMNOPQRSTUVWXYZ), e.StackTrace, StringComparison.Ordinal); } [Fact] public static void SetRemoteStackTrace_IncludedInExceptionStackTrace() { Exception e; e = new Exception(); Assert.Same(e, ExceptionDispatchInfo.SetRemoteStackTrace(e, "pumpkin-anaconda-maritime")); // 3 randomly selected words Assert.Contains("pumpkin-anaconda-maritime", e.StackTrace, StringComparison.Ordinal); Assert.DoesNotContain("pumpkin-anaconda-maritime", new StackTrace(e).ToString(), StringComparison.Ordinal); // we shouldn't attempt to parse it in a StackTrace object e = new Exception(); Assert.Same(e, ExceptionDispatchInfo.SetRemoteStackTrace(e, "pumpkin-anaconda-maritime")); try { throw e; } catch { } Assert.Contains("pumpkin-anaconda-maritime", e.StackTrace, StringComparison.Ordinal); Assert.DoesNotContain("pumpkin-anaconda-maritime", new StackTrace(e).ToString(), StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private static void ABCDEFGHIJKLMNOPQRSTUVWXYZ(Exception e) { Assert.Same(e, ExceptionDispatchInfo.SetCurrentStackTrace(e)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Xunit; namespace System.Runtime.ExceptionServices.Tests { public class ExceptionDispatchInfoTests { [Fact] public static void StaticThrow_NullArgument_ThrowArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.Throw(null)); } [Fact] public static void StaticThrow_UpdatesStackTraceAppropriately() { const string RethrowMessageSubstring = "End of stack trace"; var e = new FormatException(); for (int i = 0; i < 3; i++) { Assert.Same(e, Assert.Throws<FormatException>(() => ExceptionDispatchInfo.Throw(e))); Assert.Equal(i, Regex.Count(e.StackTrace, RethrowMessageSubstring)); } } [Fact] public static void SetCurrentOrRemoteStackTrace_Invalid_Throws() { Exception e; // Null argument e = null; AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.SetCurrentStackTrace(e)); AssertExtensions.Throws<ArgumentNullException>("source", () => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); AssertExtensions.Throws<ArgumentNullException>("stackTrace", () => ExceptionDispatchInfo.SetRemoteStackTrace(new Exception(), stackTrace: null)); // Previously set current stack e = new Exception(); ExceptionDispatchInfo.SetCurrentStackTrace(e); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetCurrentStackTrace(e)); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); // Previously thrown e = new Exception(); try { throw e; } catch { } Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetCurrentStackTrace(e)); Assert.Throws<InvalidOperationException>(() => ExceptionDispatchInfo.SetRemoteStackTrace(e, "Hello")); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public static void SetCurrentStackTrace_IncludedInExceptionStackTrace() { Exception e; e = new Exception(); ABCDEFGHIJKLMNOPQRSTUVWXYZ(e); Assert.Contains(nameof(ABCDEFGHIJKLMNOPQRSTUVWXYZ), e.StackTrace, StringComparison.Ordinal); e = new Exception(); ABCDEFGHIJKLMNOPQRSTUVWXYZ(e); try { throw e; } catch { } Assert.Contains(nameof(ABCDEFGHIJKLMNOPQRSTUVWXYZ), e.StackTrace, StringComparison.Ordinal); } [Fact] public static void SetRemoteStackTrace_IncludedInExceptionStackTrace() { Exception e; e = new Exception(); Assert.Same(e, ExceptionDispatchInfo.SetRemoteStackTrace(e, "pumpkin-anaconda-maritime")); // 3 randomly selected words Assert.Contains("pumpkin-anaconda-maritime", e.StackTrace, StringComparison.Ordinal); Assert.DoesNotContain("pumpkin-anaconda-maritime", new StackTrace(e).ToString(), StringComparison.Ordinal); // we shouldn't attempt to parse it in a StackTrace object e = new Exception(); Assert.Same(e, ExceptionDispatchInfo.SetRemoteStackTrace(e, "pumpkin-anaconda-maritime")); try { throw e; } catch { } Assert.Contains("pumpkin-anaconda-maritime", e.StackTrace, StringComparison.Ordinal); Assert.DoesNotContain("pumpkin-anaconda-maritime", new StackTrace(e).ToString(), StringComparison.Ordinal); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private static void ABCDEFGHIJKLMNOPQRSTUVWXYZ(Exception e) { Assert.Same(e, ExceptionDispatchInfo.SetCurrentStackTrace(e)); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Xunit; namespace System.Text.Unicode.Tests { public class Utf8Tests { private const string X_UTF8 = "58"; // U+0058 LATIN CAPITAL LETTER X, 1 byte private const string X_UTF16 = "X"; private const string Y_UTF8 = "59"; // U+0058 LATIN CAPITAL LETTER Y, 1 byte private const string Y_UTF16 = "Y"; private const string Z_UTF8 = "5A"; // U+0058 LATIN CAPITAL LETTER Z, 1 byte private const string Z_UTF16 = "Z"; private const string E_ACUTE_UTF8 = "C3A9"; // U+00E9 LATIN SMALL LETTER E WITH ACUTE, 2 bytes private const string E_ACUTE_UTF16 = "\u00E9"; private const string EURO_SYMBOL_UTF8 = "E282AC"; // U+20AC EURO SIGN, 3 bytes private const string EURO_SYMBOL_UTF16 = "\u20AC"; private const string REPLACEMENT_CHAR_UTF8 = "EFBFBD"; // U+FFFD REPLACEMENT CHAR, 3 bytes private const string REPLACEMENT_CHAR_UTF16 = "\uFFFD"; private const string GRINNING_FACE_UTF8 = "F09F9880"; // U+1F600 GRINNING FACE, 4 bytes private const string GRINNING_FACE_UTF16 = "\U0001F600"; private const string WOMAN_CARTWHEELING_MEDSKIN_UTF16 = "\U0001F938\U0001F3FD\u200D\u2640\uFE0F"; // U+1F938 U+1F3FD U+200D U+2640 U+FE0F WOMAN CARTWHEELING: MEDIUM SKIN TONE // All valid scalars [ U+0000 .. U+D7FF ] and [ U+E000 .. U+10FFFF ]. private static readonly IEnumerable<Rune> s_allValidScalars = Enumerable.Range(0x0000, 0xD800).Concat(Enumerable.Range(0xE000, 0x110000 - 0xE000)).Select(value => new Rune(value)); private static readonly ReadOnlyMemory<char> s_allScalarsAsUtf16; private static readonly ReadOnlyMemory<byte> s_allScalarsAsUtf8; static Utf8Tests() { List<char> allScalarsAsUtf16 = new List<char>(); List<byte> allScalarsAsUtf8 = new List<byte>(); foreach (Rune rune in s_allValidScalars) { allScalarsAsUtf16.AddRange(ToUtf16(rune)); allScalarsAsUtf8.AddRange(ToUtf8(rune)); } s_allScalarsAsUtf16 = allScalarsAsUtf16.ToArray().AsMemory(); s_allScalarsAsUtf8 = allScalarsAsUtf8.ToArray().AsMemory(); } /* * COMMON UTILITIES FOR UNIT TESTS */ public static byte[] DecodeHex(ReadOnlySpan<char> inputHex) { Assert.True(Regex.IsMatch(inputHex.ToString(), "^([0-9a-fA-F]{2})*$"), "Input must be an even number of hex characters."); return Convert.FromHexString(inputHex); } // !! IMPORTANT !! // Don't delete this implementation, as we use it as a reference to make sure the framework's // transcoding logic is correct. public static byte[] ToUtf8(Rune rune) { Assert.True(Rune.IsValid(rune.Value), $"Rune with value U+{(uint)rune.Value:X4} is not well-formed."); if (rune.Value < 0x80) { return new[] { (byte)rune.Value }; } else if (rune.Value < 0x0800) { return new[] { (byte)((rune.Value >> 6) | 0xC0), (byte)((rune.Value & 0x3F) | 0x80) }; } else if (rune.Value < 0x10000) { return new[] { (byte)((rune.Value >> 12) | 0xE0), (byte)(((rune.Value >> 6) & 0x3F) | 0x80), (byte)((rune.Value & 0x3F) | 0x80) }; } else { return new[] { (byte)((rune.Value >> 18) | 0xF0), (byte)(((rune.Value >> 12) & 0x3F) | 0x80), (byte)(((rune.Value >> 6) & 0x3F) | 0x80), (byte)((rune.Value & 0x3F) | 0x80) }; } } // !! IMPORTANT !! // Don't delete this implementation, as we use it as a reference to make sure the framework's // transcoding logic is correct. private static char[] ToUtf16(Rune rune) { Assert.True(Rune.IsValid(rune.Value), $"Rune with value U+{(uint)rune.Value:X4} is not well-formed."); if (rune.IsBmp) { return new[] { (char)rune.Value }; } else { return new[] { (char)((rune.Value >> 10) + 0xD800 - 0x40), (char)((rune.Value & 0x03FF) + 0xDC00) }; } } [Theory] [InlineData("", "")] // empty string is OK [InlineData(X_UTF16, X_UTF8)] [InlineData(E_ACUTE_UTF16, E_ACUTE_UTF8)] [InlineData(EURO_SYMBOL_UTF16, EURO_SYMBOL_UTF8)] public void ToBytes_WithSmallValidBuffers(string utf16Input, string expectedUtf8TranscodingHex) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf8, // so inputs should be less than 2 chars. Assert.InRange(utf16Input.Length, 0, 1); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Theory] [InlineData("AB")] // 2 ASCII chars, hits fast inner loop [InlineData("ABCD")] // 4 ASCII chars, hits fast inner loop [InlineData("ABCDEF")] // 6 ASCII chars, hits fast inner loop [InlineData("ABCDEFGH")] // 8 ASCII chars, hits fast inner loop [InlineData("ABCDEFGHIJ")] // 10 ASCII chars, hits fast inner loop [InlineData("ABCDEF" + E_ACUTE_UTF16 + "HIJ")] // interrupts inner loop due to non-ASCII char in first char of first DWORD [InlineData("ABCDEFG" + EURO_SYMBOL_UTF16 + "IJ")] // interrupts inner loop due to non-ASCII char in second char of first DWORD [InlineData("ABCDEFGH" + E_ACUTE_UTF16 + "J")] // interrupts inner loop due to non-ASCII char in first char of second DWORD [InlineData("ABCDEFGHI" + EURO_SYMBOL_UTF16)] // interrupts inner loop due to non-ASCII char in second char of second DWORD [InlineData(X_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then falls down to slow path [InlineData(X_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then consumes 2x 2-byte sequences at once [InlineData(E_ACUTE_UTF16 + X_UTF16)] // no first ASCII char to drain, consumes 2-byte seq followed by ASCII char [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // stay within 2x 2-byte sequence processing loop [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in second char of DWORD [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in first char of DWORD [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // break out of 2x 2-byte seq loop due to 3-byte data [InlineData(E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // 2-byte logic sees next char isn't ASCII, cannot read full DWORD from remaining input buffer, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16)] // 2x 3-byte logic can't read a full DWORD from next part of buffer, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + X_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16)] // 3-byte processing loop can't consume next ASCII char, can't read DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // stay within 2x 3-byte sequence processing loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at beginning of DWORD after 2x 3-byte sequence [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at end of DWORD after 2x 3-byte sequence [InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // consume 2-byte sequence as second char in DWORD which begins with 3-byte encoded char [InlineData(EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 3-byte sequence followed by 4-byte sequence [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 2x 3-byte sequence followed by 4-byte sequence [InlineData(GRINNING_FACE_UTF16)] // single 4-byte surrogate char pair [InlineData(GRINNING_FACE_UTF16 + EURO_SYMBOL_UTF16)] // 4-byte surrogate char pair, cannot read next DWORD, falls down to slow drain loop public void ToBytes_WithLargeValidBuffers(string utf16Input) { // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8, // so inputs should be at least 2 chars. Assert.True(utf16Input.Length >= 2); // We're going to run the tests with destination buffer lengths ranging from 0 all the way // to buffers large enough to hold the full output. This allows us to test logic that // detects whether we're about to overrun our destination buffer and instead returns DestinationTooSmall. Rune[] enumeratedScalars = utf16Input.EnumerateRunes().ToArray(); // 0-length buffer test ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumCharsRead: 0, expectedUtf8Transcoding: ReadOnlySpan<byte>.Empty); int expectedNumCharsConsumed = 0; byte[] concatenatedUtf8 = Array.Empty<byte>(); for (int i = 0; i < enumeratedScalars.Length; i++) { Rune thisScalar = enumeratedScalars[i]; // provide partial destination buffers all the way up to (but not including) enough to hold the next full scalar encoding for (int j = 1; j < thisScalar.Utf8SequenceLength; j++) { ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length + j, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: concatenatedUtf8); } // now provide a destination buffer large enough to hold the next full scalar encoding expectedNumCharsConsumed += thisScalar.Utf16SequenceLength; concatenatedUtf8 = concatenatedUtf8.Concat(ToUtf8(thisScalar)).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (i == enumeratedScalars.Length - 1) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: concatenatedUtf8); } // now throw lots of ASCII data at the beginning so that we exercise the vectorized code paths utf16Input = new string('x', 64) + utf16Input; concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: concatenatedUtf8); // now throw some non-ASCII data at the beginning so that we *don't* exercise the vectorized code paths utf16Input = WOMAN_CARTWHEELING_MEDSKIN_UTF16 + utf16Input[64..]; concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: concatenatedUtf8); } [Theory] [InlineData('\uD800', OperationStatus.NeedMoreData)] // standalone high surrogate [InlineData('\uDFFF', OperationStatus.InvalidData)] // standalone low surrogate public void ToBytes_WithOnlyStandaloneSurrogates(char charValue, OperationStatus expectedOperationStatus) { ToBytes_Test_Core( utf16Input: new[] { charValue }, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: expectedOperationStatus, expectedNumCharsRead: 0, expectedUtf8Transcoding: Span<byte>.Empty); } [Theory] [InlineData("<LOW><HIGH>", 0, "")] // swapped surrogate pair characters [InlineData("A<LOW><HIGH>", 1, "41")] // consume standalone ASCII char, then swapped surrogate pair characters [InlineData("A<HIGH>B", 1, "41")] // consume standalone ASCII char, then standalone high surrogate char [InlineData("A<LOW>B", 1, "41")] // consume standalone ASCII char, then standalone low surrogate char [InlineData("AB<HIGH><HIGH>", 2, "4142")] // consume two ASCII chars, then standalone high surrogate char [InlineData("AB<LOW><LOW>", 2, "4142")] // consume two ASCII chars, then standalone low surrogate char public void ToBytes_WithInvalidSurrogates(string utf16Input, int expectedNumCharsConsumed, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8, // so inputs should be at least 2 chars. Assert.True(utf16Input.Length >= 2); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: (expectedUtf8TranscodingHex.Length) / 2 + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Theory] [InlineData("<LOW><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete high surr. [InlineData("<HIGH><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone high surr. and incomplete high surr. [InlineData("<LOW><LOW>", REPLACEMENT_CHAR_UTF8 + REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete low surr. [InlineData("A<LOW>B<LOW>C<HIGH>D", "41" + REPLACEMENT_CHAR_UTF8 + "42" + REPLACEMENT_CHAR_UTF8 + "43" + REPLACEMENT_CHAR_UTF8 + "44")] // standalone low, low, high surrounded by other data public void ToBytes_WithReplacements(string utf16Input, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); bool isFinalCharHighSurrogate = char.IsHighSurrogate(utf16Input.Last()); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: (isFinalCharHighSurrogate) ? OperationStatus.NeedMoreData : OperationStatus.Done, expectedNumCharsRead: (isFinalCharHighSurrogate) ? (utf16Input.Length - 1) : utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); if (isFinalCharHighSurrogate) { // Also test with isFinalChunk = true ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2 + Rune.ReplacementChar.Utf8SequenceLength /* for replacement char */, replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex + REPLACEMENT_CHAR_UTF8)); } } [Theory] [InlineData(E_ACUTE_UTF16 + "<LOW>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD [InlineData(E_ACUTE_UTF16 + "<LOW>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone low surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD [InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone high surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>", false, 1, OperationStatus.NeedMoreData, E_ACUTE_UTF8)] // don't replace standalone high surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X' public void ToBytes_WithReplacements_AndCustomBufferSizes(string utf16Input, bool isFinalChunk, int expectedNumCharsConsumed, OperationStatus expectedOperationStatus, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: true, isFinalChunk: isFinalChunk, expectedOperationStatus: expectedOperationStatus, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Fact] public void ToBytes_AllPossibleScalarValues() { ToBytes_Test_Core( utf16Input: s_allScalarsAsUtf16.Span, destinationSize: s_allScalarsAsUtf8.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: s_allScalarsAsUtf16.Length, expectedUtf8Transcoding: s_allScalarsAsUtf8.Span); } private static void ToBytes_Test_Core(ReadOnlySpan<char> utf16Input, int destinationSize, bool replaceInvalidSequences, bool isFinalChunk, OperationStatus expectedOperationStatus, int expectedNumCharsRead, ReadOnlySpan<byte> expectedUtf8Transcoding) { // Arrange using (BoundedMemory<char> boundedSource = BoundedMemory.AllocateFromExistingData(utf16Input)) using (BoundedMemory<byte> boundedDestination = BoundedMemory.Allocate<byte>(destinationSize)) { boundedSource.MakeReadonly(); // Act OperationStatus actualOperationStatus = Utf8.FromUtf16(boundedSource.Span, boundedDestination.Span, out int actualNumCharsRead, out int actualNumBytesWritten, replaceInvalidSequences, isFinalChunk); // Assert Assert.Equal(expectedOperationStatus, actualOperationStatus); Assert.Equal(expectedNumCharsRead, actualNumCharsRead); Assert.Equal(expectedUtf8Transcoding.Length, actualNumBytesWritten); Assert.Equal(expectedUtf8Transcoding.ToArray(), boundedDestination.Span.Slice(0, actualNumBytesWritten).ToArray()); } } [Theory] [InlineData("80", 0, "")] // sequence cannot begin with continuation character [InlineData("8182", 0, "")] // sequence cannot begin with continuation character [InlineData("838485", 0, "")] // sequence cannot begin with continuation character [InlineData(X_UTF8 + "80", 1, X_UTF16)] // sequence cannot begin with continuation character [InlineData(X_UTF8 + "8182", 1, X_UTF16)] // sequence cannot begin with continuation character [InlineData("C0", 0, "")] // [ C0 ] is always invalid [InlineData("C080", 0, "")] // [ C0 ] is always invalid [InlineData("C08081", 0, "")] // [ C0 ] is always invalid [InlineData(X_UTF8 + "C1", 1, X_UTF16)] // [ C1 ] is always invalid [InlineData(X_UTF8 + "C180", 1, X_UTF16)] // [ C1 ] is always invalid [InlineData(X_UTF8 + "C27F", 1, X_UTF16)] // [ C2 ] is improperly terminated [InlineData("E2827F", 0, "")] // [ E2 82 ] is improperly terminated [InlineData("E09F80", 0, "")] // [ E0 9F ... ] is overlong [InlineData("E0C080", 0, "")] // [ E0 ] is improperly terminated [InlineData("ED7F80", 0, "")] // [ ED ] is improperly terminated [InlineData("EDA080", 0, "")] // [ ED A0 ... ] is surrogate public void ToChars_WithSmallInvalidBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf16, // so inputs should be less than 4 bytes. Assert.InRange(utf8HexInput.Length, 0, 6); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] [InlineData("C2", 0, "")] // [ C2 ] is an incomplete sequence [InlineData("E282", 0, "")] // [ E2 82 ] is an incomplete sequence [InlineData(X_UTF8 + "C2", 1, X_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(X_UTF8 + "E0", 1, X_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(X_UTF8 + "E0BF", 1, X_UTF16)] // [ E0 BF ] is an incomplete sequence [InlineData(X_UTF8 + "F0", 1, X_UTF16)] // [ F0 ] is an incomplete sequence [InlineData(X_UTF8 + "F0BF", 1, X_UTF16)] // [ F0 BF ] is an incomplete sequence [InlineData(X_UTF8 + "F0BFA0", 1, X_UTF16)] // [ F0 BF A0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "C2", 2, E_ACUTE_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "E0", 2, E_ACUTE_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "F0", 2, E_ACUTE_UTF16)] // [ F0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "E0BF", 2, E_ACUTE_UTF16)] // [ E0 BF ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "F0BF", 2, E_ACUTE_UTF16)] // [ F0 BF ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "C2", 3, EURO_SYMBOL_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "E0", 3, EURO_SYMBOL_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "F0", 3, EURO_SYMBOL_UTF16)] // [ F0 ] is an incomplete sequence public void ToChars_WithVariousIncompleteBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf16, // so inputs should be less than 4 bytes. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] /* SMALL VALID BUFFERS - tests drain loop at end of method */ [InlineData("")] // empty string is OK [InlineData("X")] [InlineData("XY")] [InlineData("XYZ")] [InlineData(E_ACUTE_UTF16)] [InlineData(X_UTF16 + E_ACUTE_UTF16)] [InlineData(E_ACUTE_UTF16 + X_UTF16)] [InlineData(EURO_SYMBOL_UTF16)] /* LARGE VALID BUFFERS - test main loop at beginning of method */ [InlineData(E_ACUTE_UTF16 + "ABCD" + "0123456789:;<=>?")] // Loop unrolling at end of buffer [InlineData(E_ACUTE_UTF16 + "ABCD" + "0123456789:;<=>?" + "01234567" + E_ACUTE_UTF16 + "89:;<=>?")] // Loop unrolling interrupted by non-ASCII [InlineData("ABC" + E_ACUTE_UTF16 + "0123")] // 3 ASCII bytes followed by non-ASCII [InlineData("AB" + E_ACUTE_UTF16 + "0123")] // 2 ASCII bytes followed by non-ASCII [InlineData("A" + E_ACUTE_UTF16 + "0123")] // 1 ASCII byte followed by non-ASCII [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // 4x 2-byte sequences, exercises optimization code path in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + "PQ")] // 3x 2-byte sequences + 2 ASCII bytes, exercises optimization code path in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + "PQ")] // single 2-byte sequence + 2 trailing ASCII bytes, exercises draining logic in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + "P" + E_ACUTE_UTF16 + "0@P")] // single 2-byte sequences + 1 trailing ASCII byte + 2-byte sequence, exercises draining logic in 2-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + "@")] // single 3-byte sequence + 1 trailing ASCII byte, exercises draining logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + "@P`")] // single 3-byte sequence + 3 trailing ASCII byte, exercises draining logic and "running out of data" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // 3x 3-byte sequences, exercises "stay within 3-byte loop" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // 4x 3-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + E_ACUTE_UTF16)] // 3x 3-byte sequences + single 2-byte sequence, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // 2x 3-byte sequences + 4x 2-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(GRINNING_FACE_UTF16 + GRINNING_FACE_UTF16)] // 2x 4-byte sequences, exercises 4-byte sequence processing [InlineData(GRINNING_FACE_UTF16 + "@AB")] // single 4-byte sequence + 3 ASCII bytes, exercises 4-byte sequence processing and draining logic [InlineData(WOMAN_CARTWHEELING_MEDSKIN_UTF16)] // exercises switching between multiple sequence lengths public void ToChars_ValidBuffers(string utf16Input) { // We're going to run the tests with destination buffer lengths ranging from 0 all the way // to buffers large enough to hold the full output. This allows us to test logic that // detects whether we're about to overrun our destination buffer and instead returns DestinationTooSmall. Rune[] enumeratedScalars = utf16Input.EnumerateRunes().ToArray(); // Convert entire input to UTF-8 using our unit test reference logic. byte[] utf8Input = enumeratedScalars.SelectMany(ToUtf8).ToArray(); // 0-length buffer test ToChars_Test_Core( utf8Input: utf8Input, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (utf8Input.Length == 0) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumBytesRead: 0, expectedUtf16Transcoding: ReadOnlySpan<char>.Empty); int expectedNumBytesConsumed = 0; char[] concatenatedUtf16 = Array.Empty<char>(); for (int i = 0; i < enumeratedScalars.Length; i++) { Rune thisScalar = enumeratedScalars[i]; // if this is an astral scalar value, quickly test a buffer that's not large enough to contain the entire UTF-16 encoding if (!thisScalar.IsBmp) { ToChars_Test_Core( utf8Input: utf8Input, destinationSize: concatenatedUtf16.Length + 1, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: concatenatedUtf16); } // now provide a destination buffer large enough to hold the next full scalar encoding expectedNumBytesConsumed += thisScalar.Utf8SequenceLength; concatenatedUtf16 = concatenatedUtf16.Concat(ToUtf16(thisScalar)).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: concatenatedUtf16.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (i == enumeratedScalars.Length - 1) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: concatenatedUtf16); } // now throw lots of ASCII data at the beginning so that we exercise the vectorized code paths utf16Input = new string('x', 64) + utf16Input; utf8Input = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: utf16Input.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8Input.Length, expectedUtf16Transcoding: utf16Input); // now throw some non-ASCII data at the beginning so that we *don't* exercise the vectorized code paths utf16Input = WOMAN_CARTWHEELING_MEDSKIN_UTF16 + utf16Input[64..]; utf8Input = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: utf16Input.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8Input.Length, expectedUtf16Transcoding: utf16Input); } [Theory] [InlineData("3031" + "80" + "202122232425", 2, "01")] // Continuation character at start of sequence should match no bitmask [InlineData("3031" + "C080" + "2021222324", 2, "01")] // Overlong 2-byte sequence at start of DWORD [InlineData("3031" + "C180" + "2021222324", 2, "01")] // Overlong 2-byte sequence at start of DWORD [InlineData("C280" + "C180", 2, "\u0080")] // Overlong 2-byte sequence at end of DWORD [InlineData("C27F" + "C280", 0, "")] // Improperly terminated 2-byte sequence at start of DWORD [InlineData("C2C0" + "C280", 0, "")] // Improperly terminated 2-byte sequence at start of DWORD [InlineData("C280" + "C27F", 2, "\u0080")] // Improperly terminated 2-byte sequence at end of DWORD [InlineData("C280" + "C2C0", 2, "\u0080")] // Improperly terminated 2-byte sequence at end of DWORD [InlineData("C280" + "C280" + "80203040", 4, "\u0080\u0080")] // Continuation character at start of sequence, within "stay in 2-byte processing" optimization [InlineData("C280" + "C280" + "C180" + "C280", 4, "\u0080\u0080")] // Overlong 2-byte sequence at start of DWORD, within "stay in 2-byte processing" optimization [InlineData("C280" + "C280" + "C280" + "C180", 6, "\u0080\u0080\u0080")] // Overlong 2-byte sequence at end of DWORD, within "stay in 2-byte processing" optimization [InlineData("3031" + "E09F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Overlong 3-byte sequence at start of DWORD [InlineData("3031" + "E07F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E0C080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E17F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E1C080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "EDA080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Surrogate 3-byte sequence at start of DWORD [InlineData("3031" + "E69C88" + "E59B" + "E69C88", 5, "01\u6708")] // Incomplete 3-byte sequence surrounded by valid 3-byte sequences [InlineData("3031" + "F5808080", 2, "01")] // [ F5 ] is always invalid [InlineData("3031" + "F6808080", 2, "01")] // [ F6 ] is always invalid [InlineData("3031" + "F7808080", 2, "01")] // [ F7 ] is always invalid [InlineData("3031" + "F8808080", 2, "01")] // [ F8 ] is always invalid [InlineData("3031" + "F9808080", 2, "01")] // [ F9 ] is always invalid [InlineData("3031" + "FA808080", 2, "01")] // [ FA ] is always invalid [InlineData("3031" + "FB808080", 2, "01")] // [ FB ] is always invalid [InlineData("3031" + "FC808080", 2, "01")] // [ FC ] is always invalid [InlineData("3031" + "FD808080", 2, "01")] // [ FD ] is always invalid [InlineData("3031" + "FE808080", 2, "01")] // [ FE ] is always invalid [InlineData("3031" + "FF808080", 2, "01")] // [ FF ] is always invalid public void ToChars_WithLargeInvalidBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf16, // so inputs should be less >= 4 bytes. Assert.True(utf8HexInput.Length >= 8); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] [InlineData(X_UTF8 + "80" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // stray continuation byte [ 80 ] [InlineData(X_UTF8 + "FF" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // invalid UTF-8 byte [ FF ] [InlineData(X_UTF8 + "C2" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // 2-byte sequence starter [ C2 ] not followed by continuation byte [InlineData(X_UTF8 + "C1C180" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ C1 80 ] is overlong but consists of two maximal invalid subsequences, each of length 1 byte [InlineData(X_UTF8 + E_ACUTE_UTF8 + "E08080", X_UTF16 + E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16)] // [ E0 80 ] is overlong 2-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] is stray continuation byte [InlineData(GRINNING_FACE_UTF8 + "F08F8080" + GRINNING_FACE_UTF8, GRINNING_FACE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + GRINNING_FACE_UTF16)] // [ F0 8F ] is overlong 4-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] instances are stray continuation bytes [InlineData(GRINNING_FACE_UTF8 + "F4908080" + GRINNING_FACE_UTF8, GRINNING_FACE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + GRINNING_FACE_UTF16)] // [ F4 90 ] is out-of-range 4-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] instances are stray continuation bytes [InlineData(E_ACUTE_UTF8 + "EDA0" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ ED A0 ] is encoding of UTF-16 surrogate code point, so consists of two maximal invalid subsequences, each of length 1 byte [InlineData(E_ACUTE_UTF8 + "ED80" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ ED 80 ] is incomplete 3-byte sequence, so is 2-byte maximal invalid subsequence [InlineData(E_ACUTE_UTF8 + "F380" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ F3 80 ] is incomplete 4-byte sequence, so is 2-byte maximal invalid subsequence [InlineData(E_ACUTE_UTF8 + "F38080" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ F3 80 80 ] is incomplete 4-byte sequence, so is 3-byte maximal invalid subsequence public void ToChars_WithReplacement(string utf8HexInput, string expectedUtf16Transcoding) { // First run the test with isFinalBlock = false, // both with and without some bytes of incomplete trailing data. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); // Then run the test with isFinalBlock = true, with incomplete trailing data. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length + 1, // allow room for U+FFFD replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8HexInput.Length / 2 + 2, expectedUtf16Transcoding: expectedUtf16Transcoding + REPLACEMENT_CHAR_UTF16); } [Fact] public void ToChars_AllPossibleScalarValues() { ToChars_Test_Core( utf8Input: s_allScalarsAsUtf8.Span, destinationSize: s_allScalarsAsUtf16.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: s_allScalarsAsUtf8.Length, expectedUtf16Transcoding: s_allScalarsAsUtf16.Span); } private static void ToChars_Test_Core(ReadOnlySpan<byte> utf8Input, int destinationSize, bool replaceInvalidSequences, bool isFinalChunk, OperationStatus expectedOperationStatus, int expectedNumBytesRead, ReadOnlySpan<char> expectedUtf16Transcoding) { // Arrange using (BoundedMemory<byte> boundedSource = BoundedMemory.AllocateFromExistingData(utf8Input)) using (BoundedMemory<char> boundedDestination = BoundedMemory.Allocate<char>(destinationSize)) { boundedSource.MakeReadonly(); // Act OperationStatus actualOperationStatus = Utf8.ToUtf16(boundedSource.Span, boundedDestination.Span, out int actualNumBytesRead, out int actualNumCharsWritten, replaceInvalidSequences, isFinalChunk); // Assert Assert.Equal(expectedOperationStatus, actualOperationStatus); Assert.Equal(expectedNumBytesRead, actualNumBytesRead); Assert.Equal(expectedUtf16Transcoding.Length, actualNumCharsWritten); Assert.Equal(expectedUtf16Transcoding.ToString(), boundedDestination.Span.Slice(0, actualNumCharsWritten).ToString()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Xunit; namespace System.Text.Unicode.Tests { public class Utf8Tests { private const string X_UTF8 = "58"; // U+0058 LATIN CAPITAL LETTER X, 1 byte private const string X_UTF16 = "X"; private const string Y_UTF8 = "59"; // U+0058 LATIN CAPITAL LETTER Y, 1 byte private const string Y_UTF16 = "Y"; private const string Z_UTF8 = "5A"; // U+0058 LATIN CAPITAL LETTER Z, 1 byte private const string Z_UTF16 = "Z"; private const string E_ACUTE_UTF8 = "C3A9"; // U+00E9 LATIN SMALL LETTER E WITH ACUTE, 2 bytes private const string E_ACUTE_UTF16 = "\u00E9"; private const string EURO_SYMBOL_UTF8 = "E282AC"; // U+20AC EURO SIGN, 3 bytes private const string EURO_SYMBOL_UTF16 = "\u20AC"; private const string REPLACEMENT_CHAR_UTF8 = "EFBFBD"; // U+FFFD REPLACEMENT CHAR, 3 bytes private const string REPLACEMENT_CHAR_UTF16 = "\uFFFD"; private const string GRINNING_FACE_UTF8 = "F09F9880"; // U+1F600 GRINNING FACE, 4 bytes private const string GRINNING_FACE_UTF16 = "\U0001F600"; private const string WOMAN_CARTWHEELING_MEDSKIN_UTF16 = "\U0001F938\U0001F3FD\u200D\u2640\uFE0F"; // U+1F938 U+1F3FD U+200D U+2640 U+FE0F WOMAN CARTWHEELING: MEDIUM SKIN TONE // All valid scalars [ U+0000 .. U+D7FF ] and [ U+E000 .. U+10FFFF ]. private static readonly IEnumerable<Rune> s_allValidScalars = Enumerable.Range(0x0000, 0xD800).Concat(Enumerable.Range(0xE000, 0x110000 - 0xE000)).Select(value => new Rune(value)); private static readonly ReadOnlyMemory<char> s_allScalarsAsUtf16; private static readonly ReadOnlyMemory<byte> s_allScalarsAsUtf8; static Utf8Tests() { List<char> allScalarsAsUtf16 = new List<char>(); List<byte> allScalarsAsUtf8 = new List<byte>(); foreach (Rune rune in s_allValidScalars) { allScalarsAsUtf16.AddRange(ToUtf16(rune)); allScalarsAsUtf8.AddRange(ToUtf8(rune)); } s_allScalarsAsUtf16 = allScalarsAsUtf16.ToArray().AsMemory(); s_allScalarsAsUtf8 = allScalarsAsUtf8.ToArray().AsMemory(); } /* * COMMON UTILITIES FOR UNIT TESTS */ public static byte[] DecodeHex(ReadOnlySpan<char> inputHex) { Assert.Matches(@"^([0-9a-fA-F]{2})*$", inputHex.ToString()); return Convert.FromHexString(inputHex); } // !! IMPORTANT !! // Don't delete this implementation, as we use it as a reference to make sure the framework's // transcoding logic is correct. public static byte[] ToUtf8(Rune rune) { Assert.True(Rune.IsValid(rune.Value), $"Rune with value U+{(uint)rune.Value:X4} is not well-formed."); if (rune.Value < 0x80) { return new[] { (byte)rune.Value }; } else if (rune.Value < 0x0800) { return new[] { (byte)((rune.Value >> 6) | 0xC0), (byte)((rune.Value & 0x3F) | 0x80) }; } else if (rune.Value < 0x10000) { return new[] { (byte)((rune.Value >> 12) | 0xE0), (byte)(((rune.Value >> 6) & 0x3F) | 0x80), (byte)((rune.Value & 0x3F) | 0x80) }; } else { return new[] { (byte)((rune.Value >> 18) | 0xF0), (byte)(((rune.Value >> 12) & 0x3F) | 0x80), (byte)(((rune.Value >> 6) & 0x3F) | 0x80), (byte)((rune.Value & 0x3F) | 0x80) }; } } // !! IMPORTANT !! // Don't delete this implementation, as we use it as a reference to make sure the framework's // transcoding logic is correct. private static char[] ToUtf16(Rune rune) { Assert.True(Rune.IsValid(rune.Value), $"Rune with value U+{(uint)rune.Value:X4} is not well-formed."); if (rune.IsBmp) { return new[] { (char)rune.Value }; } else { return new[] { (char)((rune.Value >> 10) + 0xD800 - 0x40), (char)((rune.Value & 0x03FF) + 0xDC00) }; } } [Theory] [InlineData("", "")] // empty string is OK [InlineData(X_UTF16, X_UTF8)] [InlineData(E_ACUTE_UTF16, E_ACUTE_UTF8)] [InlineData(EURO_SYMBOL_UTF16, EURO_SYMBOL_UTF8)] public void ToBytes_WithSmallValidBuffers(string utf16Input, string expectedUtf8TranscodingHex) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf8, // so inputs should be less than 2 chars. Assert.InRange(utf16Input.Length, 0, 1); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Theory] [InlineData("AB")] // 2 ASCII chars, hits fast inner loop [InlineData("ABCD")] // 4 ASCII chars, hits fast inner loop [InlineData("ABCDEF")] // 6 ASCII chars, hits fast inner loop [InlineData("ABCDEFGH")] // 8 ASCII chars, hits fast inner loop [InlineData("ABCDEFGHIJ")] // 10 ASCII chars, hits fast inner loop [InlineData("ABCDEF" + E_ACUTE_UTF16 + "HIJ")] // interrupts inner loop due to non-ASCII char in first char of first DWORD [InlineData("ABCDEFG" + EURO_SYMBOL_UTF16 + "IJ")] // interrupts inner loop due to non-ASCII char in second char of first DWORD [InlineData("ABCDEFGH" + E_ACUTE_UTF16 + "J")] // interrupts inner loop due to non-ASCII char in first char of second DWORD [InlineData("ABCDEFGHI" + EURO_SYMBOL_UTF16)] // interrupts inner loop due to non-ASCII char in second char of second DWORD [InlineData(X_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then falls down to slow path [InlineData(X_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // drains first ASCII char then consumes 2x 2-byte sequences at once [InlineData(E_ACUTE_UTF16 + X_UTF16)] // no first ASCII char to drain, consumes 2-byte seq followed by ASCII char [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // stay within 2x 2-byte sequence processing loop [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in second char of DWORD [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + X_UTF16 + X_UTF16)] // break out of 2x 2-byte seq loop due to ASCII data in first char of DWORD [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // break out of 2x 2-byte seq loop due to 3-byte data [InlineData(E_ACUTE_UTF16 + EURO_SYMBOL_UTF16)] // 2-byte logic sees next char isn't ASCII, cannot read full DWORD from remaining input buffer, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16)] // 2x 3-byte logic can't read a full DWORD from next part of buffer, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + X_UTF16 + X_UTF16)] // 3-byte processing loop consumes trailing ASCII char, but can't read next DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16)] // 3-byte processing loop can't consume next ASCII char, can't read DWORD, falls down to slow drain loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // stay within 2x 3-byte sequence processing loop [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at beginning of DWORD after 2x 3-byte sequence [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + X_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // consume stray ASCII char at end of DWORD after 2x 3-byte sequence [InlineData(EURO_SYMBOL_UTF16 + E_ACUTE_UTF16 + X_UTF16)] // consume 2-byte sequence as second char in DWORD which begins with 3-byte encoded char [InlineData(EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 3-byte sequence followed by 4-byte sequence [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + GRINNING_FACE_UTF16)] // 2x 3-byte sequence followed by 4-byte sequence [InlineData(GRINNING_FACE_UTF16)] // single 4-byte surrogate char pair [InlineData(GRINNING_FACE_UTF16 + EURO_SYMBOL_UTF16)] // 4-byte surrogate char pair, cannot read next DWORD, falls down to slow drain loop public void ToBytes_WithLargeValidBuffers(string utf16Input) { // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8, // so inputs should be at least 2 chars. Assert.True(utf16Input.Length >= 2); // We're going to run the tests with destination buffer lengths ranging from 0 all the way // to buffers large enough to hold the full output. This allows us to test logic that // detects whether we're about to overrun our destination buffer and instead returns DestinationTooSmall. Rune[] enumeratedScalars = utf16Input.EnumerateRunes().ToArray(); // 0-length buffer test ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumCharsRead: 0, expectedUtf8Transcoding: ReadOnlySpan<byte>.Empty); int expectedNumCharsConsumed = 0; byte[] concatenatedUtf8 = Array.Empty<byte>(); for (int i = 0; i < enumeratedScalars.Length; i++) { Rune thisScalar = enumeratedScalars[i]; // provide partial destination buffers all the way up to (but not including) enough to hold the next full scalar encoding for (int j = 1; j < thisScalar.Utf8SequenceLength; j++) { ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length + j, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: concatenatedUtf8); } // now provide a destination buffer large enough to hold the next full scalar encoding expectedNumCharsConsumed += thisScalar.Utf16SequenceLength; concatenatedUtf8 = concatenatedUtf8.Concat(ToUtf8(thisScalar)).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (i == enumeratedScalars.Length - 1) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: concatenatedUtf8); } // now throw lots of ASCII data at the beginning so that we exercise the vectorized code paths utf16Input = new string('x', 64) + utf16Input; concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: concatenatedUtf8); // now throw some non-ASCII data at the beginning so that we *don't* exercise the vectorized code paths utf16Input = WOMAN_CARTWHEELING_MEDSKIN_UTF16 + utf16Input[64..]; concatenatedUtf8 = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: concatenatedUtf8.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: concatenatedUtf8); } [Theory] [InlineData('\uD800', OperationStatus.NeedMoreData)] // standalone high surrogate [InlineData('\uDFFF', OperationStatus.InvalidData)] // standalone low surrogate public void ToBytes_WithOnlyStandaloneSurrogates(char charValue, OperationStatus expectedOperationStatus) { ToBytes_Test_Core( utf16Input: new[] { charValue }, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: expectedOperationStatus, expectedNumCharsRead: 0, expectedUtf8Transcoding: Span<byte>.Empty); } [Theory] [InlineData("<LOW><HIGH>", 0, "")] // swapped surrogate pair characters [InlineData("A<LOW><HIGH>", 1, "41")] // consume standalone ASCII char, then swapped surrogate pair characters [InlineData("A<HIGH>B", 1, "41")] // consume standalone ASCII char, then standalone high surrogate char [InlineData("A<LOW>B", 1, "41")] // consume standalone ASCII char, then standalone low surrogate char [InlineData("AB<HIGH><HIGH>", 2, "4142")] // consume two ASCII chars, then standalone high surrogate char [InlineData("AB<LOW><LOW>", 2, "4142")] // consume two ASCII chars, then standalone low surrogate char public void ToBytes_WithInvalidSurrogates(string utf16Input, int expectedNumCharsConsumed, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf8, // so inputs should be at least 2 chars. Assert.True(utf16Input.Length >= 2); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: (expectedUtf8TranscodingHex.Length) / 2 + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Theory] [InlineData("<LOW><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete high surr. [InlineData("<HIGH><HIGH>", REPLACEMENT_CHAR_UTF8)] // standalone high surr. and incomplete high surr. [InlineData("<LOW><LOW>", REPLACEMENT_CHAR_UTF8 + REPLACEMENT_CHAR_UTF8)] // standalone low surr. and incomplete low surr. [InlineData("A<LOW>B<LOW>C<HIGH>D", "41" + REPLACEMENT_CHAR_UTF8 + "42" + REPLACEMENT_CHAR_UTF8 + "43" + REPLACEMENT_CHAR_UTF8 + "44")] // standalone low, low, high surrounded by other data public void ToBytes_WithReplacements(string utf16Input, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); bool isFinalCharHighSurrogate = char.IsHighSurrogate(utf16Input.Last()); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: (isFinalCharHighSurrogate) ? OperationStatus.NeedMoreData : OperationStatus.Done, expectedNumCharsRead: (isFinalCharHighSurrogate) ? (utf16Input.Length - 1) : utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); if (isFinalCharHighSurrogate) { // Also test with isFinalChunk = true ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2 + Rune.ReplacementChar.Utf8SequenceLength /* for replacement char */, replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: utf16Input.Length, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex + REPLACEMENT_CHAR_UTF8)); } } [Theory] [InlineData(E_ACUTE_UTF16 + "<LOW>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD [InlineData(E_ACUTE_UTF16 + "<LOW>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone low surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 1, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8)] // not enough output buffer to hold U+FFFD [InlineData(E_ACUTE_UTF16 + "<HIGH>", true, 2, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // replace standalone high surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>", false, 1, OperationStatus.NeedMoreData, E_ACUTE_UTF8)] // don't replace standalone high surr. at end [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 2, OperationStatus.DestinationTooSmall, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8)] // not enough output buffer to hold 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, true, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X' [InlineData(E_ACUTE_UTF16 + "<HIGH>" + X_UTF16, false, 3, OperationStatus.Done, E_ACUTE_UTF8 + REPLACEMENT_CHAR_UTF8 + X_UTF8)] // replacement followed by 'X' public void ToBytes_WithReplacements_AndCustomBufferSizes(string utf16Input, bool isFinalChunk, int expectedNumCharsConsumed, OperationStatus expectedOperationStatus, string expectedUtf8TranscodingHex) { // xUnit can't handle ill-formed strings in [InlineData], so we replace here. utf16Input = utf16Input.Replace("<HIGH>", "\uD800").Replace("<LOW>", "\uDFFF"); ToBytes_Test_Core( utf16Input: utf16Input, destinationSize: expectedUtf8TranscodingHex.Length / 2, replaceInvalidSequences: true, isFinalChunk: isFinalChunk, expectedOperationStatus: expectedOperationStatus, expectedNumCharsRead: expectedNumCharsConsumed, expectedUtf8Transcoding: DecodeHex(expectedUtf8TranscodingHex)); } [Fact] public void ToBytes_AllPossibleScalarValues() { ToBytes_Test_Core( utf16Input: s_allScalarsAsUtf16.Span, destinationSize: s_allScalarsAsUtf8.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumCharsRead: s_allScalarsAsUtf16.Length, expectedUtf8Transcoding: s_allScalarsAsUtf8.Span); } private static void ToBytes_Test_Core(ReadOnlySpan<char> utf16Input, int destinationSize, bool replaceInvalidSequences, bool isFinalChunk, OperationStatus expectedOperationStatus, int expectedNumCharsRead, ReadOnlySpan<byte> expectedUtf8Transcoding) { // Arrange using (BoundedMemory<char> boundedSource = BoundedMemory.AllocateFromExistingData(utf16Input)) using (BoundedMemory<byte> boundedDestination = BoundedMemory.Allocate<byte>(destinationSize)) { boundedSource.MakeReadonly(); // Act OperationStatus actualOperationStatus = Utf8.FromUtf16(boundedSource.Span, boundedDestination.Span, out int actualNumCharsRead, out int actualNumBytesWritten, replaceInvalidSequences, isFinalChunk); // Assert Assert.Equal(expectedOperationStatus, actualOperationStatus); Assert.Equal(expectedNumCharsRead, actualNumCharsRead); Assert.Equal(expectedUtf8Transcoding.Length, actualNumBytesWritten); Assert.Equal(expectedUtf8Transcoding.ToArray(), boundedDestination.Span.Slice(0, actualNumBytesWritten).ToArray()); } } [Theory] [InlineData("80", 0, "")] // sequence cannot begin with continuation character [InlineData("8182", 0, "")] // sequence cannot begin with continuation character [InlineData("838485", 0, "")] // sequence cannot begin with continuation character [InlineData(X_UTF8 + "80", 1, X_UTF16)] // sequence cannot begin with continuation character [InlineData(X_UTF8 + "8182", 1, X_UTF16)] // sequence cannot begin with continuation character [InlineData("C0", 0, "")] // [ C0 ] is always invalid [InlineData("C080", 0, "")] // [ C0 ] is always invalid [InlineData("C08081", 0, "")] // [ C0 ] is always invalid [InlineData(X_UTF8 + "C1", 1, X_UTF16)] // [ C1 ] is always invalid [InlineData(X_UTF8 + "C180", 1, X_UTF16)] // [ C1 ] is always invalid [InlineData(X_UTF8 + "C27F", 1, X_UTF16)] // [ C2 ] is improperly terminated [InlineData("E2827F", 0, "")] // [ E2 82 ] is improperly terminated [InlineData("E09F80", 0, "")] // [ E0 9F ... ] is overlong [InlineData("E0C080", 0, "")] // [ E0 ] is improperly terminated [InlineData("ED7F80", 0, "")] // [ ED ] is improperly terminated [InlineData("EDA080", 0, "")] // [ ED A0 ... ] is surrogate public void ToChars_WithSmallInvalidBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf16, // so inputs should be less than 4 bytes. Assert.InRange(utf8HexInput.Length, 0, 6); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] [InlineData("C2", 0, "")] // [ C2 ] is an incomplete sequence [InlineData("E282", 0, "")] // [ E2 82 ] is an incomplete sequence [InlineData(X_UTF8 + "C2", 1, X_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(X_UTF8 + "E0", 1, X_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(X_UTF8 + "E0BF", 1, X_UTF16)] // [ E0 BF ] is an incomplete sequence [InlineData(X_UTF8 + "F0", 1, X_UTF16)] // [ F0 ] is an incomplete sequence [InlineData(X_UTF8 + "F0BF", 1, X_UTF16)] // [ F0 BF ] is an incomplete sequence [InlineData(X_UTF8 + "F0BFA0", 1, X_UTF16)] // [ F0 BF A0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "C2", 2, E_ACUTE_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "E0", 2, E_ACUTE_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "F0", 2, E_ACUTE_UTF16)] // [ F0 ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "E0BF", 2, E_ACUTE_UTF16)] // [ E0 BF ] is an incomplete sequence [InlineData(E_ACUTE_UTF8 + "F0BF", 2, E_ACUTE_UTF16)] // [ F0 BF ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "C2", 3, EURO_SYMBOL_UTF16)] // [ C2 ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "E0", 3, EURO_SYMBOL_UTF16)] // [ E0 ] is an incomplete sequence [InlineData(EURO_SYMBOL_UTF8 + "F0", 3, EURO_SYMBOL_UTF16)] // [ F0 ] is an incomplete sequence public void ToChars_WithVariousIncompleteBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "slow processing" code path at the end of TranscodeToUtf16, // so inputs should be less than 4 bytes. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] /* SMALL VALID BUFFERS - tests drain loop at end of method */ [InlineData("")] // empty string is OK [InlineData("X")] [InlineData("XY")] [InlineData("XYZ")] [InlineData(E_ACUTE_UTF16)] [InlineData(X_UTF16 + E_ACUTE_UTF16)] [InlineData(E_ACUTE_UTF16 + X_UTF16)] [InlineData(EURO_SYMBOL_UTF16)] /* LARGE VALID BUFFERS - test main loop at beginning of method */ [InlineData(E_ACUTE_UTF16 + "ABCD" + "0123456789:;<=>?")] // Loop unrolling at end of buffer [InlineData(E_ACUTE_UTF16 + "ABCD" + "0123456789:;<=>?" + "01234567" + E_ACUTE_UTF16 + "89:;<=>?")] // Loop unrolling interrupted by non-ASCII [InlineData("ABC" + E_ACUTE_UTF16 + "0123")] // 3 ASCII bytes followed by non-ASCII [InlineData("AB" + E_ACUTE_UTF16 + "0123")] // 2 ASCII bytes followed by non-ASCII [InlineData("A" + E_ACUTE_UTF16 + "0123")] // 1 ASCII byte followed by non-ASCII [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // 4x 2-byte sequences, exercises optimization code path in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + "PQ")] // 3x 2-byte sequences + 2 ASCII bytes, exercises optimization code path in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + "PQ")] // single 2-byte sequence + 2 trailing ASCII bytes, exercises draining logic in 2-byte sequence processing [InlineData(E_ACUTE_UTF16 + "P" + E_ACUTE_UTF16 + "0@P")] // single 2-byte sequences + 1 trailing ASCII byte + 2-byte sequence, exercises draining logic in 2-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + "@")] // single 3-byte sequence + 1 trailing ASCII byte, exercises draining logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + "@P`")] // single 3-byte sequence + 3 trailing ASCII byte, exercises draining logic and "running out of data" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // 3x 3-byte sequences, exercises "stay within 3-byte loop" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16)] // 4x 3-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + E_ACUTE_UTF16)] // 3x 3-byte sequences + single 2-byte sequence, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(EURO_SYMBOL_UTF16 + EURO_SYMBOL_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16 + E_ACUTE_UTF16)] // 2x 3-byte sequences + 4x 2-byte sequences, exercises "consume multiple bytes at a time" logic in 3-byte sequence processing [InlineData(GRINNING_FACE_UTF16 + GRINNING_FACE_UTF16)] // 2x 4-byte sequences, exercises 4-byte sequence processing [InlineData(GRINNING_FACE_UTF16 + "@AB")] // single 4-byte sequence + 3 ASCII bytes, exercises 4-byte sequence processing and draining logic [InlineData(WOMAN_CARTWHEELING_MEDSKIN_UTF16)] // exercises switching between multiple sequence lengths public void ToChars_ValidBuffers(string utf16Input) { // We're going to run the tests with destination buffer lengths ranging from 0 all the way // to buffers large enough to hold the full output. This allows us to test logic that // detects whether we're about to overrun our destination buffer and instead returns DestinationTooSmall. Rune[] enumeratedScalars = utf16Input.EnumerateRunes().ToArray(); // Convert entire input to UTF-8 using our unit test reference logic. byte[] utf8Input = enumeratedScalars.SelectMany(ToUtf8).ToArray(); // 0-length buffer test ToChars_Test_Core( utf8Input: utf8Input, destinationSize: 0, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (utf8Input.Length == 0) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumBytesRead: 0, expectedUtf16Transcoding: ReadOnlySpan<char>.Empty); int expectedNumBytesConsumed = 0; char[] concatenatedUtf16 = Array.Empty<char>(); for (int i = 0; i < enumeratedScalars.Length; i++) { Rune thisScalar = enumeratedScalars[i]; // if this is an astral scalar value, quickly test a buffer that's not large enough to contain the entire UTF-16 encoding if (!thisScalar.IsBmp) { ToChars_Test_Core( utf8Input: utf8Input, destinationSize: concatenatedUtf16.Length + 1, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: concatenatedUtf16); } // now provide a destination buffer large enough to hold the next full scalar encoding expectedNumBytesConsumed += thisScalar.Utf8SequenceLength; concatenatedUtf16 = concatenatedUtf16.Concat(ToUtf16(thisScalar)).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: concatenatedUtf16.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: (i == enumeratedScalars.Length - 1) ? OperationStatus.Done : OperationStatus.DestinationTooSmall, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: concatenatedUtf16); } // now throw lots of ASCII data at the beginning so that we exercise the vectorized code paths utf16Input = new string('x', 64) + utf16Input; utf8Input = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: utf16Input.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8Input.Length, expectedUtf16Transcoding: utf16Input); // now throw some non-ASCII data at the beginning so that we *don't* exercise the vectorized code paths utf16Input = WOMAN_CARTWHEELING_MEDSKIN_UTF16 + utf16Input[64..]; utf8Input = utf16Input.EnumerateRunes().SelectMany(ToUtf8).ToArray(); ToChars_Test_Core( utf8Input: utf8Input, destinationSize: utf16Input.Length, replaceInvalidSequences: false, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8Input.Length, expectedUtf16Transcoding: utf16Input); } [Theory] [InlineData("3031" + "80" + "202122232425", 2, "01")] // Continuation character at start of sequence should match no bitmask [InlineData("3031" + "C080" + "2021222324", 2, "01")] // Overlong 2-byte sequence at start of DWORD [InlineData("3031" + "C180" + "2021222324", 2, "01")] // Overlong 2-byte sequence at start of DWORD [InlineData("C280" + "C180", 2, "\u0080")] // Overlong 2-byte sequence at end of DWORD [InlineData("C27F" + "C280", 0, "")] // Improperly terminated 2-byte sequence at start of DWORD [InlineData("C2C0" + "C280", 0, "")] // Improperly terminated 2-byte sequence at start of DWORD [InlineData("C280" + "C27F", 2, "\u0080")] // Improperly terminated 2-byte sequence at end of DWORD [InlineData("C280" + "C2C0", 2, "\u0080")] // Improperly terminated 2-byte sequence at end of DWORD [InlineData("C280" + "C280" + "80203040", 4, "\u0080\u0080")] // Continuation character at start of sequence, within "stay in 2-byte processing" optimization [InlineData("C280" + "C280" + "C180" + "C280", 4, "\u0080\u0080")] // Overlong 2-byte sequence at start of DWORD, within "stay in 2-byte processing" optimization [InlineData("C280" + "C280" + "C280" + "C180", 6, "\u0080\u0080\u0080")] // Overlong 2-byte sequence at end of DWORD, within "stay in 2-byte processing" optimization [InlineData("3031" + "E09F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Overlong 3-byte sequence at start of DWORD [InlineData("3031" + "E07F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E0C080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E17F80" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "E1C080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Improperly terminated 3-byte sequence at start of DWORD [InlineData("3031" + "EDA080" + EURO_SYMBOL_UTF8 + EURO_SYMBOL_UTF8, 2, "01")] // Surrogate 3-byte sequence at start of DWORD [InlineData("3031" + "E69C88" + "E59B" + "E69C88", 5, "01\u6708")] // Incomplete 3-byte sequence surrounded by valid 3-byte sequences [InlineData("3031" + "F5808080", 2, "01")] // [ F5 ] is always invalid [InlineData("3031" + "F6808080", 2, "01")] // [ F6 ] is always invalid [InlineData("3031" + "F7808080", 2, "01")] // [ F7 ] is always invalid [InlineData("3031" + "F8808080", 2, "01")] // [ F8 ] is always invalid [InlineData("3031" + "F9808080", 2, "01")] // [ F9 ] is always invalid [InlineData("3031" + "FA808080", 2, "01")] // [ FA ] is always invalid [InlineData("3031" + "FB808080", 2, "01")] // [ FB ] is always invalid [InlineData("3031" + "FC808080", 2, "01")] // [ FC ] is always invalid [InlineData("3031" + "FD808080", 2, "01")] // [ FD ] is always invalid [InlineData("3031" + "FE808080", 2, "01")] // [ FE ] is always invalid [InlineData("3031" + "FF808080", 2, "01")] // [ FF ] is always invalid public void ToChars_WithLargeInvalidBuffers(string utf8HexInput, int expectedNumBytesConsumed, string expectedUtf16Transcoding) { // These test cases are for the "fast processing" code which is the main loop of TranscodeToUtf16, // so inputs should be less >= 4 bytes. Assert.True(utf8HexInput.Length >= 8); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); // Now try the tests again with a larger buffer. // This ensures that running out of destination space wasn't the reason we failed. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length + 16, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.InvalidData, expectedNumBytesRead: expectedNumBytesConsumed, expectedUtf16Transcoding: expectedUtf16Transcoding); } [Theory] [InlineData(X_UTF8 + "80" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // stray continuation byte [ 80 ] [InlineData(X_UTF8 + "FF" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // invalid UTF-8 byte [ FF ] [InlineData(X_UTF8 + "C2" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // 2-byte sequence starter [ C2 ] not followed by continuation byte [InlineData(X_UTF8 + "C1C180" + X_UTF8, X_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ C1 80 ] is overlong but consists of two maximal invalid subsequences, each of length 1 byte [InlineData(X_UTF8 + E_ACUTE_UTF8 + "E08080", X_UTF16 + E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16)] // [ E0 80 ] is overlong 2-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] is stray continuation byte [InlineData(GRINNING_FACE_UTF8 + "F08F8080" + GRINNING_FACE_UTF8, GRINNING_FACE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + GRINNING_FACE_UTF16)] // [ F0 8F ] is overlong 4-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] instances are stray continuation bytes [InlineData(GRINNING_FACE_UTF8 + "F4908080" + GRINNING_FACE_UTF8, GRINNING_FACE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + GRINNING_FACE_UTF16)] // [ F4 90 ] is out-of-range 4-byte sequence (1 byte maximal invalid subsequence), and following [ 80 ] instances are stray continuation bytes [InlineData(E_ACUTE_UTF8 + "EDA0" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ ED A0 ] is encoding of UTF-16 surrogate code point, so consists of two maximal invalid subsequences, each of length 1 byte [InlineData(E_ACUTE_UTF8 + "ED80" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ ED 80 ] is incomplete 3-byte sequence, so is 2-byte maximal invalid subsequence [InlineData(E_ACUTE_UTF8 + "F380" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ F3 80 ] is incomplete 4-byte sequence, so is 2-byte maximal invalid subsequence [InlineData(E_ACUTE_UTF8 + "F38080" + X_UTF8, E_ACUTE_UTF16 + REPLACEMENT_CHAR_UTF16 + X_UTF16)] // [ F3 80 80 ] is incomplete 4-byte sequence, so is 3-byte maximal invalid subsequence public void ToChars_WithReplacement(string utf8HexInput, string expectedUtf16Transcoding) { // First run the test with isFinalBlock = false, // both with and without some bytes of incomplete trailing data. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: false, expectedOperationStatus: OperationStatus.NeedMoreData, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); // Then run the test with isFinalBlock = true, with incomplete trailing data. ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length, replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.DestinationTooSmall, expectedNumBytesRead: utf8HexInput.Length / 2, expectedUtf16Transcoding: expectedUtf16Transcoding); ToChars_Test_Core( utf8Input: DecodeHex(utf8HexInput + "E0BF" /* trailing data */), destinationSize: expectedUtf16Transcoding.Length + 1, // allow room for U+FFFD replaceInvalidSequences: true, isFinalChunk: true, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: utf8HexInput.Length / 2 + 2, expectedUtf16Transcoding: expectedUtf16Transcoding + REPLACEMENT_CHAR_UTF16); } [Fact] public void ToChars_AllPossibleScalarValues() { ToChars_Test_Core( utf8Input: s_allScalarsAsUtf8.Span, destinationSize: s_allScalarsAsUtf16.Length, replaceInvalidSequences: false, isFinalChunk: false, expectedOperationStatus: OperationStatus.Done, expectedNumBytesRead: s_allScalarsAsUtf8.Length, expectedUtf16Transcoding: s_allScalarsAsUtf16.Span); } private static void ToChars_Test_Core(ReadOnlySpan<byte> utf8Input, int destinationSize, bool replaceInvalidSequences, bool isFinalChunk, OperationStatus expectedOperationStatus, int expectedNumBytesRead, ReadOnlySpan<char> expectedUtf16Transcoding) { // Arrange using (BoundedMemory<byte> boundedSource = BoundedMemory.AllocateFromExistingData(utf8Input)) using (BoundedMemory<char> boundedDestination = BoundedMemory.Allocate<char>(destinationSize)) { boundedSource.MakeReadonly(); // Act OperationStatus actualOperationStatus = Utf8.ToUtf16(boundedSource.Span, boundedDestination.Span, out int actualNumBytesRead, out int actualNumCharsWritten, replaceInvalidSequences, isFinalChunk); // Assert Assert.Equal(expectedOperationStatus, actualOperationStatus); Assert.Equal(expectedNumBytesRead, actualNumBytesRead); Assert.Equal(expectedUtf16Transcoding.Length, actualNumCharsWritten); Assert.Equal(expectedUtf16Transcoding.ToString(), boundedDestination.Span.Slice(0, actualNumCharsWritten).ToString()); } } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System/TimeZoneInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public static partial class TimeZoneInfoTests { private static readonly bool s_isWindows = OperatingSystem.IsWindows(); private static readonly bool s_isOSX = OperatingSystem.IsMacOS(); private static string s_strPacific = s_isWindows ? "Pacific Standard Time" : "America/Los_Angeles"; private static string s_strSydney = s_isWindows ? "AUS Eastern Standard Time" : "Australia/Sydney"; private static string s_strGMT = s_isWindows ? "GMT Standard Time" : "Europe/London"; private static string s_strTonga = s_isWindows ? "Tonga Standard Time" : "Pacific/Tongatapu"; private static string s_strBrasil = s_isWindows ? "E. South America Standard Time" : "America/Sao_Paulo"; private static string s_strPerth = s_isWindows ? "W. Australia Standard Time" : "Australia/Perth"; private static string s_strBrasilia = s_isWindows ? "E. South America Standard Time" : "America/Sao_Paulo"; private static string s_strNairobi = s_isWindows ? "E. Africa Standard Time" : "Africa/Nairobi"; private static string s_strAmsterdam = s_isWindows ? "W. Europe Standard Time" : "Europe/Berlin"; private static string s_strRussian = s_isWindows ? "Russian Standard Time" : "Europe/Moscow"; private static string s_strLibya = s_isWindows ? "Libya Standard Time" : "Africa/Tripoli"; private static string s_strJohannesburg = s_isWindows ? "South Africa Standard Time" : "Africa/Johannesburg"; private static string s_strCasablanca = s_isWindows ? "Morocco Standard Time" : "Africa/Casablanca"; private static string s_strCatamarca = s_isWindows ? "Argentina Standard Time" : "America/Argentina/Catamarca"; private static string s_strLisbon = s_isWindows ? "GMT Standard Time" : "Europe/Lisbon"; private static string s_strNewfoundland = s_isWindows ? "Newfoundland Standard Time" : "America/St_Johns"; private static string s_strIran = s_isWindows ? "Iran Standard Time" : "Asia/Tehran"; private static string s_strFiji = s_isWindows ? "Fiji Standard Time" : "Pacific/Fiji"; private static TimeZoneInfo s_myUtc = TimeZoneInfo.Utc; private static TimeZoneInfo s_myLocal = TimeZoneInfo.Local; private static TimeZoneInfo s_regLocal = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id); // in case DST is disabled on Local private static TimeZoneInfo s_GMTLondon = TimeZoneInfo.FindSystemTimeZoneById(s_strGMT); private static TimeZoneInfo s_nairobiTz = TimeZoneInfo.FindSystemTimeZoneById(s_strNairobi); private static TimeZoneInfo s_amsterdamTz = TimeZoneInfo.FindSystemTimeZoneById(s_strAmsterdam); private static TimeZoneInfo s_johannesburgTz = TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg); private static TimeZoneInfo s_casablancaTz = TimeZoneInfo.FindSystemTimeZoneById(s_strCasablanca); private static TimeZoneInfo s_catamarcaTz = TimeZoneInfo.FindSystemTimeZoneById(s_strCatamarca); private static TimeZoneInfo s_LisbonTz = TimeZoneInfo.FindSystemTimeZoneById(s_strLisbon); private static TimeZoneInfo s_NewfoundlandTz = TimeZoneInfo.FindSystemTimeZoneById(s_strNewfoundland); private static bool s_localIsPST = TimeZoneInfo.Local.Id == s_strPacific; private static bool s_regLocalSupportsDST = s_regLocal.SupportsDaylightSavingTime; private static bool s_localSupportsDST = TimeZoneInfo.Local.SupportsDaylightSavingTime; // In 2006, Australia delayed ending DST by a week. However, Windows says it still ended the last week of March. private static readonly int s_sydneyOffsetLastWeekOfMarch2006 = s_isWindows ? 10 : 11; [Fact] public static void Kind() { TimeZoneInfo tzi = TimeZoneInfo.Local; Assert.Equal(tzi, TimeZoneInfo.Local); tzi = TimeZoneInfo.Utc; Assert.Equal(tzi, TimeZoneInfo.Utc); } [Fact] public static void Names() { TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo utc = TimeZoneInfo.Utc; Assert.NotNull(local.DaylightName); Assert.NotNull(local.DisplayName); Assert.NotNull(local.StandardName); Assert.NotNull(local.ToString()); Assert.NotNull(utc.DaylightName); Assert.NotNull(utc.DisplayName); Assert.NotNull(utc.StandardName); Assert.NotNull(utc.ToString()); } // Due to ICU size limitations, full daylight/standard names are not included for the browser. // Name abbreviations, if available, are used instead public static IEnumerable<object []> Platform_TimeZoneNamesTestData() { if (PlatformDetection.IsBrowser || PlatformDetection.IsiOS || PlatformDetection.IstvOS) return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) America/Los_Angeles", "PST", "PDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Australia/Sydney", "AEST", "AEDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Australia/Perth", "AWST", "AWDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Asia/Tehran", "+0330", "+0430" }, { s_NewfoundlandTz, "(UTC-03:30) America/St_Johns", "NST", "NDT" }, { s_catamarcaTz, "(UTC-03:00) America/Argentina/Catamarca", "-03", "-02" } }; else if (PlatformDetection.IsWindows) return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) Pacific Time (US & Canada)", "Pacific Standard Time", "Pacific Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Canberra, Melbourne, Sydney", "AUS Eastern Standard Time", "AUS Eastern Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Perth", "W. Australia Standard Time", "W. Australia Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Tehran", "Iran Standard Time", "Iran Daylight Time" }, { s_NewfoundlandTz, "(UTC-03:30) Newfoundland", "Newfoundland Standard Time", "Newfoundland Daylight Time" }, { s_catamarcaTz, "(UTC-03:00) City of Buenos Aires", "Argentina Standard Time", "Argentina Daylight Time" } }; else return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) Pacific Time (Los Angeles)", "Pacific Standard Time", "Pacific Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Eastern Australia Time (Sydney)", "Australian Eastern Standard Time", "Australian Eastern Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Australian Western Standard Time (Perth)", "Australian Western Standard Time", "Australian Western Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Iran Time", "Iran Standard Time", "Iran Daylight Time" }, { s_NewfoundlandTz, "(UTC-03:30) Newfoundland Time (St. John’s)", "Newfoundland Standard Time", "Newfoundland Daylight Time" }, { s_catamarcaTz, "(UTC-03:00) Argentina Standard Time (Catamarca)", "Argentina Standard Time", "Argentina Summer Time" } }; } // We test the existence of a specific English time zone name to avoid failures on non-English platforms. [ConditionalTheory(nameof(IsEnglishUILanguage))] [MemberData(nameof(Platform_TimeZoneNamesTestData))] public static void Platform_TimeZoneNames(TimeZoneInfo tzi, string displayName, string standardName, string daylightName) { // Edge case - Optionally allow some characters to be absent in the display name. const string chars = ".’"; foreach (char c in chars) { if (displayName.Contains(c, StringComparison.Ordinal) && !tzi.DisplayName.Contains(c, StringComparison.Ordinal)) { displayName = displayName.Replace(c.ToString(), "", StringComparison.Ordinal); } } Assert.Equal($"DisplayName: \"{displayName}\", StandardName: {standardName}\", DaylightName: {daylightName}\"", $"DisplayName: \"{tzi.DisplayName}\", StandardName: {tzi.StandardName}\", DaylightName: {tzi.DaylightName}\""); } [Fact] public static void ConvertTime() { TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo utc = TimeZoneInfo.Utc; DateTime dt = TimeZoneInfo.ConvertTime(DateTime.Today, utc); Assert.Equal(DateTime.Today, TimeZoneInfo.ConvertTime(dt, local)); DateTime today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Utc); dt = TimeZoneInfo.ConvertTime(today, local); Assert.Equal(today, TimeZoneInfo.ConvertTime(dt, utc)); } [Fact] public static void LibyaTimeZone() { TimeZoneInfo tripoli; // Make sure first the timezone data is updated in the machine as it should include Libya Timezone try { tripoli = TimeZoneInfo.FindSystemTimeZoneById(s_strLibya); } catch (Exception /* TimeZoneNotFoundException in netstandard1.7 test*/ ) { // Libya time zone not found Console.WriteLine("Warning: Libya time zone is not exist in this machine"); return; } var startOf2012 = new DateTime(2012, 1, 1, 0, 0, 0, DateTimeKind.Utc); var endOf2011 = startOf2012.AddTicks(-1); DateTime libyaLocalTime = TimeZoneInfo.ConvertTime(endOf2011, tripoli); DateTime expectResult = new DateTime(2012, 1, 1, 2, 0, 0).AddTicks(-1); Assert.True(libyaLocalTime.Equals(expectResult), string.Format("Expected {0} and got {1}", expectResult, libyaLocalTime)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void TestYukonTZ() { try { TimeZoneInfo yukon = TimeZoneInfo.FindSystemTimeZoneById("Yukon Standard Time"); // First, ensure we have the updated data TimeZoneInfo.AdjustmentRule [] rules = yukon.GetAdjustmentRules(); if (rules.Length <= 0 || rules[rules.Length - 1].DateStart.Year != 2021 || rules[rules.Length - 1].DateEnd.Year != 9999) { return; } TimeSpan minus7HoursSpan = new TimeSpan(-7, 0, 0); DateTimeOffset midnight = new DateTimeOffset(2021, 1, 1, 0, 0, 0, 0, minus7HoursSpan); DateTimeOffset beforeMidnight = new DateTimeOffset(2020, 12, 31, 23, 59, 59, 999, minus7HoursSpan); DateTimeOffset before1AM = new DateTimeOffset(2021, 1, 1, 0, 59, 59, 999, minus7HoursSpan); DateTimeOffset at1AM = new DateTimeOffset(2021, 1, 1, 1, 0, 0, 0, minus7HoursSpan); DateTimeOffset midnight2022 = new DateTimeOffset(2022, 1, 1, 0, 0, 0, 0, minus7HoursSpan); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(midnight)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(beforeMidnight)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(before1AM)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(at1AM)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(midnight2022)); } catch (TimeZoneNotFoundException) { // Some Windows versions don't carry the complete TZ data. Ignore the tests on such versions. } } [Fact] public static void RussianTimeZone() { TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(s_strRussian); var inputUtcDate = new DateTime(2013, 6, 1, 0, 0, 0, DateTimeKind.Utc); DateTime russiaTime = TimeZoneInfo.ConvertTime(inputUtcDate, tz); DateTime expectResult = new DateTime(2013, 6, 1, 4, 0, 0); Assert.True(russiaTime.Equals(expectResult), string.Format("Expected {0} and got {1}", expectResult, russiaTime)); DateTime dt = new DateTime(2011, 12, 31, 23, 30, 0); TimeSpan o = tz.GetUtcOffset(dt); Assert.True(o.Equals(TimeSpan.FromHours(4)), string.Format("Expected {0} and got {1}", TimeSpan.FromHours(4), o)); } [Fact] public static void CaseInsensitiveLookup() { Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strBrasilia), TimeZoneInfo.FindSystemTimeZoneById(s_strBrasilia.ToLowerInvariant())); Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg), TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg.ToUpperInvariant())); // Populate internal cache with all timezones. The implementation takes different path for lookup by id // when all timezones are populated. TimeZoneInfo.GetSystemTimeZones(); // The timezones used for the tests after GetSystemTimeZones calls have to be different from the ones used before GetSystemTimeZones to // exercise the rare path. Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), TimeZoneInfo.FindSystemTimeZoneById(s_strSydney.ToLowerInvariant())); Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), TimeZoneInfo.FindSystemTimeZoneById(s_strPerth.ToUpperInvariant())); } [Fact] public static void ConvertTime_DateTimeOffset_Invalid() { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<ArgumentNullException>(time1, null); // We catch TimeZoneNotFoundException in then netstandard1.7 tests VerifyConvertException<Exception>(time1, string.Empty); VerifyConvertException<Exception>(time1, " "); VerifyConvertException<Exception>(time1, "\0"); VerifyConvertException<Exception>(time1, "Pacific"); // whole string must match VerifyConvertException<Exception>(time1, "Pacific Standard Time Zone"); // no extra characters VerifyConvertException<Exception>(time1, " Pacific Standard Time"); // no leading space VerifyConvertException<Exception>(time1, "Pacific Standard Time "); // no trailing space VerifyConvertException<Exception>(time1, "\0Pacific Standard Time"); // no leading null VerifyConvertException<Exception>(time1, "Pacific Standard Time\0"); // no trailing null VerifyConvertException<Exception>(time1, "Pacific Standard Time\\ "); // no trailing null VerifyConvertException<Exception>(time1, "Pacific Standard Time\\Display"); VerifyConvertException<Exception>(time1, "Pacific Standard Time\n"); // no trailing newline VerifyConvertException<Exception>(time1, new string('a', 256)); // long string } [Fact] public static void ConvertTime_DateTimeOffset_NearMinMaxValue() { VerifyConvert(DateTimeOffset.MaxValue, TimeZoneInfo.Utc.Id, DateTimeOffset.MaxValue); VerifyConvert(DateTimeOffset.MaxValue, s_strPacific, new DateTimeOffset(DateTime.MaxValue.AddHours(-8), new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue, s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(new DateTimeOffset(DateTime.MaxValue, new TimeSpan(5, 0, 0)), s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0)), s_strSydney, new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue.AddHours(-11), s_strSydney, new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue.AddHours(-11.5), s_strSydney, new DateTimeOffset(DateTime.MaxValue.AddHours(-0.5), new TimeSpan(11, 0, 0))); VerifyConvert(new DateTimeOffset(DateTime.MaxValue.AddHours(-5), new TimeSpan(3, 0, 0)), s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(DateTimeOffset.MinValue, TimeZoneInfo.Utc.Id, DateTimeOffset.MinValue); VerifyConvert(DateTimeOffset.MinValue, s_strSydney, new DateTimeOffset(DateTime.MinValue.AddHours(10), new TimeSpan(10, 0, 0))); VerifyConvert(DateTimeOffset.MinValue, s_strPacific, DateTimeOffset.MinValue); VerifyConvert(new DateTimeOffset(DateTime.MinValue, new TimeSpan(-3, 0, 0)), s_strPacific, DateTimeOffset.MinValue); VerifyConvert(new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0)), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MinValue.AddHours(8), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MinValue.AddHours(8.5), s_strPacific, new DateTimeOffset(DateTime.MinValue.AddHours(0.5), new TimeSpan(-8, 0, 0))); VerifyConvert(new DateTimeOffset(DateTime.MinValue.AddHours(5), new TimeSpan(-3, 0, 0)), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTime.MaxValue, s_strPacific, s_strSydney, DateTime.MaxValue); VerifyConvert(DateTime.MaxValue.AddHours(-19), s_strPacific, s_strSydney, DateTime.MaxValue); VerifyConvert(DateTime.MaxValue.AddHours(-19.5), s_strPacific, s_strSydney, DateTime.MaxValue.AddHours(-0.5)); VerifyConvert(DateTime.MinValue, s_strSydney, s_strPacific, DateTime.MinValue); TimeSpan earlyTimesDifference = GetEarlyTimesOffset(s_strSydney) - GetEarlyTimesOffset(s_strPacific); VerifyConvert(DateTime.MinValue + earlyTimesDifference, s_strSydney, s_strPacific, DateTime.MinValue); VerifyConvert(DateTime.MinValue.AddHours(0.5) + earlyTimesDifference, s_strSydney, s_strPacific, DateTime.MinValue.AddHours(0.5)); } [Fact] public static void ConvertTime_DateTimeOffset_VariousSystemTimeZones() { var time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-7, 0, 0)); var time2 = new DateTimeOffset(2006, 5, 12, 22, 17, 42, new TimeSpan(10, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2006, 3, 14, 9, 47, 12, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(2006, 3, 15, 4, 47, 12, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(2006, 11, 5, 20, 3, 0, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(1987, 1, 1, 2, 3, 0, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(1987, 1, 1, 21, 3, 0, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2001, 5, 12, 5, 17, 42, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2001, 5, 12, 17, 17, 42, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 5, 19, 20, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 17, 19, 20, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 1, 20, 1, new TimeSpan(0, 0, 0)); var time1a = new DateTimeOffset(2003, 3, 30, 2, 20, 1, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 14, 20, 1, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time1a, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1a); VerifyConvert(time1, s_strGMT, time1a); // invalid hour VerifyConvert(time1a, s_strGMT, time1a); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 0, 0, 23, new TimeSpan(0, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 13, 0, 23, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 1, 30, 0, new TimeSpan(0)); // ambiguous (STD) time1a = new DateTimeOffset(2003, 10, 26, 1, 30, 0, new TimeSpan(1, 0, 0)); // ambiguous (DLT) time2 = new DateTimeOffset(2003, 10, 26, 14, 30, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); VerifyConvert(time1a, s_strTonga, time2.AddHours(-1)); VerifyConvert(time1a, s_strGMT, time1a); time1 = new DateTimeOffset(2003, 10, 25, 14, 0, 0, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 10, 26, 2, 0, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 2, 20, 0, new TimeSpan(0)); time2 = new DateTimeOffset(2003, 10, 26, 15, 20, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(0)); time2 = new DateTimeOffset(2003, 10, 26, 16, 0, 1, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); var time3 = new DateTime(2001, 5, 12, 5, 17, 42); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(12)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 3, 30, 5, 19, 20); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(12)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 3, 30, 1, 20, 1); VerifyConvertException<ArgumentException>(time3, s_strGMT, s_strTonga); // invalid time VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 3, 30, 0, 0, 23); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 10, 26, 2, 0, 0); // ambiguous VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 10, 26, 2, 20, 0); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); // ambiguous VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 10, 26, 3, 0, 1); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); // Iran has Utc offset 4:30 during the DST and 3:30 during standard time. time3 = new DateTime(2018, 4, 20, 7, 0, 0, DateTimeKind.Utc); VerifyConvert(time3, s_strIran, time3.AddHours(4.5), DateTimeKind.Unspecified); // DST time time3 = new DateTime(2018, 1, 20, 7, 0, 0, DateTimeKind.Utc); VerifyConvert(time3, s_strIran, time3.AddHours(3.5), DateTimeKind.Unspecified); // DST time } [Fact] public static void ConvertTime_SameTimeZones() { var time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 10, 15, 2, 30, 0, new TimeSpan(-2, 0, 0)); // invalid VerifyConvert(time1, s_strBrasil, time1.ToOffset(new TimeSpan(-3, 0, 0))); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-3, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-2, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-7, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(1964, 6, 19, 12, 45, 10, new TimeSpan(0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.ToUniversalTime()); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.ToUniversalTime()); } [Fact] public static void ConvertTime_DateTime_NearMinAndMaxValue() { DateTime time1 = new DateTime(2006, 5, 12); DateTime utcMaxValue = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc); VerifyConvert(utcMaxValue, s_strSydney, DateTime.MaxValue); VerifyConvert(utcMaxValue.AddHours(-11), s_strSydney, DateTime.MaxValue); VerifyConvert(utcMaxValue.AddHours(-11.5), s_strSydney, DateTime.MaxValue.AddHours(-0.5)); VerifyConvert(utcMaxValue, s_strPacific, DateTime.MaxValue.AddHours(-8)); DateTime utcMinValue = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc); VerifyConvert(utcMinValue, s_strPacific, DateTime.MinValue); TimeSpan earlyTimesOffsetPacific = GetEarlyTimesOffset(s_strPacific); earlyTimesOffsetPacific = earlyTimesOffsetPacific.Negate(); // Pacific is behind UTC, so negate for a positive value VerifyConvert(utcMinValue + earlyTimesOffsetPacific, s_strPacific, DateTime.MinValue); VerifyConvert(utcMinValue.AddHours(0.5) + earlyTimesOffsetPacific, s_strPacific, DateTime.MinValue.AddHours(0.5)); TimeSpan earlyTimesOffsetSydney = GetEarlyTimesOffset(s_strSydney); VerifyConvert(utcMinValue, s_strSydney, DateTime.MinValue + earlyTimesOffsetSydney); } [Fact] public static void ConverTime_DateTime_VariousSystemTimeZonesTest() { var time1utc = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Utc); var time1 = new DateTime(2006, 5, 12, 5, 17, 42); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-7)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(10)); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); VerifyConvert(time1utc, s_strTonga, time1.AddHours(13)); time1utc = new DateTime(2006, 3, 28, 9, 47, 12, DateTimeKind.Utc); time1 = new DateTime(2006, 3, 28, 9, 47, 12); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(s_sydneyOffsetLastWeekOfMarch2006)); time1utc = new DateTime(2006, 11, 5, 1, 3, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 11, 5, 1, 3, 0); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(11)); time1utc = new DateTime(1987, 1, 1, 2, 3, 0, DateTimeKind.Utc); time1 = new DateTime(1987, 1, 1, 2, 3, 0); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(11)); time1utc = new DateTime(2003, 3, 30, 0, 0, 23, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 0, 0, 23); VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2003, 3, 30, 2, 0, 24, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 2, 0, 24); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); time1utc = new DateTime(2003, 3, 30, 5, 19, 20, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 5, 19, 20); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); time1utc = new DateTime(2003, 10, 26, 2, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 2, 0, 0); // ambiguous VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2003, 10, 26, 2, 20, 0, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 2, 20, 0); VerifyConvert(time1utc, s_strGMT, time1); // ambiguous time1utc = new DateTime(2003, 10, 26, 3, 0, 1, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 3, 0, 1); VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2005, 3, 30, 0, 0, 23, DateTimeKind.Utc); time1 = new DateTime(2005, 3, 30, 0, 0, 23); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1 = new DateTime(2006, 5, 12, 5, 17, 42); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(17)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-17)); time1 = new DateTime(2006, 3, 28, 9, 47, 12); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(s_sydneyOffsetLastWeekOfMarch2006 + 8)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-(s_sydneyOffsetLastWeekOfMarch2006 + 8))); time1 = new DateTime(2006, 11, 5, 1, 3, 0); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(19)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-19)); time1 = new DateTime(1987, 1, 1, 2, 3, 0); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(19)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-19)); } [Fact] public static void ConvertTime_DateTime_PerthRules() { var time1utc = new DateTime(2005, 12, 31, 15, 59, 59, DateTimeKind.Utc); var time1 = new DateTime(2005, 12, 31, 15, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 16, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 16, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 16, 30, 0, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 16, 30, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 23, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 23, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2006, 1, 1, 0, 1, 1, DateTimeKind.Utc); time1 = new DateTime(2006, 1, 1, 0, 1, 1); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // 2006 rule in effect time1utc = new DateTime(2006, 5, 12, 2, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 5, 12, 2, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // begin dst time1utc = new DateTime(2006, 11, 30, 17, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2006, 11, 30, 17, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2006, 11, 30, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 1, 2, 0, 0); VerifyConvert(time1utc, s_strPerth, time1); time1utc = new DateTime(2006, 12, 31, 15, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 31, 15, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); // 2007 rule time1utc = new DateTime(2006, 12, 31, 20, 1, 2, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 31, 20, 1, 2); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); // end dst time1utc = new DateTime(2007, 3, 24, 16, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 16, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); time1utc = new DateTime(2007, 3, 24, 17, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 17, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); time1utc = new DateTime(2007, 3, 24, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 18, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2007, 3, 24, 19, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 19, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // begin dst time1utc = new DateTime(2008, 10, 25, 17, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2008, 10, 25, 17, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2008, 10, 25, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2008, 10, 25, 18, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); } [Fact] public static void ConvertTime_DateTime_UtcToUtc() { var time1utc = new DateTime(2003, 3, 30, 0, 0, 23, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 3, 30, 2, 0, 24, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 3, 30, 5, 19, 20, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 2, 0, 0, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 2, 20, 0, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 3, 0, 1, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); } [Fact] public static void ConvertTime_DateTime_UtcToLocal() { if (s_localIsPST) { var time1 = new DateTime(2006, 4, 2, 1, 30, 0); var time1utc = new DateTime(2006, 4, 2, 1, 30, 0, DateTimeKind.Utc); VerifyConvert(time1utc.Subtract(s_regLocal.GetUtcOffset(time1utc)), TimeZoneInfo.Local.Id, time1); // Converts to "Pacific Standard Time" not actual Local, so historical rules are always respected int delta = s_regLocalSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); // 2007 rule time1 = new DateTime(2007, 3, 11, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 3, 11, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous hour (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); } } [Fact] public static void ConvertTime_DateTime_LocalToSystem() { var time1 = new DateTime(2006, 5, 12, 5, 17, 42); var time1local = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Local); var localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(10)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(10)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-7)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-7)); time1 = new DateTime(2006, 3, 28, 9, 47, 12); time1local = new DateTime(2006, 3, 28, 9, 47, 12, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(s_sydneyOffsetLastWeekOfMarch2006)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(s_sydneyOffsetLastWeekOfMarch2006)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(2006, 11, 5, 1, 3, 0); time1local = new DateTime(2006, 11, 5, 1, 3, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(1987, 1, 1, 2, 3, 0); time1local = new DateTime(1987, 1, 1, 2, 3, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(2001, 5, 12, 5, 17, 42); time1local = new DateTime(2001, 5, 12, 5, 17, 42, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); var gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 5, 19, 20); time1local = new DateTime(2003, 1, 30, 5, 19, 20, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 3, 20, 1); time1local = new DateTime(2003, 1, 30, 3, 20, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 0, 0, 23); time1local = new DateTime(2003, 1, 30, 0, 0, 23, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 0, 0, 0); time1local = new DateTime(2003, 11, 26, 0, 0, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 6, 20, 0); time1local = new DateTime(2003, 11, 26, 6, 20, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 3, 0, 1); time1local = new DateTime(2003, 11, 26, 3, 0, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); } [Fact] public static void ConvertTime_DateTime_LocalToLocal() { if (s_localIsPST) { var time1 = new DateTime(1964, 6, 19, 12, 45, 10); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); int delta = TimeZoneInfo.Local.Equals(s_regLocal) ? 0 : 1; time1 = new DateTime(2007, 3, 11, 1, 0, 0); // just before DST transition VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 3, 11, 2, 0, 0); // invalid (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Local.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id); } else { VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); } time1 = new DateTime(2007, 3, 11, 3, 0, 0); // just after DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // just before DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); time1 = (new DateTime(2007, 11, 4, 1, 30, 0, DateTimeKind.Local)).ToUniversalTime().AddHours(-1).ToLocalTime(); // DST half of repeated hour (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta), DateTimeKind.Unspecified); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // just after DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2004, 4, 4, 0, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 4, 4, 4, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 10, 31, 0, 30, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = (new DateTime(2004, 10, 31, 1, 30, 0, DateTimeKind.Local)).ToUniversalTime().AddHours(-1).ToLocalTime(); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal), DateTimeKind.Unspecified); time1 = new DateTime(2004, 10, 31, 1, 30, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 10, 31, 3, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); } } [Fact] public static void ConvertTime_DateTime_LocalToUtc() { var time1 = new DateTime(1964, 6, 19, 12, 45, 10); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); // invalid/ambiguous times in Local time1 = new DateTime(2006, 5, 12, 7, 34, 59); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); if (s_localIsPST) { int delta = s_localSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 4, 2, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Utc.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id); } else { VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); // 2007 rule time1 = new DateTime(2007, 3, 11, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 3, 11, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Utc.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id); } else { VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } time1 = new DateTime(2007, 3, 11, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } } [Fact] public static void ConvertTime_DateTime_VariousDateTimeKinds() { VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), s_strPacific, s_strSydney); VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), s_strSydney, s_strPacific); VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), "UTC", s_strSydney, new DateTime(2006, 2, 13, 16, 37, 48)); // DCR 24267 VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), TimeZoneInfo.Utc.Id, s_strSydney, new DateTime(2006, 2, 13, 16, 37, 48)); // DCR 24267 VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Unspecified), TimeZoneInfo.Local.Id, s_strSydney, new DateTime(2006, 2, 13, 5, 37, 48).AddHours(11).Subtract(s_regLocal.GetUtcOffset(new DateTime(2006, 2, 13, 5, 37, 48)))); // DCR 24267 if (TimeZoneInfo.Local.Id != s_strSydney) { VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), s_strSydney, s_strPacific); } VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), "UTC", s_strPacific); VerifyConvertException<Exception>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), "Local", s_strPacific); } [Fact] public static void ConvertTime_DateTime_MiscUtc() { VerifyConvert(new DateTime(2003, 4, 6, 1, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 4, 6, 1, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 4, 6, 2, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 4, 6, 2, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 10, 26, 1, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 10, 26, 1, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 10, 26, 2, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 10, 26, 2, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 8, 4, 12, 0, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 8, 4, 12, 0, 0), DateTimeKind.Utc)); // Round trip VerifyRoundTrip(new DateTime(2003, 8, 4, 12, 0, 0, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(new DateTime(1929, 3, 9, 23, 59, 59, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(new DateTime(2000, 2, 28, 23, 59, 59, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); // DateTime(2016, 11, 6, 8, 1, 17, DateTimeKind.Utc) is ambiguous time for Pacific Time Zone VerifyRoundTrip(new DateTime(2016, 11, 6, 8, 1, 17, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(DateTime.UtcNow, "UTC", TimeZoneInfo.Local.Id); var time1 = new DateTime(2006, 5, 12, 7, 34, 59); VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc)); if (s_localIsPST) { int delta = s_localSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 4, 2, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, "UTC"); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC"); } else { VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); } time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); } } [Fact] public static void ConvertTime_Brasilia() { var time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 10, 15, 2, 30, 0, new TimeSpan(-2, 0, 0)); // invalid VerifyConvert(time1, s_strBrasilia, time1.ToOffset(new TimeSpan(-3, 0, 0))); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-3, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-2, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasilia, time1); } [Fact] public static void ConvertTime_Tonga() { var time1 = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Utc); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2001, 5, 12, 5, 17, 42); var localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); var time1local = new DateTime(2001, 5, 12, 5, 17, 42, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 5, 19, 20); time1local = new DateTime(2003, 1, 30, 5, 19, 20, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 1, 20, 1); time1local = new DateTime(2003, 1, 30, 1, 20, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 0, 0, 23); time1local = new DateTime(2003, 1, 30, 0, 0, 23, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 2, 0, 0); time1local = new DateTime(2003, 11, 26, 2, 0, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 2, 20, 0); time1local = new DateTime(2003, 11, 26, 2, 20, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 3, 0, 1); time1local = new DateTime(2003, 11, 26, 3, 0, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); } [Fact] public static void ConvertTime_NullTimeZone_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), null)); AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTimeOffset(), null)); AssertExtensions.Throws<ArgumentNullException>("sourceTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), null, s_casablancaTz)); AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), s_casablancaTz, null)); } [Fact] public static void GetAmbiguousTimeOffsets_Invalid() { VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32, DateTimeKind.Local)); } [Fact] public static void GetAmbiguousTimeOffsets_Nairobi_Invalid() { VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32)); } [Fact] public static void GetAmbiguousTimeOffsets_Amsterdam() { // // * 00:59:59 Sunday March 26, 2006 in Universal converts to // 01:59:59 Sunday March 26, 2006 in Europe/Amsterdam (NO DST) // // * 01:00:00 Sunday March 26, 2006 in Universal converts to // 03:00:00 Sunday March 26, 2006 in Europe/Amsterdam (DST) // VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc)); TimeSpan one = new TimeSpan(+1, 0, 0); TimeSpan two = new TimeSpan(+2, 0, 0); TimeSpan[] amsterdamAmbiguousOffsets = new TimeSpan[] { one, two }; // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 01, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 02, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 03, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 04, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 05, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 06, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 07, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 08, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 09, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 10, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 11, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 12, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 13, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 14, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 49, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 50, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 51, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 52, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 53, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 54, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 56, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 57, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 58, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), amsterdamAmbiguousOffsets); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 01, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 02, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 03, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 04, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 05, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 06, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 07, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 08, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 09, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 10, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 11, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 12, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 13, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 14, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 49, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 50, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 51, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 52, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 53, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 56, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 57, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 58, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 02, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 06, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 03, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 04, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 05, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 01, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 01, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 01, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 02, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 03, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 50)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 59)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54)); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 55), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 59), amsterdamAmbiguousOffsets); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44)); } [Fact] public static void GetAmbiguousTimeOffsets_LocalAmbiguousOffsets() { if (!s_localIsPST) return; // Test valid for Pacific TZ only TimeSpan[] localOffsets = new TimeSpan[] { new TimeSpan(-7, 0, 0), new TimeSpan(-8, 0, 0) }; VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 2, 0, 0, DateTimeKind.Local)); // use correct rule VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 3, 0, 0, DateTimeKind.Local)); // use correct rule VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 1, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 1, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 0, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 30, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 0, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 0, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0, DateTimeKind.Local)); } [Fact] public static void IsDaylightSavingTime() { VerifyDST(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2004, 4, 4, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(s_nairobiTz, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyDST(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyDST(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyDST(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyDST(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyDST(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyDST(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyDST(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyDST(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyDST(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc), true); // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), true); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 50), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 59), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54), true); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 4, 2, 2, 30, 0, DateTimeKind.Local), true); if (s_localIsPST) { VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 10, 31, 0, 30, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 10, 31, 0, 30, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0, DateTimeKind.Local), false); // invalid time VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); // invalid time VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 0, 0), false); // ambiguous VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 0, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 30, 0), false); // ambiguous VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); } } [Fact] public static void IsInvalidTime() { VerifyInv(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyInv(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyInv(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyInv(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyInv(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyInv(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyInv(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyInv(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyInv(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyInv(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyInv(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32), false); // March 26, 2006 October 29, 2006 // 2AM 3AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* // // * 00:59:59 Sunday March 26, 2006 in Universal converts to // 01:59:59 Sunday March 26, 2006 in Europe/Amsterdam (NO DST) // // * 01:00:00 Sunday March 26, 2006 in Universal converts to // 03:00:00 Sunday March 26, 2006 in Europe/Amsterdam (DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc), false); // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), false); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 50, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 55, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 10), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 20), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 30), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 55), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 56), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 57), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 58), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 01), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 10), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 20), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 30), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 40), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 50), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 00), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 50), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 59), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54), false); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44), false); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix and Windows rules differ in this case public static void IsDaylightSavingTime_CatamarcaMultiYearDaylightSavings() { // America/Catamarca had DST from // 1946-10-01T04:00:00.0000000Z {-03:00:00 DST=True} // 1963-10-01T03:00:00.0000000Z {-04:00:00 DST=False} VerifyDST(s_catamarcaTz, new DateTime(1946, 09, 30, 17, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 03, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 03, 59, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 04, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1950, 01, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1953, 03, 01, 15, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1955, 05, 01, 16, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1957, 07, 01, 17, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1959, 09, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1961, 11, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 02, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 02, 59, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 03, 00, 00, DateTimeKind.Utc), false); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux will use local mean time for DateTimes before standard time came into effect. [InlineData("1940-02-24T23:59:59.0000000Z", false, "0:00:00")] [InlineData("1940-02-25T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1940-11-20T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1940-12-31T23:59:59.0000000Z", true, "1:00:00")] [InlineData("1941-01-01T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-02-24T12:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T01:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T22:59:59.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T23:00:00.0000000Z", false, "0:00:00")] public static void IsDaylightSavingTime_CasablancaMultiYearDaylightSavings(string dateTimeString, bool expectedDST, string expectedOffsetString) { // Africa/Casablanca had DST from // 1940-02-25T00:00:00.0000000Z {+01:00:00 DST=True} // 1945-11-17T23:00:00.0000000Z { 00:00:00 DST=False} DateTime dt = DateTime.ParseExact(dateTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); VerifyDST(s_casablancaTz, dt, expectedDST); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_casablancaTz.GetUtcOffset(dt)); } [Fact] [SkipOnPlatform(TestPlatforms.Windows, "Not supported on Windows.")] public static void TestSplittingRulesWhenReported() { // This test confirm we are splitting the rules which span multiple years on Linux // we use "America/Los_Angeles" which has the rule covering 2/9/1942 to 8/14/1945 // with daylight transition by 01:00:00. This rule should be split into 3 rules: // - rule 1 from 2/9/1942 to 12/31/1942 // - rule 2 from 1/1/1943 to 12/31/1944 // - rule 3 from 1/1/1945 to 8/14/1945 TimeZoneInfo.AdjustmentRule[] rules = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific).GetAdjustmentRules(); bool ruleEncountered = false; for (int i = 0; i < rules.Length; i++) { if (rules[i].DateStart == new DateTime(1942, 2, 9)) { Assert.True(i + 2 <= rules.Length - 1); TimeSpan daylightDelta = TimeSpan.FromHours(1); // DateStart : 2/9/1942 12:00:00 AM (Unspecified) // DateEnd : 12/31/1942 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:02:00:00 M:2, D:9, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:23:59:59.9990000 M:12, D:31, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1942, 12, 31), rules[i].DateEnd); Assert.Equal(daylightDelta, rules[i].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 2, 9), rules[i].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 59, 59, 999), 12, 31), rules[i].DaylightTransitionEnd); // DateStart : 1/1/1943 12:00:00 AM (Unspecified) // DateEnd : 12/31/1944 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:00:00:00 M:1, D:1, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:23:59:59.9990000 M:12, D:31, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1943, 1, 1), rules[i + 1].DateStart); Assert.Equal(new DateTime(1944, 12, 31), rules[i + 1].DateEnd); Assert.Equal(daylightDelta, rules[i + 1].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 0, 0, 0), 1, 1), rules[i + 1].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 59, 59, 999), 12, 31), rules[i + 1].DaylightTransitionEnd); // DateStart : 1/1/1945 12:00:00 AM (Unspecified) // DateEnd : 8/14/1945 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:00:00:00 M:1, D:1, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:15:59:59.9990000 M:8, D:14, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1945, 1, 1), rules[i + 2].DateStart); Assert.Equal(new DateTime(1945, 8, 14), rules[i + 2].DateEnd); Assert.Equal(daylightDelta, rules[i + 2].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 0, 0, 0), 1, 1), rules[i + 2].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 15, 59, 59, 999), 8, 14), rules[i + 2].DaylightTransitionEnd); ruleEncountered = true; break; } } Assert.True(ruleEncountered, "The 1942 rule of America/Los_Angeles not found."); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux will use local mean time for DateTimes before standard time came into effect. // in 1996 Europe/Lisbon changed from standard time to DST without changing the UTC offset [InlineData("1995-09-30T17:00:00.0000000Z", false, "1:00:00")] [InlineData("1996-03-31T00:59:59.0000000Z", false, "1:00:00")] [InlineData("1996-03-31T01:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-03-31T01:00:01.0000000Z", true, "1:00:00")] [InlineData("1996-03-31T11:00:01.0000000Z", true, "1:00:00")] [InlineData("1996-08-31T11:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T00:59:59.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T01:00:00.0000000Z", false, "0:00:00")] [InlineData("1996-10-28T01:00:00.0000000Z", false, "0:00:00")] [InlineData("1997-03-30T00:59:59.0000000Z", false, "0:00:00")] [InlineData("1997-03-30T01:00:00.0000000Z", true, "1:00:00")] public static void IsDaylightSavingTime_LisbonDaylightSavingsWithNoOffsetChange(string dateTimeString, bool expectedDST, string expectedOffsetString) { DateTime dt = DateTime.ParseExact(dateTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); VerifyDST(s_LisbonTz, dt, expectedDST); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_LisbonTz.GetUtcOffset(dt)); } [Theory] // Newfoundland is UTC-3:30 standard and UTC-2:30 dst // using non-UTC date times in this test to get some coverage for non-UTC date times [InlineData("2015-03-08T01:59:59", false, false, false, "-3:30:00", "-8:00:00")] // since DST kicks in a 2AM, from 2AM - 3AM is Invalid [InlineData("2015-03-08T02:00:00", false, true, false, "-3:30:00", "-8:00:00")] [InlineData("2015-03-08T02:59:59", false, true, false, "-3:30:00", "-8:00:00")] [InlineData("2015-03-08T03:00:00", true, false, false, "-2:30:00", "-8:00:00")] [InlineData("2015-03-08T07:29:59", true, false, false, "-2:30:00", "-8:00:00")] [InlineData("2015-03-08T07:30:00", true, false, false, "-2:30:00", "-7:00:00")] [InlineData("2015-11-01T00:59:59", true, false, false, "-2:30:00", "-7:00:00")] [InlineData("2015-11-01T01:00:00", false, false, true, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T01:59:59", false, false, true, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T02:00:00", false, false, false, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T05:29:59", false, false, false, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T05:30:00", false, false, false, "-3:30:00", "-8:00:00")] public static void NewfoundlandTimeZone(string dateTimeString, bool expectedDST, bool isInvalidTime, bool isAmbiguousTime, string expectedOffsetString, string pacificOffsetString) { DateTime dt = DateTime.ParseExact(dateTimeString, "s", CultureInfo.InvariantCulture); VerifyInv(s_NewfoundlandTz, dt, isInvalidTime); if (!isInvalidTime) { VerifyDST(s_NewfoundlandTz, dt, expectedDST); VerifyAmbiguous(s_NewfoundlandTz, dt, isAmbiguousTime); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_NewfoundlandTz.GetUtcOffset(dt)); TimeSpan pacificOffset = TimeSpan.Parse(pacificOffsetString, CultureInfo.InvariantCulture); VerifyConvert(dt, s_strNewfoundland, s_strPacific, dt - (offset - pacificOffset)); } } [Fact] public static void GetSystemTimeZones() { ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); Assert.NotEmpty(timeZones); Assert.Contains(timeZones, t => t.Id == s_strPacific); Assert.Contains(timeZones, t => t.Id == s_strSydney); Assert.Contains(timeZones, t => t.Id == s_strGMT); Assert.Contains(timeZones, t => t.Id == s_strTonga); Assert.Contains(timeZones, t => t.Id == s_strBrasil); Assert.Contains(timeZones, t => t.Id == s_strPerth); Assert.Contains(timeZones, t => t.Id == s_strBrasilia); Assert.Contains(timeZones, t => t.Id == s_strNairobi); Assert.Contains(timeZones, t => t.Id == s_strAmsterdam); Assert.Contains(timeZones, t => t.Id == s_strRussian); Assert.Contains(timeZones, t => t.Id == s_strLibya); Assert.Contains(timeZones, t => t.Id == s_strCatamarca); Assert.Contains(timeZones, t => t.Id == s_strLisbon); Assert.Contains(timeZones, t => t.Id == s_strNewfoundland); // ensure the TimeZoneInfos are sorted by BaseUtcOffset and then DisplayName. TimeZoneInfo previous = timeZones[0]; for (int i = 1; i < timeZones.Count; i++) { TimeZoneInfo current = timeZones[i]; int baseOffsetsCompared = current.BaseUtcOffset.CompareTo(previous.BaseUtcOffset); Assert.True(baseOffsetsCompared >= 0, string.Format("TimeZoneInfos are out of order. {0}:{1} should be before {2}:{3}", previous.Id, previous.BaseUtcOffset, current.Id, current.BaseUtcOffset)); if (baseOffsetsCompared == 0) { Assert.True(current.DisplayName.CompareTo(previous.DisplayName) >= 0, string.Format("TimeZoneInfos are out of order. {0} should be before {1}", previous.DisplayName, current.DisplayName)); } } } [Fact] public static void DaylightTransitionsExactTime() { TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); DateTime after = new DateTime(2011, 11, 6, 9, 0, 0, 0, DateTimeKind.Utc); DateTime mid = after.AddTicks(-1); DateTime before = after.AddTicks(-2); Assert.Equal(TimeSpan.FromHours(-7), zone.GetUtcOffset(before)); Assert.Equal(TimeSpan.FromHours(-7), zone.GetUtcOffset(mid)); Assert.Equal(TimeSpan.FromHours(-8), zone.GetUtcOffset(after)); } /// <summary> /// Ensure Africa/Johannesburg transitions from +3 to +2 at /// 1943-02-20T23:00:00Z, and not a tick before that. /// See https://github.com/dotnet/runtime/issues/4728 /// </summary> [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux and Windows rules differ in this case public static void DaylightTransitionsExactTime_Johannesburg() { DateTimeOffset transition = new DateTimeOffset(1943, 3, 20, 23, 0, 0, TimeSpan.Zero); Assert.Equal(TimeSpan.FromHours(3), s_johannesburgTz.GetUtcOffset(transition.AddTicks(-2))); Assert.Equal(TimeSpan.FromHours(3), s_johannesburgTz.GetUtcOffset(transition.AddTicks(-1))); Assert.Equal(TimeSpan.FromHours(2), s_johannesburgTz.GetUtcOffset(transition)); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { s_casablancaTz, s_casablancaTz, true }; yield return new object[] { s_casablancaTz, s_LisbonTz, false }; yield return new object[] { TimeZoneInfo.Utc, TimeZoneInfo.Utc, true }; yield return new object[] { TimeZoneInfo.Utc, s_casablancaTz, false }; yield return new object[] { TimeZoneInfo.Local, TimeZoneInfo.Local, true }; yield return new object[] { TimeZoneInfo.Local, new object(), false }; yield return new object[] { TimeZoneInfo.Local, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void EqualsTest(TimeZoneInfo timeZoneInfo, object obj, bool expected) { Assert.Equal(expected, timeZoneInfo.Equals(obj)); if (obj is TimeZoneInfo) { Assert.Equal(expected, timeZoneInfo.Equals((TimeZoneInfo)obj)); Assert.Equal(expected, timeZoneInfo.GetHashCode().Equals(obj.GetHashCode())); } } [Fact] public static void ClearCachedData() { TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(s_strSydney); TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo.ClearCachedData(); Assert.ThrowsAny<ArgumentException>(() => { TimeZoneInfo.ConvertTime(DateTime.Now, local, cst); }); } [Fact] public static void ConvertTime_DateTimeOffset_NullDestination_ArgumentNullException() { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<ArgumentNullException>(time1, null); } public static IEnumerable<object[]> ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData() { yield return new object[] { string.Empty }; yield return new object[] { " " }; yield return new object[] { "\0" }; yield return new object[] { s_strPacific.Substring(0, s_strPacific.Length / 2) }; // whole string must match yield return new object[] { s_strPacific + " Zone" }; // no extra characters yield return new object[] { " " + s_strPacific }; // no leading space yield return new object[] { s_strPacific + " " }; // no trailing space yield return new object[] { "\0" + s_strPacific }; // no leading null yield return new object[] { s_strPacific + "\0" }; // no trailing null yield return new object[] { s_strPacific + "\\ " }; // no trailing null yield return new object[] { s_strPacific + "\\Display" }; yield return new object[] { s_strPacific + "\n" }; // no trailing newline yield return new object[] { new string('a', 100) }; // long string } [Theory] [MemberData(nameof(ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData))] public static void ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException(string destinationId) { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<TimeZoneNotFoundException>(time1, destinationId); } [Fact] public static void ConvertTimeFromUtc() { // destination timezone is null Assert.Throws<ArgumentNullException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0), null); }); // destination timezone is UTC DateTime now = DateTime.UtcNow; DateTime convertedNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Utc); Assert.Equal(now, convertedNow); } [Fact] public static void ConvertTimeToUtc() { // null source VerifyConvertToUtcException<ArgumentNullException>(new DateTime(2007, 5, 3, 12, 16, 0), null); TimeZoneInfo london = CreateCustomLondonTimeZone(); // invalid DateTime DateTime invalidDate = new DateTime(2007, 3, 25, 1, 30, 0); VerifyConvertToUtcException<ArgumentException>(invalidDate, london); // DateTimeKind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Utc), london); // correct UTC conversion DateTime date = new DateTime(2007, 01, 01, 0, 0, 0); Assert.Equal(date.ToUniversalTime(), TimeZoneInfo.ConvertTimeToUtc(date)); } [Fact] public static void ConvertTimeFromToUtc() { TimeZoneInfo london = CreateCustomLondonTimeZone(); DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, back.Kind); Assert.Equal(utc, back); converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); DateTimeKind expectedKind = (TimeZoneInfo.Local == TimeZoneInfo.Utc) ? DateTimeKind.Utc : DateTimeKind.Local; Assert.Equal(expectedKind, converted.Kind); back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Local); Assert.Equal(DateTimeKind.Utc, back.Kind); Assert.Equal(utc, back); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void ConvertTimeFromToUtc_UnixOnly() { // DateTime Kind is Local Assert.ThrowsAny<ArgumentException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0, DateTimeKind.Local), TimeZoneInfo.Local); }); TimeZoneInfo london = CreateCustomLondonTimeZone(); // winter (no DST) DateTime winter = new DateTime(2007, 12, 25, 12, 0, 0); DateTime convertedWinter = TimeZoneInfo.ConvertTimeFromUtc(winter, london); Assert.Equal(winter, convertedWinter); // summer (DST) DateTime summer = new DateTime(2007, 06, 01, 12, 0, 0); DateTime convertedSummer = TimeZoneInfo.ConvertTimeFromUtc(summer, london); Assert.Equal(summer + new TimeSpan(1, 0, 0), convertedSummer); // Kind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Local), london); // Test the ambiguous date DateTime utcAmbiguous = new DateTime(2016, 10, 30, 0, 14, 49, DateTimeKind.Utc); DateTime convertedAmbiguous = TimeZoneInfo.ConvertTimeFromUtc(utcAmbiguous, london); Assert.Equal(DateTimeKind.Unspecified, convertedAmbiguous.Kind); Assert.True(london.IsAmbiguousTime(convertedAmbiguous), $"Expected to have {convertedAmbiguous} is ambiguous"); // convert to London time and back DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, london); Assert.Equal(DateTimeKind.Unspecified, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, london); Assert.Equal(DateTimeKind.Utc, back.Kind); if (london.IsAmbiguousTime(converted)) { // if the time is ambiguous this will not round trip the original value because this ambiguous time can be mapped into // 2 UTC times. usually we return the value with the DST delta added to it. back = back.AddTicks(- london.GetAdjustmentRules()[0].DaylightDelta.Ticks); } Assert.Equal(utc, back); } [Fact] public static void CreateCustomTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // supports DST TimeZoneInfo tz1 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }); Assert.True(tz1.SupportsDaylightSavingTime); // doesn't support DST TimeZoneInfo tz2 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(4, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }, true); Assert.False(tz2.SupportsDaylightSavingTime); TimeZoneInfo tz3 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, null); Assert.False(tz3.SupportsDaylightSavingTime); } [Fact] public static void CreateCustomTimeZone_Invalid() { VerifyCustomTimeZoneException<ArgumentNullException>(null, new TimeSpan(0), null, null); // null Id VerifyCustomTimeZoneException<ArgumentException>("", new TimeSpan(0), null, null); // empty string Id VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(0, 0, 55), null, null); // offset not minutes VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(14, 1, 0), null, null); // offset too big VerifyCustomTimeZoneException<ArgumentException>("mytimezone", - new TimeSpan(14, 1, 0), null, null); // offset too small } [Fact] public static void CreateCustomTimeZone_InvalidTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // AdjustmentRules overlap TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2004, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r2 }); // AdjustmentRules not ordered TimeZoneInfo.AdjustmentRule r3 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2006, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r3, r1 }); // Offset out of range TimeZoneInfo.AdjustmentRule r4 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(3, 0, 0), s1, e1); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r4 }); // overlapping AdjustmentRules for a date TimeZoneInfo.AdjustmentRule r5 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2005, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r5 }); // null AdjustmentRule VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { null }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // TimeZone not found on Windows public static void HasSameRules_RomeAndVatican() { TimeZoneInfo rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vatican"); Assert.True(rome.HasSameRules(vatican)); } [Fact] public static void HasSameRules_NullAdjustmentRules() { TimeZoneInfo utc = TimeZoneInfo.Utc; TimeZoneInfo custom = TimeZoneInfo.CreateCustomTimeZone("Custom", new TimeSpan(0), "Custom", "Custom"); Assert.True(utc.HasSameRules(custom)); } [Fact] public static void ConvertTimeBySystemTimeZoneIdTests() { DateTime now = DateTime.Now; DateTime utcNow = TimeZoneInfo.ConvertTimeToUtc(now); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Utc.Id)); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Utc.Id, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Local.Id, TimeZoneInfo.Utc.Id)); DateTimeOffset offsetNow = new DateTimeOffset(now); DateTimeOffset utcOffsetNow = new DateTimeOffset(utcNow); Assert.Equal(offsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcOffsetNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcOffsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(offsetNow, TimeZoneInfo.Utc.Id)); } public static IEnumerable<object[]> SystemTimeZonesTestData() { foreach (TimeZoneInfo tz in TimeZoneInfo.GetSystemTimeZones()) { yield return new object[] { tz }; } // Include fixed offset IANA zones in the test data when they are available. if (!PlatformDetection.IsWindows) { for (int i = -14; i <= 12; i++) { TimeZoneInfo tz = null; try { string id = $"Etc/GMT{i:+0;-0}"; tz = TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException) { } if (tz != null) { yield return new object[] { tz }; } } } } private const string IanaAbbreviationPattern = @"^(?:[A-Z][A-Za-z]+|[+-]\d{2}|[+-]\d{4})$"; private static readonly Regex s_IanaAbbreviationRegex = new Regex(IanaAbbreviationPattern); // UTC aliases per https://github.com/unicode-org/cldr/blob/master/common/bcp47/timezone.xml // (This list is not likely to change.) private static readonly string[] s_UtcAliases = new[] { "Etc/UTC", "Etc/UCT", "Etc/Universal", "Etc/Zulu", "UCT", "UTC", "Universal", "Zulu" }; // On Android GMT, GMT+0, and GMT-0 are values private static readonly string[] s_GMTAliases = new [] { "GMT", "GMT0", "GMT+0", "GMT-0" }; [Theory] [MemberData(nameof(SystemTimeZonesTestData))] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void TimeZoneDisplayNames_Unix(TimeZoneInfo timeZone) { bool isUtc = s_UtcAliases.Contains(timeZone.Id, StringComparer.OrdinalIgnoreCase); if (PlatformDetection.IsBrowser) { // Browser platform doesn't have full ICU names, but uses the IANA IDs and abbreviations instead. // The display name will be the offset plus the ID. // The offset is checked separately in TimeZoneInfo_DisplayNameStartsWithOffset Assert.True(timeZone.DisplayName.EndsWith(" " + timeZone.Id), $"Id: \"{timeZone.Id}\", DisplayName should have ended with the ID, Actual DisplayName: \"{timeZone.DisplayName}\""); if (isUtc) { // Make sure UTC and its aliases have exactly "UTC" for the standard and daylight names Assert.True(timeZone.StandardName == "UTC", $"Id: \"{timeZone.Id}\", Expected StandardName: \"UTC\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(timeZone.DaylightName == "UTC", $"Id: \"{timeZone.Id}\", Expected DaylightName: \"UTC\", Actual DaylightName: \"{timeZone.DaylightName}\""); } else { // For other time zones, match any valid IANA time zone abbreviation, including numeric forms Assert.True(s_IanaAbbreviationRegex.IsMatch(timeZone.StandardName), $"Id: \"{timeZone.Id}\", StandardName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(s_IanaAbbreviationRegex.IsMatch(timeZone.DaylightName), $"Id: \"{timeZone.Id}\", DaylightName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual DaylightName: \"{timeZone.DaylightName}\""); } } else if (isUtc) { // UTC's display name is the string "(UTC) " and the same text as the standard name. Assert.True(timeZone.DisplayName == $"(UTC) {timeZone.StandardName}", $"Id: \"{timeZone.Id}\", Expected DisplayName: \"(UTC) {timeZone.StandardName}\", Actual DisplayName: \"{timeZone.DisplayName}\""); // All aliases of UTC should have the same names as UTC itself Assert.True(timeZone.DisplayName == TimeZoneInfo.Utc.DisplayName, $"Id: \"{timeZone.Id}\", Expected DisplayName: \"{TimeZoneInfo.Utc.DisplayName}\", Actual DisplayName: \"{timeZone.DisplayName}\""); Assert.True(timeZone.StandardName == TimeZoneInfo.Utc.StandardName, $"Id: \"{timeZone.Id}\", Expected StandardName: \"{TimeZoneInfo.Utc.StandardName}\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(timeZone.DaylightName == TimeZoneInfo.Utc.DaylightName, $"Id: \"{timeZone.Id}\", Expected DaylightName: \"{TimeZoneInfo.Utc.DaylightName}\", Actual DaylightName: \"{timeZone.DaylightName}\""); } else { // All we can really say generically here is that they aren't empty. Assert.False(string.IsNullOrWhiteSpace(timeZone.DisplayName), $"Id: \"{timeZone.Id}\", DisplayName should not have been empty."); Assert.False(string.IsNullOrWhiteSpace(timeZone.StandardName), $"Id: \"{timeZone.Id}\", StandardName should not have been empty."); // GMT* on Android does sets daylight savings time to false, so there will be no DaylightName if (!PlatformDetection.IsAndroid || (PlatformDetection.IsAndroid && !timeZone.Id.StartsWith("GMT"))) { Assert.False(string.IsNullOrWhiteSpace(timeZone.DaylightName), $"Id: \"{timeZone.Id}\", DaylightName should not have been empty."); } } } [ActiveIssue("https://github.com/dotnet/runtime/issues/19794", TestPlatforms.AnyUnix)] [Theory] [MemberData(nameof(SystemTimeZonesTestData))] public static void ToSerializedString_FromSerializedString_RoundTrips(TimeZoneInfo timeZone) { string serialized = timeZone.ToSerializedString(); TimeZoneInfo deserializedTimeZone = TimeZoneInfo.FromSerializedString(serialized); Assert.Equal(timeZone, deserializedTimeZone); Assert.Equal(serialized, deserializedTimeZone.ToSerializedString()); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] [MemberData(nameof(SystemTimeZonesTestData))] public static void BinaryFormatter_RoundTrips(TimeZoneInfo timeZone) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, timeZone); stream.Position = 0; TimeZoneInfo deserializedTimeZone = (TimeZoneInfo)formatter.Deserialize(stream); Assert.Equal(timeZone, deserializedTimeZone); } } [Fact] public static void TimeZoneInfo_DoesNotCreateAdjustmentRulesWithOffsetOutsideOfRange() { // On some OSes with some time zones setting // time zone may contain old adjustment rule which have offset higher than 14h // Assert.DoesNotThrow DateTimeOffset.FromFileTime(0); } [Fact] public static void TimeZoneInfo_DoesConvertTimeForOldDatesOfTimeZonesWithExceedingMaxRange() { // On some OSes this time zone contains old adjustment rules which have offset higher than 14h TimeZoneInfo tzi = TryGetSystemTimeZone("Asia/Manila"); if (tzi == null) { // Time zone could not be found return; } // Assert.DoesNotThrow TimeZoneInfo.ConvertTime(new DateTimeOffset(1800, 4, 4, 10, 10, 4, 2, TimeSpan.Zero), tzi); } [Fact] public static void GetSystemTimeZones_AllTimeZonesHaveOffsetInValidRange() { foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { foreach (TimeZoneInfo.AdjustmentRule ar in tzi.GetAdjustmentRules()) { Assert.True(Math.Abs((tzi.GetUtcOffset(ar.DateStart)).TotalHours) <= 14.0); } } } private static byte [] timeZoneFileContents = new byte[] { 0x54, 0x5A, 0x69, 0x66, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x5A, 0x69, 0x66, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xF8, 0xE4, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x10, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x0E, 0x10, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x4C, 0x4D, 0x54, 0x00, 0x2B, 0x30, 0x31, 0x00, 0x2B, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // POSIX Rule // 0x0A, 0x3C, 0x2B, 0x30, 0x30, 0x3E, 0x30, 0x3C, 0x2B, 0x30, 0x31, // 0x3E, 0x2C, 0x30, 0x2F, 0x30, 0x2C, 0x4A, 0x33, 0x36, 0x35, 0x2F, 0x32, 0x35, 0x0A }; [ActiveIssue("https://github.com/dotnet/runtime/issues/64134")] [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [PlatformSpecific(TestPlatforms.AnyUnix)] [InlineData("<+00>0<+01>,0/0,J365/25", 1, 1, true)] [InlineData("<+00>0<+01>,30/0,J365/25", 31, 1, true)] [InlineData("<+00>0<+01>,31/0,J365/25", 1, 2, true)] [InlineData("<+00>0<+01>,58/0,J365/25", 28, 2, true)] [InlineData("<+00>0<+01>,59/0,J365/25", 0, 0, false)] [InlineData("<+00>0<+01>,9999999/0,J365/25", 0, 0, false)] [InlineData("<+00>0<+01>,A/0,J365/25", 0, 0, false)] public static void NJulianRuleTest(string posixRule, int dayNumber, int monthNumber, bool shouldSucceed) { string zoneFilePath = Path.GetTempPath() + Path.GetRandomFileName(); using (FileStream fs = new FileStream(zoneFilePath, FileMode.Create)) { fs.Write(timeZoneFileContents.AsSpan()); // Append the POSIX rule fs.WriteByte(0x0A); foreach (char c in posixRule) { fs.WriteByte((byte) c); } fs.WriteByte(0x0A); } try { ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("TZ", zoneFilePath); RemoteExecutor.Invoke((day, month, succeed) => { bool expectedToSucceed = bool.Parse(succeed); int d = int.Parse(day); int m = int.Parse(month); TimeZoneInfo.AdjustmentRule [] rules = TimeZoneInfo.Local.GetAdjustmentRules(); if (expectedToSucceed) { Assert.Equal(1, rules.Length); Assert.Equal(d, rules[0].DaylightTransitionStart.Day); Assert.Equal(m, rules[0].DaylightTransitionStart.Month); } else { Assert.Equal(0, rules.Length); } }, dayNumber.ToString(), monthNumber.ToString(), shouldSucceed.ToString(), new RemoteInvokeOptions { StartInfo = psi}).Dispose(); } finally { try { File.Delete(zoneFilePath); } catch { } // don't fail the test if we couldn't delete the file. } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void TimeZoneInfo_LocalZoneWithInvariantMode() { string hostTZId = TimeZoneInfo.Local.Id; ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", PlatformDetection.IsInvariantGlobalization ? "0" : "1"); RemoteExecutor.Invoke((tzId, hostIsRunningInInvariantMode) => { bool hostInvariantMode = bool.Parse(hostIsRunningInInvariantMode); if (!hostInvariantMode) { // If hostInvariantMode is false, means the child process should enable the globalization invariant mode. // We validate here that by trying to create a culture which should throws in such mode. Assert.Throws<CultureNotFoundException>(() => CultureInfo.GetCultureInfo("en-US")); } Assert.Equal(tzId, TimeZoneInfo.Local.Id); }, hostTZId, PlatformDetection.IsInvariantGlobalization.ToString(), new RemoteInvokeOptions { StartInfo = psi}).Dispose(); } [Fact] public static void TimeZoneInfo_DaylightDeltaIsNoMoreThan12Hours() { foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { foreach (TimeZoneInfo.AdjustmentRule ar in tzi.GetAdjustmentRules()) { Assert.True(Math.Abs(ar.DaylightDelta.TotalHours) <= 12.0); } } } [Theory] [MemberData(nameof(SystemTimeZonesTestData))] public static void TimeZoneInfo_DisplayNameStartsWithOffset(TimeZoneInfo tzi) { if (s_UtcAliases.Contains(tzi.Id, StringComparer.OrdinalIgnoreCase)) { // UTC and all of its aliases (Etc/UTC, and others) start with just "(UTC) " Assert.StartsWith("(UTC) ", tzi.DisplayName); } else if (s_GMTAliases.Contains(tzi.Id, StringComparer.OrdinalIgnoreCase)) { Assert.StartsWith("GMT", tzi.DisplayName); } else { Assert.False(string.IsNullOrWhiteSpace(tzi.StandardName)); Assert.Matches(@"^\(UTC(\+|-)[0-9]{2}:[0-9]{2}\) \S.*", tzi.DisplayName); // see https://github.com/dotnet/corefx/pull/33204#issuecomment-438782500 if (PlatformDetection.IsNotWindowsNanoServer && !PlatformDetection.IsWindows7) { string offset = Regex.Match(tzi.DisplayName, @"(-|)[0-9]{2}:[0-9]{2}").Value; TimeSpan ts = TimeSpan.Parse(offset); if (PlatformDetection.IsWindows && tzi.BaseUtcOffset != ts && (tzi.Id.Contains("Morocco") || tzi.Id.Contains("Volgograd"))) { // Windows data can report display name with UTC+01:00 offset which is not matching the actual BaseUtcOffset. // We special case this in the test to avoid the test failures like: // 01:00 != 00:00:00, dn:(UTC+01:00) Casablanca, sn:Morocco Standard Time // 04:00 != 03:00:00, dn:(UTC+04:00) Volgograd, sn:Volgograd Standard Time if (tzi.Id.Contains("Morocco")) { Assert.True(tzi.BaseUtcOffset == new TimeSpan(0, 0, 0), $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } else { // Volgograd, Russia Assert.True(tzi.BaseUtcOffset == new TimeSpan(3, 0, 0), $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } } else { Assert.True(tzi.BaseUtcOffset == ts || tzi.GetUtcOffset(DateTime.Now) == ts, $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } } } } [Fact] public static void EnsureUtcObjectSingleton() { TimeZoneInfo utcObject = TimeZoneInfo.GetSystemTimeZones().Single(x => x.Id.Equals("UTC", StringComparison.OrdinalIgnoreCase)); Assert.True(ReferenceEquals(utcObject, TimeZoneInfo.Utc)); Assert.True(ReferenceEquals(TimeZoneInfo.FindSystemTimeZoneById("UTC"), TimeZoneInfo.Utc)); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))] [InlineData("Pacific Standard Time", "America/Los_Angeles")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney")] [InlineData("GMT Standard Time", "Europe/London")] [InlineData("Tonga Standard Time", "Pacific/Tongatapu")] [InlineData("W. Australia Standard Time", "Australia/Perth")] [InlineData("E. South America Standard Time", "America/Sao_Paulo")] [InlineData("E. Africa Standard Time", "Africa/Nairobi")] [InlineData("W. Europe Standard Time", "Europe/Berlin")] [InlineData("Russian Standard Time", "Europe/Moscow")] [InlineData("Libya Standard Time", "Africa/Tripoli")] [InlineData("South Africa Standard Time", "Africa/Johannesburg")] [InlineData("Morocco Standard Time", "Africa/Casablanca")] [InlineData("Argentina Standard Time", "America/Argentina/Catamarca")] [InlineData("Newfoundland Standard Time", "America/St_Johns")] [InlineData("Iran Standard Time", "Asia/Tehran")] public static void UsingAlternativeTimeZoneIdsTest(string windowsId, string ianaId) { if (PlatformDetection.ICUVersion.Major >= 52 && !PlatformDetection.IsiOS && !PlatformDetection.IstvOS) { TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById(ianaId); TimeZoneInfo tzi2 = TimeZoneInfo.FindSystemTimeZoneById(windowsId); Assert.Equal(tzi1.BaseUtcOffset, tzi2.BaseUtcOffset); Assert.NotEqual(tzi1.Id, tzi2.Id); } else { Assert.Throws<TimeZoneNotFoundException>(() => TimeZoneInfo.FindSystemTimeZoneById(s_isWindows ? ianaId : windowsId)); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(s_isWindows ? windowsId : ianaId); } } public static bool SupportIanaNamesConversion => PlatformDetection.IsNotMobile && PlatformDetection.ICUVersion.Major >= 52; public static bool SupportIanaNamesConversionAndRemoteExecution => SupportIanaNamesConversion && RemoteExecutor.IsSupported; public static bool DoesNotSupportIanaNamesConversion => !SupportIanaNamesConversion; // This test is executed using the remote execution because it needs to run before creating the time zone cache to ensure testing with that state. // There are already other tests that test after creating the cache. [ConditionalFact(nameof(SupportIanaNamesConversionAndRemoteExecution))] public static void IsIanaIdWithNotCacheTest() { RemoteExecutor.Invoke(() => { Assert.Equal(!s_isWindows || TimeZoneInfo.Local.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase), TimeZoneInfo.Local.HasIanaId); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); Assert.False(tzi.HasIanaId); tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); Assert.True(tzi.HasIanaId); }).Dispose(); } [ConditionalFact(nameof(SupportIanaNamesConversion))] public static void IsIanaIdTest() { bool expected = !s_isWindows; Assert.Equal((expected || TimeZoneInfo.Local.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase)), TimeZoneInfo.Local.HasIanaId); foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { Assert.True((expected || tzi.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase)) == tzi.HasIanaId, $"`{tzi.Id}` has wrong IANA Id indicator"); } Assert.False(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time").HasIanaId, $" should not be IANA Id."); Assert.True(TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles").HasIanaId, $"'America/Los_Angeles' should be IANA Id"); } [ConditionalFact(nameof(DoesNotSupportIanaNamesConversion))] [PlatformSpecific(~TestPlatforms.Android)] public static void UnsupportedImplicitConversionTest() { string nonNativeTzName = s_isWindows ? "America/Los_Angeles" : "Pacific Standard Time"; Assert.Throws<TimeZoneNotFoundException>(() => TimeZoneInfo.FindSystemTimeZoneById(nonNativeTzName)); } [ConditionalTheory(nameof(SupportIanaNamesConversion))] [InlineData("Pacific Standard Time", "America/Los_Angeles")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney")] [InlineData("GMT Standard Time", "Europe/London")] [InlineData("Tonga Standard Time", "Pacific/Tongatapu")] [InlineData("W. Australia Standard Time", "Australia/Perth")] [InlineData("E. South America Standard Time", "America/Sao_Paulo")] [InlineData("E. Africa Standard Time", "Africa/Nairobi")] [InlineData("W. Europe Standard Time", "Europe/Berlin")] [InlineData("Russian Standard Time", "Europe/Moscow")] [InlineData("Libya Standard Time", "Africa/Tripoli")] [InlineData("South Africa Standard Time", "Africa/Johannesburg")] [InlineData("Morocco Standard Time", "Africa/Casablanca")] [InlineData("Argentina Standard Time", "America/Buenos_Aires")] [InlineData("Newfoundland Standard Time", "America/St_Johns")] [InlineData("Iran Standard Time", "Asia/Tehran")] public static void IdsConversionsTest(string windowsId, string ianaId) { Assert.True(TimeZoneInfo.TryConvertIanaIdToWindowsId(ianaId, out string winId)); Assert.Equal(windowsId, winId); Assert.True(TimeZoneInfo.TryConvertWindowsIdToIanaId(winId, out string ianaConvertedId)); Assert.Equal(ianaId, ianaConvertedId); } [ConditionalTheory(nameof(SupportIanaNamesConversion))] [InlineData("Pacific Standard Time", "America/Vancouver", "CA")] [InlineData("Pacific Standard Time", "America/Los_Angeles", "US")] [InlineData("Pacific Standard Time", "America/Los_Angeles", "\u0600NotValidRegion")] [InlineData("Central Europe Standard Time", "Europe/Budapest", "DJ")] [InlineData("Central Europe Standard Time", "Europe/Budapest", "\uFFFFNotValidRegion")] [InlineData("Central Europe Standard Time", "Europe/Prague", "CZ")] [InlineData("Central Europe Standard Time", "Europe/Ljubljana", "SI")] [InlineData("Central Europe Standard Time", "Europe/Bratislava", "SK")] [InlineData("Central Europe Standard Time", "Europe/Tirane", "AL")] [InlineData("Central Europe Standard Time", "Europe/Podgorica", "ME")] [InlineData("Central Europe Standard Time", "Europe/Belgrade", "RS")] // lowercased region name cases: [InlineData("Cen. Australia Standard Time", "Australia/Adelaide", "au")] [InlineData("AUS Central Standard Time", "Australia/Darwin", "au")] [InlineData("E. Australia Standard Time", "Australia/Brisbane", "au")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney", "au")] [InlineData("Tasmania Standard Time", "Australia/Hobart", "au")] [InlineData("Romance Standard Time", "Europe/Madrid", "es")] [InlineData("Romance Standard Time", "Europe/Madrid", "Es")] [InlineData("Romance Standard Time", "Europe/Madrid", "eS")] [InlineData("GMT Standard Time", "Europe/London", "gb")] [InlineData("GMT Standard Time", "Europe/Dublin", "ie")] [InlineData("W. Europe Standard Time", "Europe/Rome", "it")] [InlineData("New Zealand Standard Time", "Pacific/Auckland", "nz")] public static void IdsConversionsWithRegionTest(string windowsId, string ianaId, string region) { Assert.True(TimeZoneInfo.TryConvertWindowsIdToIanaId(windowsId, region, out string ianaConvertedId)); Assert.Equal(ianaId, ianaConvertedId); } // We test the existence of a specific English time zone name to avoid failures on non-English platforms. [ConditionalFact(nameof(IsEnglishUILanguageAndRemoteExecutorSupported))] public static void TestNameWithInvariantCulture() { RemoteExecutor.Invoke(() => { // We call ICU to get the names. When passing invariant culture name to ICU, it fail and we'll use the abbreviated names at that time. // We fixed this issue by avoid sending the invariant culture name to ICU and this test is confirming we work fine at that time. CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; TimeZoneInfo.ClearCachedData(); TimeZoneInfo pacific = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); Assert.True(pacific.StandardName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.StandardName}' is not the expected standard name for Pacific time zone"); Assert.True(pacific.DaylightName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.DaylightName}' is not the expected daylight name for Pacific time zone"); Assert.True(pacific.DisplayName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.DisplayName}' is not the expected display name for Pacific time zone"); }).Dispose(); } private static readonly CultureInfo[] s_CulturesForWindowsNlsDisplayNamesTest = WindowsUILanguageHelper.GetInstalledWin32CulturesWithUniqueLanguages(); private static bool CanTestWindowsNlsDisplayNames => RemoteExecutor.IsSupported && s_CulturesForWindowsNlsDisplayNamesTest.Length > 1; [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(nameof(CanTestWindowsNlsDisplayNames))] public static void TestWindowsNlsDisplayNames() { RemoteExecutor.Invoke(() => { CultureInfo[] cultures = s_CulturesForWindowsNlsDisplayNamesTest; CultureInfo.CurrentUICulture = cultures[0]; TimeZoneInfo.ClearCachedData(); TimeZoneInfo tz1 = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); CultureInfo.CurrentUICulture = cultures[1]; TimeZoneInfo.ClearCachedData(); TimeZoneInfo tz2 = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); Assert.True(tz1.DisplayName != tz2.DisplayName, $"The display name '{tz1.DisplayName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); Assert.True(tz1.StandardName != tz2.StandardName, $"The standard name '{tz1.StandardName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); Assert.True(tz1.DaylightName != tz2.DaylightName, $"The daylight name '{tz1.DaylightName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); }).Dispose(); } [Theory] [PlatformSpecific(TestPlatforms.Browser)] [InlineData("America/Buenos_Aires", "America/Argentina/Buenos_Aires")] [InlineData("America/Catamarca", "America/Argentina/Catamarca")] [InlineData("America/Cordoba", "America/Argentina/Cordoba")] [InlineData("America/Jujuy", "America/Argentina/Jujuy")] [InlineData("America/Mendoza", "America/Argentina/Mendoza")] [InlineData("America/Indianapolis", "America/Indiana/Indianapolis")] public static void TestTimeZoneIdBackwardCompatibility(string oldId, string currentId) { TimeZoneInfo oldtz = TimeZoneInfo.FindSystemTimeZoneById(oldId); TimeZoneInfo currenttz = TimeZoneInfo.FindSystemTimeZoneById(currentId); Assert.Equal(oldtz.StandardName, currenttz.StandardName); Assert.Equal(oldtz.DaylightName, currenttz.DaylightName); // Note we cannot test the DisplayName, as it will contain the ID. } [Theory] [PlatformSpecific(TestPlatforms.Browser)] [InlineData("America/Buenos_Aires")] [InlineData("America/Catamarca")] [InlineData("America/Cordoba")] [InlineData("America/Jujuy")] [InlineData("America/Mendoza")] [InlineData("America/Indianapolis")] public static void ChangeLocalTimeZone(string id) { string originalTZ = Environment.GetEnvironmentVariable("TZ"); try { TimeZoneInfo.ClearCachedData(); Environment.SetEnvironmentVariable("TZ", id); TimeZoneInfo localtz = TimeZoneInfo.Local; TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(id); Assert.Equal(tz.StandardName, localtz.StandardName); Assert.Equal(tz.DisplayName, localtz.DisplayName); } finally { TimeZoneInfo.ClearCachedData(); Environment.SetEnvironmentVariable("TZ", originalTZ); } } [Fact] public static void FijiTimeZoneTest() { TimeZoneInfo fijiTZ = TimeZoneInfo.FindSystemTimeZoneById(s_strFiji); // "Fiji Standard Time" - "Pacific/Fiji" DateTime utcDT = new DateTime(2021, 1, 1, 14, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2021, 1, 31, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2022, 10, 1, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2022, 12, 31, 11, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2023, 1, 1, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2023, 2, 1, 0, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); } [Fact] public static void AdjustmentRuleBaseUtcOffsetDeltaTest() { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 2, 0, 0), month: 3, day: 7); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 1, 0, 0), month: 11, day: 7); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end, baseUtcOffsetDelta: new TimeSpan(1, 0, 0)); TimeZoneInfo customTimeZone = TimeZoneInfo.CreateCustomTimeZone( id: "Fake Time Zone", baseUtcOffset: new TimeSpan(0), displayName: "Fake Time Zone", standardDisplayName: "Standard Fake Time Zone", daylightDisplayName: "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule }); TimeZoneInfo.AdjustmentRule[] rules = customTimeZone.GetAdjustmentRules(); Assert.Equal(1, rules.Length); Assert.Equal(new TimeSpan(1, 0, 0), rules[0].BaseUtcOffsetDelta); // BaseUtcOffsetDelta should be counted to the returned offset during the standard time. Assert.Equal(new TimeSpan(1, 0, 0), customTimeZone.GetUtcOffset(new DateTime(2021, 1, 1, 2, 0, 0))); // BaseUtcOffsetDelta should be counted to the returned offset during the daylight time. Assert.Equal(new TimeSpan(2, 0, 0), customTimeZone.GetUtcOffset(new DateTime(2021, 3, 10, 2, 0, 0))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64111", TestPlatforms.Linux)] public static void NoBackwardTimeZones() { ReadOnlyCollection<TimeZoneInfo> tzCollection = TimeZoneInfo.GetSystemTimeZones(); HashSet<String> tzDisplayNames = new HashSet<String>(); foreach (TimeZoneInfo timezone in tzCollection) { tzDisplayNames.Add(timezone.DisplayName); } Assert.Equal(tzCollection.Count, tzDisplayNames.Count); } private static bool IsEnglishUILanguage => CultureInfo.CurrentUICulture.Name.Length == 0 || CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en"; private static bool IsEnglishUILanguageAndRemoteExecutorSupported => IsEnglishUILanguage && RemoteExecutor.IsSupported; private static void VerifyConvertException<TException>(DateTimeOffset inputTime, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvertException<TException>(DateTime inputTime, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvertException<TException>(DateTime inputTime, string sourceTimeZoneId, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId), TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvert(DateTimeOffset inputTime, string destinationTimeZoneId, DateTimeOffset expectedTime) { DateTimeOffset returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string destinationTimeZoneId, DateTime expectedTime) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); Assert.True(expectedTime.Kind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime.Kind, returnedTime.Kind, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string destinationTimeZoneId, DateTime expectedTime, DateTimeKind expectedKind) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); Assert.True(expectedKind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime.Kind, returnedTime.Kind, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string sourceTimeZoneId, string destinationTimeZoneId, DateTime expectedTime) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId), TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', Source TimeZone: {3}, Dest. Time Zone: {4}", expectedTime, returnedTime, inputTime, sourceTimeZoneId, destinationTimeZoneId)); Assert.True(expectedTime.Kind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', Source TimeZone: {3}, Dest. Time Zone: {4}", expectedTime.Kind, returnedTime.Kind, inputTime, sourceTimeZoneId, destinationTimeZoneId)); } private static void VerifyRoundTrip(DateTime dt1, string sourceTimeZoneId, string destinationTimeZoneId) { TimeZoneInfo sourceTzi = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId); TimeZoneInfo destTzi = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId); DateTime dt2 = TimeZoneInfo.ConvertTime(dt1, sourceTzi, destTzi); DateTime dt3 = TimeZoneInfo.ConvertTime(dt2, destTzi, sourceTzi); if (!destTzi.IsAmbiguousTime(dt2)) { // the ambiguous time can be mapped to 2 UTC times so it is not guaranteed to round trip Assert.True(dt1.Equals(dt3), string.Format("{0} failed to round trip using source '{1}' and '{2}' zones. wrong result {3}", dt1, sourceTimeZoneId, destinationTimeZoneId, dt3)); } if (sourceTimeZoneId == TimeZoneInfo.Utc.Id) { Assert.True(dt3.Kind == DateTimeKind.Utc, string.Format("failed to get the right DT Kind after round trip {0} using source TZ {1} and dest TZi {2}", dt1, sourceTimeZoneId, destinationTimeZoneId)); } } private static void VerifyAmbiguousOffsetsException<TException>(TimeZoneInfo tz, DateTime dt) where TException : Exception { Assert.Throws<TException>(() => tz.GetAmbiguousTimeOffsets(dt)); } private static void VerifyOffsets(TimeZoneInfo tz, DateTime dt, TimeSpan[] expectedOffsets) { TimeSpan[] ret = tz.GetAmbiguousTimeOffsets(dt); VerifyTimeSpanArray(ret, expectedOffsets, string.Format("Wrong offsets when used {0} with the zone {1}", dt, tz.Id)); } private static void VerifyTimeSpanArray(TimeSpan[] actual, TimeSpan[] expected, string errorMsg) { Assert.True(actual != null); Assert.True(expected != null); Assert.True(actual.Length == expected.Length); Array.Sort(expected); // TimeZoneInfo is expected to always return sorted TimeSpan arrays for (int i = 0; i < actual.Length; i++) { Assert.True(actual[i].Equals(expected[i]), errorMsg); } } private static void VerifyDST(TimeZoneInfo tz, DateTime dt, bool expectedDST) { bool ret = tz.IsDaylightSavingTime(dt); Assert.True(ret == expectedDST, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } private static void VerifyInv(TimeZoneInfo tz, DateTime dt, bool expectedInvalid) { bool ret = tz.IsInvalidTime(dt); Assert.True(expectedInvalid == ret, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } private static void VerifyAmbiguous(TimeZoneInfo tz, DateTime dt, bool expectedAmbiguous) { bool ret = tz.IsAmbiguousTime(dt); Assert.True(expectedAmbiguous == ret, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } /// <summary> /// Gets the offset for the time zone for early times (close to DateTime.MinValue). /// </summary> /// <remarks> /// Windows uses the current daylight savings rules for early times. /// /// Other Unix distros use V2 tzfiles, which use local mean time (LMT), which is based on the solar time. /// The Pacific Standard Time LMT is UTC-07:53. For Sydney, LMT is UTC+10:04. /// </remarks> private static TimeSpan GetEarlyTimesOffset(string timeZoneId) { if (timeZoneId == s_strPacific) { if (s_isWindows) { return TimeSpan.FromHours(-8); } else { return new TimeSpan(7, 53, 0).Negate(); } } else if (timeZoneId == s_strSydney) { if (s_isWindows) { return TimeSpan.FromHours(11); } else { return new TimeSpan(10, 4, 0); } } else { throw new NotSupportedException(string.Format("The timeZoneId '{0}' is not supported by GetEarlyTimesOffset.", timeZoneId)); } } private static TimeZoneInfo TryGetSystemTimeZone(string id) { try { return TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException) { return null; } } private static TimeZoneInfo CreateCustomLondonTimeZone() { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 1, 0, 0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end); return TimeZoneInfo.CreateCustomTimeZone("Europe/London", new TimeSpan(0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule }); } private static void VerifyConvertToUtcException<TException>(DateTime dateTime, TimeZoneInfo sourceTimeZone) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTimeToUtc(dateTime, sourceTimeZone)); } private static void VerifyCustomTimeZoneException<TException>(string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName = null, TimeZoneInfo.AdjustmentRule[] adjustmentRules = null) where TException : Exception { Assert.ThrowsAny<TException>(() => { if (daylightDisplayName == null && adjustmentRules == null) { TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName); } else { TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules); } }); } // This helper class is used to retrieve information about installed OS languages from Windows. // Its methods returns empty when run on non-Windows platforms. private static class WindowsUILanguageHelper { public static CultureInfo[] GetInstalledWin32CulturesWithUniqueLanguages() => GetInstalledWin32Cultures() .GroupBy(c => c.TwoLetterISOLanguageName) .Select(g => g.First()) .ToArray(); public static unsafe CultureInfo[] GetInstalledWin32Cultures() { if (!OperatingSystem.IsWindows()) { return new CultureInfo[0]; } var list = new List<CultureInfo>(); GCHandle handle = GCHandle.Alloc(list); try { EnumUILanguages( &EnumUiLanguagesCallback, MUI_ALL_INSTALLED_LANGUAGES | MUI_LANGUAGE_NAME, GCHandle.ToIntPtr(handle)); } finally { handle.Free(); } return list.ToArray(); } [UnmanagedCallersOnly] private static unsafe int EnumUiLanguagesCallback(char* lpUiLanguageString, IntPtr lParam) { // native string is null terminated var cultureName = new string(lpUiLanguageString); string tzResourceFilePath = Path.Join(Environment.SystemDirectory, cultureName, "tzres.dll.mui"); if (!File.Exists(tzResourceFilePath)) { // If Windows installed a UI language but did not include the time zone resources DLL for that language, // then skip this language as .NET will not be able to get the localized resources for that language. return 1; } try { var handle = GCHandle.FromIntPtr(lParam); var list = (List<CultureInfo>) handle.Target; list!.Add(CultureInfo.GetCultureInfo(cultureName)); return 1; } catch { return 0; } } private const uint MUI_LANGUAGE_NAME = 0x8; private const uint MUI_ALL_INSTALLED_LANGUAGES = 0x20; [DllImport("Kernel32.dll", CharSet = CharSet.Auto)] private static extern unsafe bool EnumUILanguages(delegate* unmanaged<char*, IntPtr, int> lpUILanguageEnumProc, uint dwFlags, IntPtr lParam); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public static partial class TimeZoneInfoTests { private static readonly bool s_isWindows = OperatingSystem.IsWindows(); private static readonly bool s_isOSX = OperatingSystem.IsMacOS(); private static string s_strPacific = s_isWindows ? "Pacific Standard Time" : "America/Los_Angeles"; private static string s_strSydney = s_isWindows ? "AUS Eastern Standard Time" : "Australia/Sydney"; private static string s_strGMT = s_isWindows ? "GMT Standard Time" : "Europe/London"; private static string s_strTonga = s_isWindows ? "Tonga Standard Time" : "Pacific/Tongatapu"; private static string s_strBrasil = s_isWindows ? "E. South America Standard Time" : "America/Sao_Paulo"; private static string s_strPerth = s_isWindows ? "W. Australia Standard Time" : "Australia/Perth"; private static string s_strBrasilia = s_isWindows ? "E. South America Standard Time" : "America/Sao_Paulo"; private static string s_strNairobi = s_isWindows ? "E. Africa Standard Time" : "Africa/Nairobi"; private static string s_strAmsterdam = s_isWindows ? "W. Europe Standard Time" : "Europe/Berlin"; private static string s_strRussian = s_isWindows ? "Russian Standard Time" : "Europe/Moscow"; private static string s_strLibya = s_isWindows ? "Libya Standard Time" : "Africa/Tripoli"; private static string s_strJohannesburg = s_isWindows ? "South Africa Standard Time" : "Africa/Johannesburg"; private static string s_strCasablanca = s_isWindows ? "Morocco Standard Time" : "Africa/Casablanca"; private static string s_strCatamarca = s_isWindows ? "Argentina Standard Time" : "America/Argentina/Catamarca"; private static string s_strLisbon = s_isWindows ? "GMT Standard Time" : "Europe/Lisbon"; private static string s_strNewfoundland = s_isWindows ? "Newfoundland Standard Time" : "America/St_Johns"; private static string s_strIran = s_isWindows ? "Iran Standard Time" : "Asia/Tehran"; private static string s_strFiji = s_isWindows ? "Fiji Standard Time" : "Pacific/Fiji"; private static TimeZoneInfo s_myUtc = TimeZoneInfo.Utc; private static TimeZoneInfo s_myLocal = TimeZoneInfo.Local; private static TimeZoneInfo s_regLocal = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id); // in case DST is disabled on Local private static TimeZoneInfo s_GMTLondon = TimeZoneInfo.FindSystemTimeZoneById(s_strGMT); private static TimeZoneInfo s_nairobiTz = TimeZoneInfo.FindSystemTimeZoneById(s_strNairobi); private static TimeZoneInfo s_amsterdamTz = TimeZoneInfo.FindSystemTimeZoneById(s_strAmsterdam); private static TimeZoneInfo s_johannesburgTz = TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg); private static TimeZoneInfo s_casablancaTz = TimeZoneInfo.FindSystemTimeZoneById(s_strCasablanca); private static TimeZoneInfo s_catamarcaTz = TimeZoneInfo.FindSystemTimeZoneById(s_strCatamarca); private static TimeZoneInfo s_LisbonTz = TimeZoneInfo.FindSystemTimeZoneById(s_strLisbon); private static TimeZoneInfo s_NewfoundlandTz = TimeZoneInfo.FindSystemTimeZoneById(s_strNewfoundland); private static bool s_localIsPST = TimeZoneInfo.Local.Id == s_strPacific; private static bool s_regLocalSupportsDST = s_regLocal.SupportsDaylightSavingTime; private static bool s_localSupportsDST = TimeZoneInfo.Local.SupportsDaylightSavingTime; // In 2006, Australia delayed ending DST by a week. However, Windows says it still ended the last week of March. private static readonly int s_sydneyOffsetLastWeekOfMarch2006 = s_isWindows ? 10 : 11; [Fact] public static void Kind() { TimeZoneInfo tzi = TimeZoneInfo.Local; Assert.Equal(tzi, TimeZoneInfo.Local); tzi = TimeZoneInfo.Utc; Assert.Equal(tzi, TimeZoneInfo.Utc); } [Fact] public static void Names() { TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo utc = TimeZoneInfo.Utc; Assert.NotNull(local.DaylightName); Assert.NotNull(local.DisplayName); Assert.NotNull(local.StandardName); Assert.NotNull(local.ToString()); Assert.NotNull(utc.DaylightName); Assert.NotNull(utc.DisplayName); Assert.NotNull(utc.StandardName); Assert.NotNull(utc.ToString()); } // Due to ICU size limitations, full daylight/standard names are not included for the browser. // Name abbreviations, if available, are used instead public static IEnumerable<object[]> Platform_TimeZoneNamesTestData() { if (PlatformDetection.IsBrowser || PlatformDetection.IsiOS || PlatformDetection.IstvOS) return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) America/Los_Angeles", "PST", "PDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Australia/Sydney", "AEST", "AEDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Australia/Perth", "AWST", "AWDT" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Asia/Tehran", "+0330", "+0430" }, { s_NewfoundlandTz, "(UTC-03:30) America/St_Johns", "NST", "NDT" }, { s_catamarcaTz, "(UTC-03:00) America/Argentina/Catamarca", "-03", "-02" } }; else if (PlatformDetection.IsWindows) return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) Pacific Time (US & Canada)", "Pacific Standard Time", "Pacific Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Canberra, Melbourne, Sydney", "AUS Eastern Standard Time", "AUS Eastern Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Perth", "W. Australia Standard Time", "W. Australia Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Tehran", "Iran Standard Time", "Iran Daylight Time" }, { s_NewfoundlandTz, "(UTC-03:30) Newfoundland", "Newfoundland Standard Time", "Newfoundland Daylight Time" }, { s_catamarcaTz, "(UTC-03:00) City of Buenos Aires", "Argentina Standard Time", "Argentina Daylight Time" } }; else return new TheoryData<TimeZoneInfo, string, string, string> { { TimeZoneInfo.FindSystemTimeZoneById(s_strPacific), "(UTC-08:00) Pacific Time (Los Angeles)", "Pacific Standard Time", "Pacific Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), "(UTC+10:00) Eastern Australia Time (Sydney)", "Australian Eastern Standard Time", "Australian Eastern Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), "(UTC+08:00) Australian Western Standard Time (Perth)", "Australian Western Standard Time", "Australian Western Daylight Time" }, { TimeZoneInfo.FindSystemTimeZoneById(s_strIran), "(UTC+03:30) Iran Time", "Iran Standard Time", "Iran Daylight Time" }, { s_NewfoundlandTz, "(UTC-03:30) Newfoundland Time (St. John’s)", "Newfoundland Standard Time", "Newfoundland Daylight Time" }, { s_catamarcaTz, "(UTC-03:00) Argentina Standard Time (Catamarca)", "Argentina Standard Time", "Argentina Summer Time" } }; } // We test the existence of a specific English time zone name to avoid failures on non-English platforms. [ConditionalTheory(nameof(IsEnglishUILanguage))] [MemberData(nameof(Platform_TimeZoneNamesTestData))] public static void Platform_TimeZoneNames(TimeZoneInfo tzi, string displayName, string standardName, string daylightName) { // Edge case - Optionally allow some characters to be absent in the display name. const string chars = ".’"; foreach (char c in chars) { if (displayName.Contains(c, StringComparison.Ordinal) && !tzi.DisplayName.Contains(c, StringComparison.Ordinal)) { displayName = displayName.Replace(c.ToString(), "", StringComparison.Ordinal); } } Assert.Equal($"DisplayName: \"{displayName}\", StandardName: {standardName}\", DaylightName: {daylightName}\"", $"DisplayName: \"{tzi.DisplayName}\", StandardName: {tzi.StandardName}\", DaylightName: {tzi.DaylightName}\""); } [Fact] public static void ConvertTime() { TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo utc = TimeZoneInfo.Utc; DateTime dt = TimeZoneInfo.ConvertTime(DateTime.Today, utc); Assert.Equal(DateTime.Today, TimeZoneInfo.ConvertTime(dt, local)); DateTime today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Utc); dt = TimeZoneInfo.ConvertTime(today, local); Assert.Equal(today, TimeZoneInfo.ConvertTime(dt, utc)); } [Fact] public static void LibyaTimeZone() { TimeZoneInfo tripoli; // Make sure first the timezone data is updated in the machine as it should include Libya Timezone try { tripoli = TimeZoneInfo.FindSystemTimeZoneById(s_strLibya); } catch (Exception /* TimeZoneNotFoundException in netstandard1.7 test*/ ) { // Libya time zone not found Console.WriteLine("Warning: Libya time zone is not exist in this machine"); return; } var startOf2012 = new DateTime(2012, 1, 1, 0, 0, 0, DateTimeKind.Utc); var endOf2011 = startOf2012.AddTicks(-1); DateTime libyaLocalTime = TimeZoneInfo.ConvertTime(endOf2011, tripoli); DateTime expectResult = new DateTime(2012, 1, 1, 2, 0, 0).AddTicks(-1); Assert.True(libyaLocalTime.Equals(expectResult), string.Format("Expected {0} and got {1}", expectResult, libyaLocalTime)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void TestYukonTZ() { try { TimeZoneInfo yukon = TimeZoneInfo.FindSystemTimeZoneById("Yukon Standard Time"); // First, ensure we have the updated data TimeZoneInfo.AdjustmentRule[] rules = yukon.GetAdjustmentRules(); if (rules.Length <= 0 || rules[rules.Length - 1].DateStart.Year != 2021 || rules[rules.Length - 1].DateEnd.Year != 9999) { return; } TimeSpan minus7HoursSpan = new TimeSpan(-7, 0, 0); DateTimeOffset midnight = new DateTimeOffset(2021, 1, 1, 0, 0, 0, 0, minus7HoursSpan); DateTimeOffset beforeMidnight = new DateTimeOffset(2020, 12, 31, 23, 59, 59, 999, minus7HoursSpan); DateTimeOffset before1AM = new DateTimeOffset(2021, 1, 1, 0, 59, 59, 999, minus7HoursSpan); DateTimeOffset at1AM = new DateTimeOffset(2021, 1, 1, 1, 0, 0, 0, minus7HoursSpan); DateTimeOffset midnight2022 = new DateTimeOffset(2022, 1, 1, 0, 0, 0, 0, minus7HoursSpan); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(midnight)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(beforeMidnight)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(before1AM)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(at1AM)); Assert.Equal(minus7HoursSpan, yukon.GetUtcOffset(midnight2022)); } catch (TimeZoneNotFoundException) { // Some Windows versions don't carry the complete TZ data. Ignore the tests on such versions. } } [Fact] public static void RussianTimeZone() { TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(s_strRussian); var inputUtcDate = new DateTime(2013, 6, 1, 0, 0, 0, DateTimeKind.Utc); DateTime russiaTime = TimeZoneInfo.ConvertTime(inputUtcDate, tz); DateTime expectResult = new DateTime(2013, 6, 1, 4, 0, 0); Assert.True(russiaTime.Equals(expectResult), string.Format("Expected {0} and got {1}", expectResult, russiaTime)); DateTime dt = new DateTime(2011, 12, 31, 23, 30, 0); TimeSpan o = tz.GetUtcOffset(dt); Assert.True(o.Equals(TimeSpan.FromHours(4)), string.Format("Expected {0} and got {1}", TimeSpan.FromHours(4), o)); } [Fact] public static void CaseInsensitiveLookup() { Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strBrasilia), TimeZoneInfo.FindSystemTimeZoneById(s_strBrasilia.ToLowerInvariant())); Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg), TimeZoneInfo.FindSystemTimeZoneById(s_strJohannesburg.ToUpperInvariant())); // Populate internal cache with all timezones. The implementation takes different path for lookup by id // when all timezones are populated. TimeZoneInfo.GetSystemTimeZones(); // The timezones used for the tests after GetSystemTimeZones calls have to be different from the ones used before GetSystemTimeZones to // exercise the rare path. Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strSydney), TimeZoneInfo.FindSystemTimeZoneById(s_strSydney.ToLowerInvariant())); Assert.Equal(TimeZoneInfo.FindSystemTimeZoneById(s_strPerth), TimeZoneInfo.FindSystemTimeZoneById(s_strPerth.ToUpperInvariant())); } [Fact] public static void ConvertTime_DateTimeOffset_Invalid() { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<ArgumentNullException>(time1, null); // We catch TimeZoneNotFoundException in then netstandard1.7 tests VerifyConvertException<Exception>(time1, string.Empty); VerifyConvertException<Exception>(time1, " "); VerifyConvertException<Exception>(time1, "\0"); VerifyConvertException<Exception>(time1, "Pacific"); // whole string must match VerifyConvertException<Exception>(time1, "Pacific Standard Time Zone"); // no extra characters VerifyConvertException<Exception>(time1, " Pacific Standard Time"); // no leading space VerifyConvertException<Exception>(time1, "Pacific Standard Time "); // no trailing space VerifyConvertException<Exception>(time1, "\0Pacific Standard Time"); // no leading null VerifyConvertException<Exception>(time1, "Pacific Standard Time\0"); // no trailing null VerifyConvertException<Exception>(time1, "Pacific Standard Time\\ "); // no trailing null VerifyConvertException<Exception>(time1, "Pacific Standard Time\\Display"); VerifyConvertException<Exception>(time1, "Pacific Standard Time\n"); // no trailing newline VerifyConvertException<Exception>(time1, new string('a', 256)); // long string } [Fact] public static void ConvertTime_DateTimeOffset_NearMinMaxValue() { VerifyConvert(DateTimeOffset.MaxValue, TimeZoneInfo.Utc.Id, DateTimeOffset.MaxValue); VerifyConvert(DateTimeOffset.MaxValue, s_strPacific, new DateTimeOffset(DateTime.MaxValue.AddHours(-8), new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue, s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(new DateTimeOffset(DateTime.MaxValue, new TimeSpan(5, 0, 0)), s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0)), s_strSydney, new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue.AddHours(-11), s_strSydney, new DateTimeOffset(DateTime.MaxValue, new TimeSpan(11, 0, 0))); VerifyConvert(DateTimeOffset.MaxValue.AddHours(-11.5), s_strSydney, new DateTimeOffset(DateTime.MaxValue.AddHours(-0.5), new TimeSpan(11, 0, 0))); VerifyConvert(new DateTimeOffset(DateTime.MaxValue.AddHours(-5), new TimeSpan(3, 0, 0)), s_strSydney, DateTimeOffset.MaxValue); VerifyConvert(DateTimeOffset.MinValue, TimeZoneInfo.Utc.Id, DateTimeOffset.MinValue); VerifyConvert(DateTimeOffset.MinValue, s_strSydney, new DateTimeOffset(DateTime.MinValue.AddHours(10), new TimeSpan(10, 0, 0))); VerifyConvert(DateTimeOffset.MinValue, s_strPacific, DateTimeOffset.MinValue); VerifyConvert(new DateTimeOffset(DateTime.MinValue, new TimeSpan(-3, 0, 0)), s_strPacific, DateTimeOffset.MinValue); VerifyConvert(new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0)), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MinValue.AddHours(8), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTimeOffset.MinValue.AddHours(8.5), s_strPacific, new DateTimeOffset(DateTime.MinValue.AddHours(0.5), new TimeSpan(-8, 0, 0))); VerifyConvert(new DateTimeOffset(DateTime.MinValue.AddHours(5), new TimeSpan(-3, 0, 0)), s_strPacific, new DateTimeOffset(DateTime.MinValue, new TimeSpan(-8, 0, 0))); VerifyConvert(DateTime.MaxValue, s_strPacific, s_strSydney, DateTime.MaxValue); VerifyConvert(DateTime.MaxValue.AddHours(-19), s_strPacific, s_strSydney, DateTime.MaxValue); VerifyConvert(DateTime.MaxValue.AddHours(-19.5), s_strPacific, s_strSydney, DateTime.MaxValue.AddHours(-0.5)); VerifyConvert(DateTime.MinValue, s_strSydney, s_strPacific, DateTime.MinValue); TimeSpan earlyTimesDifference = GetEarlyTimesOffset(s_strSydney) - GetEarlyTimesOffset(s_strPacific); VerifyConvert(DateTime.MinValue + earlyTimesDifference, s_strSydney, s_strPacific, DateTime.MinValue); VerifyConvert(DateTime.MinValue.AddHours(0.5) + earlyTimesDifference, s_strSydney, s_strPacific, DateTime.MinValue.AddHours(0.5)); } [Fact] public static void ConvertTime_DateTimeOffset_VariousSystemTimeZones() { var time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-7, 0, 0)); var time2 = new DateTimeOffset(2006, 5, 12, 22, 17, 42, new TimeSpan(10, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2006, 3, 14, 9, 47, 12, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(2006, 3, 15, 4, 47, 12, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(2006, 11, 5, 20, 3, 0, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(1987, 1, 1, 2, 3, 0, new TimeSpan(-8, 0, 0)); time2 = new DateTimeOffset(1987, 1, 1, 21, 3, 0, new TimeSpan(11, 0, 0)); VerifyConvert(time1, s_strSydney, time2); VerifyConvert(time2, s_strPacific, time1); time1 = new DateTimeOffset(2001, 5, 12, 5, 17, 42, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2001, 5, 12, 17, 17, 42, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 5, 19, 20, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 17, 19, 20, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 1, 20, 1, new TimeSpan(0, 0, 0)); var time1a = new DateTimeOffset(2003, 3, 30, 2, 20, 1, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 14, 20, 1, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time1a, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1a); VerifyConvert(time1, s_strGMT, time1a); // invalid hour VerifyConvert(time1a, s_strGMT, time1a); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 3, 30, 0, 0, 23, new TimeSpan(0, 0, 0)); time2 = new DateTimeOffset(2003, 3, 30, 13, 0, 23, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 1, 30, 0, new TimeSpan(0)); // ambiguous (STD) time1a = new DateTimeOffset(2003, 10, 26, 1, 30, 0, new TimeSpan(1, 0, 0)); // ambiguous (DLT) time2 = new DateTimeOffset(2003, 10, 26, 14, 30, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); VerifyConvert(time1a, s_strTonga, time2.AddHours(-1)); VerifyConvert(time1a, s_strGMT, time1a); time1 = new DateTimeOffset(2003, 10, 25, 14, 0, 0, new TimeSpan(1, 0, 0)); time2 = new DateTimeOffset(2003, 10, 26, 2, 0, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 2, 20, 0, new TimeSpan(0)); time2 = new DateTimeOffset(2003, 10, 26, 15, 20, 0, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(0)); time2 = new DateTimeOffset(2003, 10, 26, 16, 0, 1, new TimeSpan(13, 0, 0)); VerifyConvert(time1, s_strTonga, time2); VerifyConvert(time2, s_strGMT, time1); VerifyConvert(time1, s_strGMT, time1); VerifyConvert(time2, s_strTonga, time2); var time3 = new DateTime(2001, 5, 12, 5, 17, 42); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(12)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 3, 30, 5, 19, 20); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(12)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 3, 30, 1, 20, 1); VerifyConvertException<ArgumentException>(time3, s_strGMT, s_strTonga); // invalid time VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 3, 30, 0, 0, 23); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-13)); time3 = new DateTime(2003, 10, 26, 2, 0, 0); // ambiguous VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 10, 26, 2, 20, 0); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); // ambiguous VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); time3 = new DateTime(2003, 10, 26, 3, 0, 1); VerifyConvert(time3, s_strGMT, s_strTonga, time3.AddHours(13)); VerifyConvert(time3, s_strTonga, s_strGMT, time3.AddHours(-12)); // Iran has Utc offset 4:30 during the DST and 3:30 during standard time. time3 = new DateTime(2018, 4, 20, 7, 0, 0, DateTimeKind.Utc); VerifyConvert(time3, s_strIran, time3.AddHours(4.5), DateTimeKind.Unspecified); // DST time time3 = new DateTime(2018, 1, 20, 7, 0, 0, DateTimeKind.Utc); VerifyConvert(time3, s_strIran, time3.AddHours(3.5), DateTimeKind.Unspecified); // DST time } [Fact] public static void ConvertTime_SameTimeZones() { var time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 10, 15, 2, 30, 0, new TimeSpan(-2, 0, 0)); // invalid VerifyConvert(time1, s_strBrasil, time1.ToOffset(new TimeSpan(-3, 0, 0))); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-3, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-2, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasil, time1); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-7, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, s_strPacific, time1); time1 = new DateTimeOffset(1964, 6, 19, 12, 45, 10, new TimeSpan(0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1); time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-8, 0, 0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.ToUniversalTime()); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.ToUniversalTime()); } [Fact] public static void ConvertTime_DateTime_NearMinAndMaxValue() { DateTime time1 = new DateTime(2006, 5, 12); DateTime utcMaxValue = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc); VerifyConvert(utcMaxValue, s_strSydney, DateTime.MaxValue); VerifyConvert(utcMaxValue.AddHours(-11), s_strSydney, DateTime.MaxValue); VerifyConvert(utcMaxValue.AddHours(-11.5), s_strSydney, DateTime.MaxValue.AddHours(-0.5)); VerifyConvert(utcMaxValue, s_strPacific, DateTime.MaxValue.AddHours(-8)); DateTime utcMinValue = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc); VerifyConvert(utcMinValue, s_strPacific, DateTime.MinValue); TimeSpan earlyTimesOffsetPacific = GetEarlyTimesOffset(s_strPacific); earlyTimesOffsetPacific = earlyTimesOffsetPacific.Negate(); // Pacific is behind UTC, so negate for a positive value VerifyConvert(utcMinValue + earlyTimesOffsetPacific, s_strPacific, DateTime.MinValue); VerifyConvert(utcMinValue.AddHours(0.5) + earlyTimesOffsetPacific, s_strPacific, DateTime.MinValue.AddHours(0.5)); TimeSpan earlyTimesOffsetSydney = GetEarlyTimesOffset(s_strSydney); VerifyConvert(utcMinValue, s_strSydney, DateTime.MinValue + earlyTimesOffsetSydney); } [Fact] public static void ConverTime_DateTime_VariousSystemTimeZonesTest() { var time1utc = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Utc); var time1 = new DateTime(2006, 5, 12, 5, 17, 42); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-7)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(10)); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); VerifyConvert(time1utc, s_strTonga, time1.AddHours(13)); time1utc = new DateTime(2006, 3, 28, 9, 47, 12, DateTimeKind.Utc); time1 = new DateTime(2006, 3, 28, 9, 47, 12); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(s_sydneyOffsetLastWeekOfMarch2006)); time1utc = new DateTime(2006, 11, 5, 1, 3, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 11, 5, 1, 3, 0); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(11)); time1utc = new DateTime(1987, 1, 1, 2, 3, 0, DateTimeKind.Utc); time1 = new DateTime(1987, 1, 1, 2, 3, 0); VerifyConvert(time1utc, s_strPacific, time1.AddHours(-8)); VerifyConvert(time1utc, s_strSydney, time1.AddHours(11)); time1utc = new DateTime(2003, 3, 30, 0, 0, 23, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 0, 0, 23); VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2003, 3, 30, 2, 0, 24, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 2, 0, 24); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); time1utc = new DateTime(2003, 3, 30, 5, 19, 20, DateTimeKind.Utc); time1 = new DateTime(2003, 3, 30, 5, 19, 20); VerifyConvert(time1utc, s_strGMT, time1.AddHours(1)); time1utc = new DateTime(2003, 10, 26, 2, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 2, 0, 0); // ambiguous VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2003, 10, 26, 2, 20, 0, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 2, 20, 0); VerifyConvert(time1utc, s_strGMT, time1); // ambiguous time1utc = new DateTime(2003, 10, 26, 3, 0, 1, DateTimeKind.Utc); time1 = new DateTime(2003, 10, 26, 3, 0, 1); VerifyConvert(time1utc, s_strGMT, time1); time1utc = new DateTime(2005, 3, 30, 0, 0, 23, DateTimeKind.Utc); time1 = new DateTime(2005, 3, 30, 0, 0, 23); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1 = new DateTime(2006, 5, 12, 5, 17, 42); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(17)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-17)); time1 = new DateTime(2006, 3, 28, 9, 47, 12); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(s_sydneyOffsetLastWeekOfMarch2006 + 8)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-(s_sydneyOffsetLastWeekOfMarch2006 + 8))); time1 = new DateTime(2006, 11, 5, 1, 3, 0); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(19)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-19)); time1 = new DateTime(1987, 1, 1, 2, 3, 0); VerifyConvert(time1, s_strPacific, s_strSydney, time1.AddHours(19)); VerifyConvert(time1, s_strSydney, s_strPacific, time1.AddHours(-19)); } [Fact] public static void ConvertTime_DateTime_PerthRules() { var time1utc = new DateTime(2005, 12, 31, 15, 59, 59, DateTimeKind.Utc); var time1 = new DateTime(2005, 12, 31, 15, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 16, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 16, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 16, 30, 0, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 16, 30, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2005, 12, 31, 23, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2005, 12, 31, 23, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2006, 1, 1, 0, 1, 1, DateTimeKind.Utc); time1 = new DateTime(2006, 1, 1, 0, 1, 1); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // 2006 rule in effect time1utc = new DateTime(2006, 5, 12, 2, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 5, 12, 2, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // begin dst time1utc = new DateTime(2006, 11, 30, 17, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2006, 11, 30, 17, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2006, 11, 30, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 1, 2, 0, 0); VerifyConvert(time1utc, s_strPerth, time1); time1utc = new DateTime(2006, 12, 31, 15, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 31, 15, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); // 2007 rule time1utc = new DateTime(2006, 12, 31, 20, 1, 2, DateTimeKind.Utc); time1 = new DateTime(2006, 12, 31, 20, 1, 2); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); // end dst time1utc = new DateTime(2007, 3, 24, 16, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 16, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); time1utc = new DateTime(2007, 3, 24, 17, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 17, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); time1utc = new DateTime(2007, 3, 24, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 18, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2007, 3, 24, 19, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2007, 3, 24, 19, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); // begin dst time1utc = new DateTime(2008, 10, 25, 17, 59, 59, DateTimeKind.Utc); time1 = new DateTime(2008, 10, 25, 17, 59, 59); VerifyConvert(time1utc, s_strPerth, time1.AddHours(8)); time1utc = new DateTime(2008, 10, 25, 18, 0, 0, DateTimeKind.Utc); time1 = new DateTime(2008, 10, 25, 18, 0, 0); VerifyConvert(time1utc, s_strPerth, time1.AddHours(9)); } [Fact] public static void ConvertTime_DateTime_UtcToUtc() { var time1utc = new DateTime(2003, 3, 30, 0, 0, 23, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 3, 30, 2, 0, 24, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 3, 30, 5, 19, 20, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 2, 0, 0, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 2, 20, 0, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); time1utc = new DateTime(2003, 10, 26, 3, 0, 1, DateTimeKind.Utc); VerifyConvert(time1utc, TimeZoneInfo.Utc.Id, time1utc); } [Fact] public static void ConvertTime_DateTime_UtcToLocal() { if (s_localIsPST) { var time1 = new DateTime(2006, 4, 2, 1, 30, 0); var time1utc = new DateTime(2006, 4, 2, 1, 30, 0, DateTimeKind.Utc); VerifyConvert(time1utc.Subtract(s_regLocal.GetUtcOffset(time1utc)), TimeZoneInfo.Local.Id, time1); // Converts to "Pacific Standard Time" not actual Local, so historical rules are always respected int delta = s_regLocalSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); // 2007 rule time1 = new DateTime(2007, 3, 11, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 3, 11, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous hour (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc), TimeZoneInfo.Local.Id, time1); } } [Fact] public static void ConvertTime_DateTime_LocalToSystem() { var time1 = new DateTime(2006, 5, 12, 5, 17, 42); var time1local = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Local); var localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(10)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(10)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-7)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-7)); time1 = new DateTime(2006, 3, 28, 9, 47, 12); time1local = new DateTime(2006, 3, 28, 9, 47, 12, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(s_sydneyOffsetLastWeekOfMarch2006)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(s_sydneyOffsetLastWeekOfMarch2006)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(2006, 11, 5, 1, 3, 0); time1local = new DateTime(2006, 11, 5, 1, 3, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(1987, 1, 1, 2, 3, 0); time1local = new DateTime(1987, 1, 1, 2, 3, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1local, s_strSydney, time1.Subtract(localOffset).AddHours(11)); VerifyConvert(time1, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); VerifyConvert(time1local, s_strPacific, time1.Subtract(localOffset).AddHours(-8)); time1 = new DateTime(2001, 5, 12, 5, 17, 42); time1local = new DateTime(2001, 5, 12, 5, 17, 42, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); var gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 5, 19, 20); time1local = new DateTime(2003, 1, 30, 5, 19, 20, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 3, 20, 1); time1local = new DateTime(2003, 1, 30, 3, 20, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 1, 30, 0, 0, 23); time1local = new DateTime(2003, 1, 30, 0, 0, 23, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 0, 0, 0); time1local = new DateTime(2003, 11, 26, 0, 0, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 6, 20, 0); time1local = new DateTime(2003, 11, 26, 6, 20, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); time1 = new DateTime(2003, 11, 26, 3, 0, 1); time1local = new DateTime(2003, 11, 26, 3, 0, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); gmtOffset = s_GMTLondon.GetUtcOffset(TimeZoneInfo.ConvertTime(time1, s_myUtc)); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); VerifyConvert(time1local, s_strGMT, time1.Subtract(localOffset).Add(gmtOffset)); } [Fact] public static void ConvertTime_DateTime_LocalToLocal() { if (s_localIsPST) { var time1 = new DateTime(1964, 6, 19, 12, 45, 10); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); int delta = TimeZoneInfo.Local.Equals(s_regLocal) ? 0 : 1; time1 = new DateTime(2007, 3, 11, 1, 0, 0); // just before DST transition VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 3, 11, 2, 0, 0); // invalid (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Local.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id); } else { VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); } time1 = new DateTime(2007, 3, 11, 3, 0, 0); // just after DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // just before DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1.AddHours(delta)); time1 = (new DateTime(2007, 11, 4, 1, 30, 0, DateTimeKind.Local)).ToUniversalTime().AddHours(-1).ToLocalTime(); // DST half of repeated hour (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1.AddHours(delta), DateTimeKind.Unspecified); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // just after DST transition (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Local.Id, time1); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, time1); time1 = new DateTime(2004, 4, 4, 0, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 4, 4, 4, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 10, 31, 0, 30, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = (new DateTime(2004, 10, 31, 1, 30, 0, DateTimeKind.Local)).ToUniversalTime().AddHours(-1).ToLocalTime(); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal), DateTimeKind.Unspecified); time1 = new DateTime(2004, 10, 31, 1, 30, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); time1 = new DateTime(2004, 10, 31, 3, 0, 0); VerifyConvert(time1, TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Local.Id, TimeZoneInfo.ConvertTime(time1, s_regLocal)); } } [Fact] public static void ConvertTime_DateTime_LocalToUtc() { var time1 = new DateTime(1964, 6, 19, 12, 45, 10); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); // invalid/ambiguous times in Local time1 = new DateTime(2006, 5, 12, 7, 34, 59); VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc); if (s_localIsPST) { int delta = s_localSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 4, 2, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Utc.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id); } else { VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); // 2007 rule time1 = new DateTime(2007, 3, 11, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 3, 11, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, TimeZoneInfo.Utc.Id); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id); } else { VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } time1 = new DateTime(2007, 3, 11, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8 - delta), DateTimeKind.Utc); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); time1 = new DateTime(2007, 11, 4, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), TimeZoneInfo.Utc.Id, time1.AddHours(8), DateTimeKind.Utc); } } [Fact] public static void ConvertTime_DateTime_VariousDateTimeKinds() { VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), s_strPacific, s_strSydney); VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), s_strSydney, s_strPacific); VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), "UTC", s_strSydney, new DateTime(2006, 2, 13, 16, 37, 48)); // DCR 24267 VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Utc), TimeZoneInfo.Utc.Id, s_strSydney, new DateTime(2006, 2, 13, 16, 37, 48)); // DCR 24267 VerifyConvert(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Unspecified), TimeZoneInfo.Local.Id, s_strSydney, new DateTime(2006, 2, 13, 5, 37, 48).AddHours(11).Subtract(s_regLocal.GetUtcOffset(new DateTime(2006, 2, 13, 5, 37, 48)))); // DCR 24267 if (TimeZoneInfo.Local.Id != s_strSydney) { VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), s_strSydney, s_strPacific); } VerifyConvertException<ArgumentException>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), "UTC", s_strPacific); VerifyConvertException<Exception>(new DateTime(2006, 2, 13, 5, 37, 48, DateTimeKind.Local), "Local", s_strPacific); } [Fact] public static void ConvertTime_DateTime_MiscUtc() { VerifyConvert(new DateTime(2003, 4, 6, 1, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 4, 6, 1, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 4, 6, 2, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 4, 6, 2, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 10, 26, 1, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 10, 26, 1, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 10, 26, 2, 30, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 10, 26, 2, 30, 0), DateTimeKind.Utc)); VerifyConvert(new DateTime(2003, 8, 4, 12, 0, 0, DateTimeKind.Utc), "UTC", DateTime.SpecifyKind(new DateTime(2003, 8, 4, 12, 0, 0), DateTimeKind.Utc)); // Round trip VerifyRoundTrip(new DateTime(2003, 8, 4, 12, 0, 0, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(new DateTime(1929, 3, 9, 23, 59, 59, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(new DateTime(2000, 2, 28, 23, 59, 59, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); // DateTime(2016, 11, 6, 8, 1, 17, DateTimeKind.Utc) is ambiguous time for Pacific Time Zone VerifyRoundTrip(new DateTime(2016, 11, 6, 8, 1, 17, DateTimeKind.Utc), "UTC", TimeZoneInfo.Local.Id); VerifyRoundTrip(DateTime.UtcNow, "UTC", TimeZoneInfo.Local.Id); var time1 = new DateTime(2006, 5, 12, 7, 34, 59); VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.Subtract(TimeZoneInfo.Local.GetUtcOffset(time1)), DateTimeKind.Utc)); if (s_localIsPST) { int delta = s_localSupportsDST ? 1 : 0; time1 = new DateTime(2006, 4, 2, 1, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 4, 2, 2, 30, 0); // invalid hour (U.S. Pacific) if (s_localSupportsDST) { VerifyConvertException<ArgumentException>(time1, "UTC"); VerifyConvertException<ArgumentException>(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC"); } else { VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); } time1 = new DateTime(2006, 4, 2, 3, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 0, 30, 0); // DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - first time, DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8 - delta), DateTimeKind.Utc)); time1 = time1.ToUniversalTime().AddHours(1).ToLocalTime(); // ambiguous hour - second time, standard (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 1, 30, 0); // ambiguous hour - unspecified, assume standard (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); time1 = new DateTime(2006, 10, 29, 2, 30, 0); // no DST (U.S. Pacific) VerifyConvert(time1, "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); VerifyConvert(DateTime.SpecifyKind(time1, DateTimeKind.Local), "UTC", DateTime.SpecifyKind(time1.AddHours(8), DateTimeKind.Utc)); } } [Fact] public static void ConvertTime_Brasilia() { var time1 = new DateTimeOffset(2003, 10, 26, 3, 0, 1, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 5, 12, 5, 17, 42, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 3, 28, 9, 47, 12, new TimeSpan(-3, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 11, 5, 1, 3, 0, new TimeSpan(-2, 0, 0)); VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 10, 15, 2, 30, 0, new TimeSpan(-2, 0, 0)); // invalid VerifyConvert(time1, s_strBrasilia, time1.ToOffset(new TimeSpan(-3, 0, 0))); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-3, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasilia, time1); time1 = new DateTimeOffset(2006, 2, 12, 1, 30, 0, new TimeSpan(-2, 0, 0)); // ambiguous VerifyConvert(time1, s_strBrasilia, time1); } [Fact] public static void ConvertTime_Tonga() { var time1 = new DateTime(2006, 5, 12, 5, 17, 42, DateTimeKind.Utc); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2001, 5, 12, 5, 17, 42); var localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); var time1local = new DateTime(2001, 5, 12, 5, 17, 42, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 5, 19, 20); time1local = new DateTime(2003, 1, 30, 5, 19, 20, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 1, 20, 1); time1local = new DateTime(2003, 1, 30, 1, 20, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); VerifyConvert(time1local, s_strTonga, DateTime.SpecifyKind(time1.Subtract(localOffset).AddHours(13), DateTimeKind.Unspecified)); time1 = new DateTime(2003, 1, 30, 0, 0, 23); time1local = new DateTime(2003, 1, 30, 0, 0, 23, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 2, 0, 0); time1local = new DateTime(2003, 11, 26, 2, 0, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 2, 20, 0); time1local = new DateTime(2003, 11, 26, 2, 20, 0, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); time1 = new DateTime(2003, 11, 26, 3, 0, 1); time1local = new DateTime(2003, 11, 26, 3, 0, 1, DateTimeKind.Local); localOffset = TimeZoneInfo.Local.GetUtcOffset(time1); VerifyConvert(time1, s_strTonga, time1.Subtract(localOffset).AddHours(13)); VerifyConvert(time1local, s_strTonga, time1.Subtract(localOffset).AddHours(13)); } [Fact] public static void ConvertTime_NullTimeZone_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), null)); AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTimeOffset(), null)); AssertExtensions.Throws<ArgumentNullException>("sourceTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), null, s_casablancaTz)); AssertExtensions.Throws<ArgumentNullException>("destinationTimeZone", () => TimeZoneInfo.ConvertTime(new DateTime(), s_casablancaTz, null)); } [Fact] public static void GetAmbiguousTimeOffsets_Invalid() { VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32, DateTimeKind.Local)); } [Fact] public static void GetAmbiguousTimeOffsets_Nairobi_Invalid() { VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31)); VerifyAmbiguousOffsetsException<ArgumentException>(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32)); } [Fact] public static void GetAmbiguousTimeOffsets_Amsterdam() { // // * 00:59:59 Sunday March 26, 2006 in Universal converts to // 01:59:59 Sunday March 26, 2006 in Europe/Amsterdam (NO DST) // // * 01:00:00 Sunday March 26, 2006 in Universal converts to // 03:00:00 Sunday March 26, 2006 in Europe/Amsterdam (DST) // VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc)); TimeSpan one = new TimeSpan(+1, 0, 0); TimeSpan two = new TimeSpan(+2, 0, 0); TimeSpan[] amsterdamAmbiguousOffsets = new TimeSpan[] { one, two }; // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 01, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 02, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 03, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 04, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 05, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 06, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 07, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 08, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 09, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 10, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 11, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 12, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 13, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 14, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 49, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 50, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 51, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 52, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 53, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 54, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 56, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 57, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 58, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), amsterdamAmbiguousOffsets); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 01, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 02, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 03, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 04, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 05, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 06, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 07, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 08, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 09, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 10, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 11, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 12, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 13, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 14, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 00, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 15, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 30, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 45, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 49, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 50, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 51, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 52, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 53, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 55, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 56, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 57, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 58, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), amsterdamAmbiguousOffsets); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 02, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 03, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 04, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 06, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 03, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 04, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 05, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 01, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 01, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 01, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 02, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 01, 03, 00, 00, DateTimeKind.Utc)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 50)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 59)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54)); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 55), amsterdamAmbiguousOffsets); VerifyOffsets(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 59), amsterdamAmbiguousOffsets); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43)); VerifyAmbiguousOffsetsException<ArgumentException>(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44)); } [Fact] public static void GetAmbiguousTimeOffsets_LocalAmbiguousOffsets() { if (!s_localIsPST) return; // Test valid for Pacific TZ only TimeSpan[] localOffsets = new TimeSpan[] { new TimeSpan(-7, 0, 0), new TimeSpan(-8, 0, 0) }; VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 2, 0, 0, DateTimeKind.Local)); // use correct rule VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 3, 14, 3, 0, 0, DateTimeKind.Local)); // use correct rule VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 1, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 1, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 0, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 2, 30, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local)); // invalid time VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 3, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 0, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 0, 30, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0, DateTimeKind.Local)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0)); VerifyAmbiguousOffsetsException<ArgumentException>(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0, DateTimeKind.Local)); } [Fact] public static void IsDaylightSavingTime() { VerifyDST(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyDST(TimeZoneInfo.Utc, new DateTime(2004, 4, 4, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(s_nairobiTz, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyDST(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyDST(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyDST(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyDST(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyDST(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyDST(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyDST(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyDST(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyDST(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc), true); // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), true); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 50), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 59), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53), true); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54), true); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44), false); VerifyDST(s_amsterdamTz, new DateTime(2006, 4, 2, 2, 30, 0, DateTimeKind.Local), true); if (s_localIsPST) { VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 0, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 4, 4, 3, 30, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 10, 31, 0, 30, 0), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2004, 10, 31, 0, 30, 0, DateTimeKind.Local), true); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 1, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 0, 0, DateTimeKind.Local), false); // invalid time VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); // invalid time VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 0, 0), false); // ambiguous VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 0, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 30, 0), false); // ambiguous VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 1, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 0, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 11, 4, 2, 30, 0, DateTimeKind.Local), false); VerifyDST(TimeZoneInfo.Local, new DateTime(2007, 3, 11, 2, 30, 0, DateTimeKind.Local), false); } } [Fact] public static void IsInvalidTime() { VerifyInv(TimeZoneInfo.Utc, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyInv(TimeZoneInfo.Utc, new DateTime(9997, 10, 15, 16, 30, 32), false); VerifyInv(s_nairobiTz, new DateTime(2006, 1, 15, 7, 15, 23), false); VerifyInv(s_nairobiTz, new DateTime(2050, 2, 15, 8, 30, 24), false); VerifyInv(s_nairobiTz, new DateTime(1800, 3, 15, 9, 45, 25), false); VerifyInv(s_nairobiTz, new DateTime(1400, 4, 15, 10, 00, 26), false); VerifyInv(s_nairobiTz, new DateTime(1234, 5, 15, 11, 15, 27), false); VerifyInv(s_nairobiTz, new DateTime(4321, 6, 15, 12, 30, 28), false); VerifyInv(s_nairobiTz, new DateTime(1111, 7, 15, 13, 45, 29), false); VerifyInv(s_nairobiTz, new DateTime(2222, 8, 15, 14, 00, 30), false); VerifyInv(s_nairobiTz, new DateTime(9998, 9, 15, 15, 15, 31), false); VerifyInv(s_nairobiTz, new DateTime(9997, 10, 15, 16, 30, 32), false); // March 26, 2006 October 29, 2006 // 2AM 3AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* // // * 00:59:59 Sunday March 26, 2006 in Universal converts to // 01:59:59 Sunday March 26, 2006 in Europe/Amsterdam (NO DST) // // * 01:00:00 Sunday March 26, 2006 in Universal converts to // 03:00:00 Sunday March 26, 2006 in Europe/Amsterdam (DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 03, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 04, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 58, 05, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 15, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 30, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 01, 02, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 03, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 04, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 05, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 06, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 28, 23, 59, 59, DateTimeKind.Utc), false); // // * 00:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 15, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 30, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 45, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 55, 55, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 59, 59, DateTimeKind.Utc), false); // // * 01:00:00 Sunday October 29, 2006 in Universal converts to // 02:00:00 Sunday October 29, 2006 in Europe/Amsterdam (NO DST) // VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 59, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 07, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 11, 01, 00, 00, 00, DateTimeKind.Utc), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 01, 15, 03, 00, 33), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 02, 15, 04, 00, 34), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 01, 02, 00, 35), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 02, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 15, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 25, 03, 00, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 00, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 50, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 55, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 10), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 20), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 30), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 55), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 56), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 57), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 58), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 01, 59, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 00), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 01), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 10), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 20), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 30), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 40), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 00, 50), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 01, 00), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 30, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 45, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 55, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 58, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 36), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 50), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 02, 59, 59), true); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 00, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 30, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 45, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 50, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 03, 59, 59), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 00, 02), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 10, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 11, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 15, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 30, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 45, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 04, 50, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 05, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 06, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 07, 03, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 08, 04, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 09, 05, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 10, 06, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 11, 07, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 12, 08, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 13, 09, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 14, 10, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 15, 01, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 16, 02, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 17, 03, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 18, 04, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 19, 05, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 20, 06, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 21, 07, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 22, 08, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 03, 26, 23, 09, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 20, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 04, 15, 03, 01, 36), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 05, 15, 04, 15, 37), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 06, 15, 02, 15, 38), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 07, 15, 01, 15, 39), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 08, 15, 00, 15, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 09, 15, 10, 15, 41), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 15, 08, 15, 42), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 27, 08, 15, 43), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 28, 08, 15, 44), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 15, 45), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 30, 46), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 00, 45, 47), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 00, 48), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 15, 49), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 30, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 45, 51), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 55, 52), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 58, 53), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 01, 59, 54), false); // March 26, 2006 October 29, 2006 // 3AM 4AM 2AM 3AM // | +1 hr | | -1 hr | // | <invalid time> | | <ambiguous time> | // *========== DST ========>* VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 05), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 09), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 00, 15), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 01, 14), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 02, 12), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 10, 55), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 21, 50), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 32, 40), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 43, 30), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 56, 20), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 57, 10), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 02, 59, 45), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 00), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 00, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 01, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 02, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 03, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 04, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 05, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 03, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 04, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 05, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 06, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 10, 29, 07, 10, 01), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 11, 15, 10, 15, 43), false); VerifyInv(s_amsterdamTz, new DateTime(2006, 12, 15, 12, 15, 44), false); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix and Windows rules differ in this case public static void IsDaylightSavingTime_CatamarcaMultiYearDaylightSavings() { // America/Catamarca had DST from // 1946-10-01T04:00:00.0000000Z {-03:00:00 DST=True} // 1963-10-01T03:00:00.0000000Z {-04:00:00 DST=False} VerifyDST(s_catamarcaTz, new DateTime(1946, 09, 30, 17, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 03, 00, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 03, 59, 00, DateTimeKind.Utc), false); VerifyDST(s_catamarcaTz, new DateTime(1946, 10, 01, 04, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1950, 01, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1953, 03, 01, 15, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1955, 05, 01, 16, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1957, 07, 01, 17, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1959, 09, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1961, 11, 01, 00, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 02, 00, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 02, 59, 00, DateTimeKind.Utc), true); VerifyDST(s_catamarcaTz, new DateTime(1963, 10, 01, 03, 00, 00, DateTimeKind.Utc), false); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux will use local mean time for DateTimes before standard time came into effect. [InlineData("1940-02-24T23:59:59.0000000Z", false, "0:00:00")] [InlineData("1940-02-25T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1940-11-20T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1940-12-31T23:59:59.0000000Z", true, "1:00:00")] [InlineData("1941-01-01T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-02-24T12:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T01:00:00.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T22:59:59.0000000Z", true, "1:00:00")] [InlineData("1945-11-17T23:00:00.0000000Z", false, "0:00:00")] public static void IsDaylightSavingTime_CasablancaMultiYearDaylightSavings(string dateTimeString, bool expectedDST, string expectedOffsetString) { // Africa/Casablanca had DST from // 1940-02-25T00:00:00.0000000Z {+01:00:00 DST=True} // 1945-11-17T23:00:00.0000000Z { 00:00:00 DST=False} DateTime dt = DateTime.ParseExact(dateTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); VerifyDST(s_casablancaTz, dt, expectedDST); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_casablancaTz.GetUtcOffset(dt)); } [Fact] [SkipOnPlatform(TestPlatforms.Windows, "Not supported on Windows.")] public static void TestSplittingRulesWhenReported() { // This test confirm we are splitting the rules which span multiple years on Linux // we use "America/Los_Angeles" which has the rule covering 2/9/1942 to 8/14/1945 // with daylight transition by 01:00:00. This rule should be split into 3 rules: // - rule 1 from 2/9/1942 to 12/31/1942 // - rule 2 from 1/1/1943 to 12/31/1944 // - rule 3 from 1/1/1945 to 8/14/1945 TimeZoneInfo.AdjustmentRule[] rules = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific).GetAdjustmentRules(); bool ruleEncountered = false; for (int i = 0; i < rules.Length; i++) { if (rules[i].DateStart == new DateTime(1942, 2, 9)) { Assert.True(i + 2 <= rules.Length - 1); TimeSpan daylightDelta = TimeSpan.FromHours(1); // DateStart : 2/9/1942 12:00:00 AM (Unspecified) // DateEnd : 12/31/1942 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:02:00:00 M:2, D:9, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:23:59:59.9990000 M:12, D:31, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1942, 12, 31), rules[i].DateEnd); Assert.Equal(daylightDelta, rules[i].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 2, 9), rules[i].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 59, 59, 999), 12, 31), rules[i].DaylightTransitionEnd); // DateStart : 1/1/1943 12:00:00 AM (Unspecified) // DateEnd : 12/31/1944 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:00:00:00 M:1, D:1, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:23:59:59.9990000 M:12, D:31, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1943, 1, 1), rules[i + 1].DateStart); Assert.Equal(new DateTime(1944, 12, 31), rules[i + 1].DateEnd); Assert.Equal(daylightDelta, rules[i + 1].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 0, 0, 0), 1, 1), rules[i + 1].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 23, 59, 59, 999), 12, 31), rules[i + 1].DaylightTransitionEnd); // DateStart : 1/1/1945 12:00:00 AM (Unspecified) // DateEnd : 8/14/1945 12:00:00 AM (Unspecified) // DaylightDelta : 01:00:00 // DaylightTransitionStart : ToD:00:00:00 M:1, D:1, W:1, DoW:Sunday, FixedDate:True // DaylightTransitionEnd : ToD:15:59:59.9990000 M:8, D:14, W:1, DoW:Sunday, FixedDate:True Assert.Equal(new DateTime(1945, 1, 1), rules[i + 2].DateStart); Assert.Equal(new DateTime(1945, 8, 14), rules[i + 2].DateEnd); Assert.Equal(daylightDelta, rules[i + 2].DaylightDelta); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 0, 0, 0), 1, 1), rules[i + 2].DaylightTransitionStart); Assert.Equal(TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 15, 59, 59, 999), 8, 14), rules[i + 2].DaylightTransitionEnd); ruleEncountered = true; break; } } Assert.True(ruleEncountered, "The 1942 rule of America/Los_Angeles not found."); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux will use local mean time for DateTimes before standard time came into effect. // in 1996 Europe/Lisbon changed from standard time to DST without changing the UTC offset [InlineData("1995-09-30T17:00:00.0000000Z", false, "1:00:00")] [InlineData("1996-03-31T00:59:59.0000000Z", false, "1:00:00")] [InlineData("1996-03-31T01:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-03-31T01:00:01.0000000Z", true, "1:00:00")] [InlineData("1996-03-31T11:00:01.0000000Z", true, "1:00:00")] [InlineData("1996-08-31T11:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T00:00:00.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T00:59:59.0000000Z", true, "1:00:00")] [InlineData("1996-10-27T01:00:00.0000000Z", false, "0:00:00")] [InlineData("1996-10-28T01:00:00.0000000Z", false, "0:00:00")] [InlineData("1997-03-30T00:59:59.0000000Z", false, "0:00:00")] [InlineData("1997-03-30T01:00:00.0000000Z", true, "1:00:00")] public static void IsDaylightSavingTime_LisbonDaylightSavingsWithNoOffsetChange(string dateTimeString, bool expectedDST, string expectedOffsetString) { DateTime dt = DateTime.ParseExact(dateTimeString, "o", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); VerifyDST(s_LisbonTz, dt, expectedDST); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_LisbonTz.GetUtcOffset(dt)); } [Theory] // Newfoundland is UTC-3:30 standard and UTC-2:30 dst // using non-UTC date times in this test to get some coverage for non-UTC date times [InlineData("2015-03-08T01:59:59", false, false, false, "-3:30:00", "-8:00:00")] // since DST kicks in a 2AM, from 2AM - 3AM is Invalid [InlineData("2015-03-08T02:00:00", false, true, false, "-3:30:00", "-8:00:00")] [InlineData("2015-03-08T02:59:59", false, true, false, "-3:30:00", "-8:00:00")] [InlineData("2015-03-08T03:00:00", true, false, false, "-2:30:00", "-8:00:00")] [InlineData("2015-03-08T07:29:59", true, false, false, "-2:30:00", "-8:00:00")] [InlineData("2015-03-08T07:30:00", true, false, false, "-2:30:00", "-7:00:00")] [InlineData("2015-11-01T00:59:59", true, false, false, "-2:30:00", "-7:00:00")] [InlineData("2015-11-01T01:00:00", false, false, true, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T01:59:59", false, false, true, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T02:00:00", false, false, false, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T05:29:59", false, false, false, "-3:30:00", "-7:00:00")] [InlineData("2015-11-01T05:30:00", false, false, false, "-3:30:00", "-8:00:00")] public static void NewfoundlandTimeZone(string dateTimeString, bool expectedDST, bool isInvalidTime, bool isAmbiguousTime, string expectedOffsetString, string pacificOffsetString) { DateTime dt = DateTime.ParseExact(dateTimeString, "s", CultureInfo.InvariantCulture); VerifyInv(s_NewfoundlandTz, dt, isInvalidTime); if (!isInvalidTime) { VerifyDST(s_NewfoundlandTz, dt, expectedDST); VerifyAmbiguous(s_NewfoundlandTz, dt, isAmbiguousTime); TimeSpan offset = TimeSpan.Parse(expectedOffsetString, CultureInfo.InvariantCulture); Assert.Equal(offset, s_NewfoundlandTz.GetUtcOffset(dt)); TimeSpan pacificOffset = TimeSpan.Parse(pacificOffsetString, CultureInfo.InvariantCulture); VerifyConvert(dt, s_strNewfoundland, s_strPacific, dt - (offset - pacificOffset)); } } [Fact] public static void GetSystemTimeZones() { ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); Assert.NotEmpty(timeZones); Assert.Contains(timeZones, t => t.Id == s_strPacific); Assert.Contains(timeZones, t => t.Id == s_strSydney); Assert.Contains(timeZones, t => t.Id == s_strGMT); Assert.Contains(timeZones, t => t.Id == s_strTonga); Assert.Contains(timeZones, t => t.Id == s_strBrasil); Assert.Contains(timeZones, t => t.Id == s_strPerth); Assert.Contains(timeZones, t => t.Id == s_strBrasilia); Assert.Contains(timeZones, t => t.Id == s_strNairobi); Assert.Contains(timeZones, t => t.Id == s_strAmsterdam); Assert.Contains(timeZones, t => t.Id == s_strRussian); Assert.Contains(timeZones, t => t.Id == s_strLibya); Assert.Contains(timeZones, t => t.Id == s_strCatamarca); Assert.Contains(timeZones, t => t.Id == s_strLisbon); Assert.Contains(timeZones, t => t.Id == s_strNewfoundland); // ensure the TimeZoneInfos are sorted by BaseUtcOffset and then DisplayName. TimeZoneInfo previous = timeZones[0]; for (int i = 1; i < timeZones.Count; i++) { TimeZoneInfo current = timeZones[i]; int baseOffsetsCompared = current.BaseUtcOffset.CompareTo(previous.BaseUtcOffset); Assert.True(baseOffsetsCompared >= 0, string.Format("TimeZoneInfos are out of order. {0}:{1} should be before {2}:{3}", previous.Id, previous.BaseUtcOffset, current.Id, current.BaseUtcOffset)); if (baseOffsetsCompared == 0) { Assert.True(current.DisplayName.CompareTo(previous.DisplayName) >= 0, string.Format("TimeZoneInfos are out of order. {0} should be before {1}", previous.DisplayName, current.DisplayName)); } } } [Fact] public static void DaylightTransitionsExactTime() { TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); DateTime after = new DateTime(2011, 11, 6, 9, 0, 0, 0, DateTimeKind.Utc); DateTime mid = after.AddTicks(-1); DateTime before = after.AddTicks(-2); Assert.Equal(TimeSpan.FromHours(-7), zone.GetUtcOffset(before)); Assert.Equal(TimeSpan.FromHours(-7), zone.GetUtcOffset(mid)); Assert.Equal(TimeSpan.FromHours(-8), zone.GetUtcOffset(after)); } /// <summary> /// Ensure Africa/Johannesburg transitions from +3 to +2 at /// 1943-02-20T23:00:00Z, and not a tick before that. /// See https://github.com/dotnet/runtime/issues/4728 /// </summary> [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Linux and Windows rules differ in this case public static void DaylightTransitionsExactTime_Johannesburg() { DateTimeOffset transition = new DateTimeOffset(1943, 3, 20, 23, 0, 0, TimeSpan.Zero); Assert.Equal(TimeSpan.FromHours(3), s_johannesburgTz.GetUtcOffset(transition.AddTicks(-2))); Assert.Equal(TimeSpan.FromHours(3), s_johannesburgTz.GetUtcOffset(transition.AddTicks(-1))); Assert.Equal(TimeSpan.FromHours(2), s_johannesburgTz.GetUtcOffset(transition)); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { s_casablancaTz, s_casablancaTz, true }; yield return new object[] { s_casablancaTz, s_LisbonTz, false }; yield return new object[] { TimeZoneInfo.Utc, TimeZoneInfo.Utc, true }; yield return new object[] { TimeZoneInfo.Utc, s_casablancaTz, false }; yield return new object[] { TimeZoneInfo.Local, TimeZoneInfo.Local, true }; yield return new object[] { TimeZoneInfo.Local, new object(), false }; yield return new object[] { TimeZoneInfo.Local, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void EqualsTest(TimeZoneInfo timeZoneInfo, object obj, bool expected) { Assert.Equal(expected, timeZoneInfo.Equals(obj)); if (obj is TimeZoneInfo) { Assert.Equal(expected, timeZoneInfo.Equals((TimeZoneInfo)obj)); Assert.Equal(expected, timeZoneInfo.GetHashCode().Equals(obj.GetHashCode())); } } [Fact] public static void ClearCachedData() { TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(s_strSydney); TimeZoneInfo local = TimeZoneInfo.Local; TimeZoneInfo.ClearCachedData(); Assert.ThrowsAny<ArgumentException>(() => { TimeZoneInfo.ConvertTime(DateTime.Now, local, cst); }); } [Fact] public static void ConvertTime_DateTimeOffset_NullDestination_ArgumentNullException() { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<ArgumentNullException>(time1, null); } public static IEnumerable<object[]> ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData() { yield return new object[] { string.Empty }; yield return new object[] { " " }; yield return new object[] { "\0" }; yield return new object[] { s_strPacific.Substring(0, s_strPacific.Length / 2) }; // whole string must match yield return new object[] { s_strPacific + " Zone" }; // no extra characters yield return new object[] { " " + s_strPacific }; // no leading space yield return new object[] { s_strPacific + " " }; // no trailing space yield return new object[] { "\0" + s_strPacific }; // no leading null yield return new object[] { s_strPacific + "\0" }; // no trailing null yield return new object[] { s_strPacific + "\\ " }; // no trailing null yield return new object[] { s_strPacific + "\\Display" }; yield return new object[] { s_strPacific + "\n" }; // no trailing newline yield return new object[] { new string('a', 100) }; // long string } [Theory] [MemberData(nameof(ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException_MemberData))] public static void ConvertTime_DateTimeOffset_InvalidDestination_TimeZoneNotFoundException(string destinationId) { DateTimeOffset time1 = new DateTimeOffset(2006, 5, 12, 0, 0, 0, TimeSpan.Zero); VerifyConvertException<TimeZoneNotFoundException>(time1, destinationId); } [Fact] public static void ConvertTimeFromUtc() { // destination timezone is null Assert.Throws<ArgumentNullException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0), null); }); // destination timezone is UTC DateTime now = DateTime.UtcNow; DateTime convertedNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Utc); Assert.Equal(now, convertedNow); } [Fact] public static void ConvertTimeToUtc() { // null source VerifyConvertToUtcException<ArgumentNullException>(new DateTime(2007, 5, 3, 12, 16, 0), null); TimeZoneInfo london = CreateCustomLondonTimeZone(); // invalid DateTime DateTime invalidDate = new DateTime(2007, 3, 25, 1, 30, 0); VerifyConvertToUtcException<ArgumentException>(invalidDate, london); // DateTimeKind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Utc), london); // correct UTC conversion DateTime date = new DateTime(2007, 01, 01, 0, 0, 0); Assert.Equal(date.ToUniversalTime(), TimeZoneInfo.ConvertTimeToUtc(date)); } [Fact] public static void ConvertTimeFromToUtc() { TimeZoneInfo london = CreateCustomLondonTimeZone(); DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Utc); Assert.Equal(DateTimeKind.Utc, back.Kind); Assert.Equal(utc, back); converted = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); DateTimeKind expectedKind = (TimeZoneInfo.Local == TimeZoneInfo.Utc) ? DateTimeKind.Utc : DateTimeKind.Local; Assert.Equal(expectedKind, converted.Kind); back = TimeZoneInfo.ConvertTimeToUtc(converted, TimeZoneInfo.Local); Assert.Equal(DateTimeKind.Utc, back.Kind); Assert.Equal(utc, back); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix public static void ConvertTimeFromToUtc_UnixOnly() { // DateTime Kind is Local Assert.ThrowsAny<ArgumentException>(() => { DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2007, 5, 3, 11, 8, 0, DateTimeKind.Local), TimeZoneInfo.Local); }); TimeZoneInfo london = CreateCustomLondonTimeZone(); // winter (no DST) DateTime winter = new DateTime(2007, 12, 25, 12, 0, 0); DateTime convertedWinter = TimeZoneInfo.ConvertTimeFromUtc(winter, london); Assert.Equal(winter, convertedWinter); // summer (DST) DateTime summer = new DateTime(2007, 06, 01, 12, 0, 0); DateTime convertedSummer = TimeZoneInfo.ConvertTimeFromUtc(summer, london); Assert.Equal(summer + new TimeSpan(1, 0, 0), convertedSummer); // Kind and source types don't match VerifyConvertToUtcException<ArgumentException>(new DateTime(2007, 5, 3, 12, 8, 0, DateTimeKind.Local), london); // Test the ambiguous date DateTime utcAmbiguous = new DateTime(2016, 10, 30, 0, 14, 49, DateTimeKind.Utc); DateTime convertedAmbiguous = TimeZoneInfo.ConvertTimeFromUtc(utcAmbiguous, london); Assert.Equal(DateTimeKind.Unspecified, convertedAmbiguous.Kind); Assert.True(london.IsAmbiguousTime(convertedAmbiguous), $"Expected to have {convertedAmbiguous} is ambiguous"); // convert to London time and back DateTime utc = DateTime.UtcNow; Assert.Equal(DateTimeKind.Utc, utc.Kind); DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utc, london); Assert.Equal(DateTimeKind.Unspecified, converted.Kind); DateTime back = TimeZoneInfo.ConvertTimeToUtc(converted, london); Assert.Equal(DateTimeKind.Utc, back.Kind); if (london.IsAmbiguousTime(converted)) { // if the time is ambiguous this will not round trip the original value because this ambiguous time can be mapped into // 2 UTC times. usually we return the value with the DST delta added to it. back = back.AddTicks(-london.GetAdjustmentRules()[0].DaylightDelta.Ticks); } Assert.Equal(utc, back); } [Fact] public static void CreateCustomTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // supports DST TimeZoneInfo tz1 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }); Assert.True(tz1.SupportsDaylightSavingTime); // doesn't support DST TimeZoneInfo tz2 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(4, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1 }, true); Assert.False(tz2.SupportsDaylightSavingTime); TimeZoneInfo tz3 = TimeZoneInfo.CreateCustomTimeZone("mytimezone", new TimeSpan(6, 0, 0), null, null, null, null); Assert.False(tz3.SupportsDaylightSavingTime); } [Fact] public static void CreateCustomTimeZone_Invalid() { VerifyCustomTimeZoneException<ArgumentNullException>(null, new TimeSpan(0), null, null); // null Id VerifyCustomTimeZoneException<ArgumentException>("", new TimeSpan(0), null, null); // empty string Id VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(0, 0, 55), null, null); // offset not minutes VerifyCustomTimeZoneException<ArgumentException>("mytimezone", new TimeSpan(14, 1, 0), null, null); // offset too big VerifyCustomTimeZoneException<ArgumentException>("mytimezone", -new TimeSpan(14, 1, 0), null, null); // offset too small } [Fact] public static void CreateCustomTimeZone_InvalidTimeZone() { TimeZoneInfo.TransitionTime s1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 3, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e1 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime s2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 2, 2, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime e2 = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 11, 2, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule r1 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(1, 0, 0), s1, e1); // AdjustmentRules overlap TimeZoneInfo.AdjustmentRule r2 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2004, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r2 }); // AdjustmentRules not ordered TimeZoneInfo.AdjustmentRule r3 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2006, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r3, r1 }); // Offset out of range TimeZoneInfo.AdjustmentRule r4 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2000, 1, 1), new DateTime(2005, 1, 1), new TimeSpan(3, 0, 0), s1, e1); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r4 }); // overlapping AdjustmentRules for a date TimeZoneInfo.AdjustmentRule r5 = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(2005, 1, 1), new DateTime(2007, 1, 1), new TimeSpan(1, 0, 0), s2, e2); VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(6, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { r1, r5 }); // null AdjustmentRule VerifyCustomTimeZoneException<InvalidTimeZoneException>("mytimezone", new TimeSpan(12, 0, 0), null, null, null, new TimeZoneInfo.AdjustmentRule[] { null }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // TimeZone not found on Windows public static void HasSameRules_RomeAndVatican() { TimeZoneInfo rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"); TimeZoneInfo vatican = TimeZoneInfo.FindSystemTimeZoneById("Europe/Vatican"); Assert.True(rome.HasSameRules(vatican)); } [Fact] public static void HasSameRules_NullAdjustmentRules() { TimeZoneInfo utc = TimeZoneInfo.Utc; TimeZoneInfo custom = TimeZoneInfo.CreateCustomTimeZone("Custom", new TimeSpan(0), "Custom", "Custom"); Assert.True(utc.HasSameRules(custom)); } [Fact] public static void ConvertTimeBySystemTimeZoneIdTests() { DateTime now = DateTime.Now; DateTime utcNow = TimeZoneInfo.ConvertTimeToUtc(now); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Utc.Id)); Assert.Equal(now, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, TimeZoneInfo.Utc.Id, TimeZoneInfo.Local.Id)); Assert.Equal(utcNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, TimeZoneInfo.Local.Id, TimeZoneInfo.Utc.Id)); DateTimeOffset offsetNow = new DateTimeOffset(now); DateTimeOffset utcOffsetNow = new DateTimeOffset(utcNow); Assert.Equal(offsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcOffsetNow, TimeZoneInfo.Local.Id)); Assert.Equal(utcOffsetNow, TimeZoneInfo.ConvertTimeBySystemTimeZoneId(offsetNow, TimeZoneInfo.Utc.Id)); } public static IEnumerable<object[]> SystemTimeZonesTestData() { foreach (TimeZoneInfo tz in TimeZoneInfo.GetSystemTimeZones()) { yield return new object[] { tz }; } // Include fixed offset IANA zones in the test data when they are available. if (!PlatformDetection.IsWindows) { for (int i = -14; i <= 12; i++) { TimeZoneInfo tz = null; try { string id = $"Etc/GMT{i:+0;-0}"; tz = TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException) { } if (tz != null) { yield return new object[] { tz }; } } } } private const string IanaAbbreviationPattern = @"^(?:[A-Z][A-Za-z]+|[+-]\d{2}|[+-]\d{4})$"; [RegexGenerator(IanaAbbreviationPattern)] private static partial Regex IanaAbbreviationRegex(); // UTC aliases per https://github.com/unicode-org/cldr/blob/master/common/bcp47/timezone.xml // (This list is not likely to change.) private static readonly string[] s_UtcAliases = new[] { "Etc/UTC", "Etc/UCT", "Etc/Universal", "Etc/Zulu", "UCT", "UTC", "Universal", "Zulu" }; // On Android GMT, GMT+0, and GMT-0 are values private static readonly string[] s_GMTAliases = new[] { "GMT", "GMT0", "GMT+0", "GMT-0" }; [Theory] [MemberData(nameof(SystemTimeZonesTestData))] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void TimeZoneDisplayNames_Unix(TimeZoneInfo timeZone) { bool isUtc = s_UtcAliases.Contains(timeZone.Id, StringComparer.OrdinalIgnoreCase); if (PlatformDetection.IsBrowser) { // Browser platform doesn't have full ICU names, but uses the IANA IDs and abbreviations instead. // The display name will be the offset plus the ID. // The offset is checked separately in TimeZoneInfo_DisplayNameStartsWithOffset Assert.True(timeZone.DisplayName.EndsWith(" " + timeZone.Id), $"Id: \"{timeZone.Id}\", DisplayName should have ended with the ID, Actual DisplayName: \"{timeZone.DisplayName}\""); if (isUtc) { // Make sure UTC and its aliases have exactly "UTC" for the standard and daylight names Assert.True(timeZone.StandardName == "UTC", $"Id: \"{timeZone.Id}\", Expected StandardName: \"UTC\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(timeZone.DaylightName == "UTC", $"Id: \"{timeZone.Id}\", Expected DaylightName: \"UTC\", Actual DaylightName: \"{timeZone.DaylightName}\""); } else { // For other time zones, match any valid IANA time zone abbreviation, including numeric forms Assert.True(IanaAbbreviationRegex().IsMatch(timeZone.StandardName), $"Id: \"{timeZone.Id}\", StandardName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(IanaAbbreviationRegex().IsMatch(timeZone.DaylightName), $"Id: \"{timeZone.Id}\", DaylightName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual DaylightName: \"{timeZone.DaylightName}\""); } } else if (isUtc) { // UTC's display name is the string "(UTC) " and the same text as the standard name. Assert.True(timeZone.DisplayName == $"(UTC) {timeZone.StandardName}", $"Id: \"{timeZone.Id}\", Expected DisplayName: \"(UTC) {timeZone.StandardName}\", Actual DisplayName: \"{timeZone.DisplayName}\""); // All aliases of UTC should have the same names as UTC itself Assert.True(timeZone.DisplayName == TimeZoneInfo.Utc.DisplayName, $"Id: \"{timeZone.Id}\", Expected DisplayName: \"{TimeZoneInfo.Utc.DisplayName}\", Actual DisplayName: \"{timeZone.DisplayName}\""); Assert.True(timeZone.StandardName == TimeZoneInfo.Utc.StandardName, $"Id: \"{timeZone.Id}\", Expected StandardName: \"{TimeZoneInfo.Utc.StandardName}\", Actual StandardName: \"{timeZone.StandardName}\""); Assert.True(timeZone.DaylightName == TimeZoneInfo.Utc.DaylightName, $"Id: \"{timeZone.Id}\", Expected DaylightName: \"{TimeZoneInfo.Utc.DaylightName}\", Actual DaylightName: \"{timeZone.DaylightName}\""); } else { // All we can really say generically here is that they aren't empty. Assert.False(string.IsNullOrWhiteSpace(timeZone.DisplayName), $"Id: \"{timeZone.Id}\", DisplayName should not have been empty."); Assert.False(string.IsNullOrWhiteSpace(timeZone.StandardName), $"Id: \"{timeZone.Id}\", StandardName should not have been empty."); // GMT* on Android does sets daylight savings time to false, so there will be no DaylightName if (!PlatformDetection.IsAndroid || (PlatformDetection.IsAndroid && !timeZone.Id.StartsWith("GMT"))) { Assert.False(string.IsNullOrWhiteSpace(timeZone.DaylightName), $"Id: \"{timeZone.Id}\", DaylightName should not have been empty."); } } } [ActiveIssue("https://github.com/dotnet/runtime/issues/19794", TestPlatforms.AnyUnix)] [Theory] [MemberData(nameof(SystemTimeZonesTestData))] public static void ToSerializedString_FromSerializedString_RoundTrips(TimeZoneInfo timeZone) { string serialized = timeZone.ToSerializedString(); TimeZoneInfo deserializedTimeZone = TimeZoneInfo.FromSerializedString(serialized); Assert.Equal(timeZone, deserializedTimeZone); Assert.Equal(serialized, deserializedTimeZone.ToSerializedString()); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] [MemberData(nameof(SystemTimeZonesTestData))] public static void BinaryFormatter_RoundTrips(TimeZoneInfo timeZone) { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, timeZone); stream.Position = 0; TimeZoneInfo deserializedTimeZone = (TimeZoneInfo)formatter.Deserialize(stream); Assert.Equal(timeZone, deserializedTimeZone); } } [Fact] public static void TimeZoneInfo_DoesNotCreateAdjustmentRulesWithOffsetOutsideOfRange() { // On some OSes with some time zones setting // time zone may contain old adjustment rule which have offset higher than 14h // Assert.DoesNotThrow DateTimeOffset.FromFileTime(0); } [Fact] public static void TimeZoneInfo_DoesConvertTimeForOldDatesOfTimeZonesWithExceedingMaxRange() { // On some OSes this time zone contains old adjustment rules which have offset higher than 14h TimeZoneInfo tzi = TryGetSystemTimeZone("Asia/Manila"); if (tzi == null) { // Time zone could not be found return; } // Assert.DoesNotThrow TimeZoneInfo.ConvertTime(new DateTimeOffset(1800, 4, 4, 10, 10, 4, 2, TimeSpan.Zero), tzi); } [Fact] public static void GetSystemTimeZones_AllTimeZonesHaveOffsetInValidRange() { foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { foreach (TimeZoneInfo.AdjustmentRule ar in tzi.GetAdjustmentRules()) { Assert.True(Math.Abs((tzi.GetUtcOffset(ar.DateStart)).TotalHours) <= 14.0); } } } private static byte[] timeZoneFileContents = new byte[] { 0x54, 0x5A, 0x69, 0x66, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x5A, 0x69, 0x66, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xF8, 0xE4, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x10, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x0E, 0x10, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x4C, 0x4D, 0x54, 0x00, 0x2B, 0x30, 0x31, 0x00, 0x2B, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // POSIX Rule // 0x0A, 0x3C, 0x2B, 0x30, 0x30, 0x3E, 0x30, 0x3C, 0x2B, 0x30, 0x31, // 0x3E, 0x2C, 0x30, 0x2F, 0x30, 0x2C, 0x4A, 0x33, 0x36, 0x35, 0x2F, 0x32, 0x35, 0x0A }; [ActiveIssue("https://github.com/dotnet/runtime/issues/64134")] [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [PlatformSpecific(TestPlatforms.AnyUnix)] [InlineData("<+00>0<+01>,0/0,J365/25", 1, 1, true)] [InlineData("<+00>0<+01>,30/0,J365/25", 31, 1, true)] [InlineData("<+00>0<+01>,31/0,J365/25", 1, 2, true)] [InlineData("<+00>0<+01>,58/0,J365/25", 28, 2, true)] [InlineData("<+00>0<+01>,59/0,J365/25", 0, 0, false)] [InlineData("<+00>0<+01>,9999999/0,J365/25", 0, 0, false)] [InlineData("<+00>0<+01>,A/0,J365/25", 0, 0, false)] public static void NJulianRuleTest(string posixRule, int dayNumber, int monthNumber, bool shouldSucceed) { string zoneFilePath = Path.GetTempPath() + Path.GetRandomFileName(); using (FileStream fs = new FileStream(zoneFilePath, FileMode.Create)) { fs.Write(timeZoneFileContents.AsSpan()); // Append the POSIX rule fs.WriteByte(0x0A); foreach (char c in posixRule) { fs.WriteByte((byte)c); } fs.WriteByte(0x0A); } try { ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("TZ", zoneFilePath); RemoteExecutor.Invoke((day, month, succeed) => { bool expectedToSucceed = bool.Parse(succeed); int d = int.Parse(day); int m = int.Parse(month); TimeZoneInfo.AdjustmentRule[] rules = TimeZoneInfo.Local.GetAdjustmentRules(); if (expectedToSucceed) { Assert.Equal(1, rules.Length); Assert.Equal(d, rules[0].DaylightTransitionStart.Day); Assert.Equal(m, rules[0].DaylightTransitionStart.Month); } else { Assert.Equal(0, rules.Length); } }, dayNumber.ToString(), monthNumber.ToString(), shouldSucceed.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); } finally { try { File.Delete(zoneFilePath); } catch { } // don't fail the test if we couldn't delete the file. } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static void TimeZoneInfo_LocalZoneWithInvariantMode() { string hostTZId = TimeZoneInfo.Local.Id; ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", PlatformDetection.IsInvariantGlobalization ? "0" : "1"); RemoteExecutor.Invoke((tzId, hostIsRunningInInvariantMode) => { bool hostInvariantMode = bool.Parse(hostIsRunningInInvariantMode); if (!hostInvariantMode) { // If hostInvariantMode is false, means the child process should enable the globalization invariant mode. // We validate here that by trying to create a culture which should throws in such mode. Assert.Throws<CultureNotFoundException>(() => CultureInfo.GetCultureInfo("en-US")); } Assert.Equal(tzId, TimeZoneInfo.Local.Id); }, hostTZId, PlatformDetection.IsInvariantGlobalization.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); } [Fact] public static void TimeZoneInfo_DaylightDeltaIsNoMoreThan12Hours() { foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { foreach (TimeZoneInfo.AdjustmentRule ar in tzi.GetAdjustmentRules()) { Assert.True(Math.Abs(ar.DaylightDelta.TotalHours) <= 12.0); } } } [Theory] [MemberData(nameof(SystemTimeZonesTestData))] public static void TimeZoneInfo_DisplayNameStartsWithOffset(TimeZoneInfo tzi) { if (s_UtcAliases.Contains(tzi.Id, StringComparer.OrdinalIgnoreCase)) { // UTC and all of its aliases (Etc/UTC, and others) start with just "(UTC) " Assert.StartsWith("(UTC) ", tzi.DisplayName); } else if (s_GMTAliases.Contains(tzi.Id, StringComparer.OrdinalIgnoreCase)) { Assert.StartsWith("GMT", tzi.DisplayName); } else { Assert.False(string.IsNullOrWhiteSpace(tzi.StandardName)); Match match = Regex.Match(tzi.DisplayName, @"^\(UTC(?<sign>\+|-)(?<amount>[0-9]{2}:[0-9]{2})\) \S.*", RegexOptions.ExplicitCapture); Assert.True(match.Success); // see https://github.com/dotnet/corefx/pull/33204#issuecomment-438782500 if (PlatformDetection.IsNotWindowsNanoServer && !PlatformDetection.IsWindows7) { string offset = (match.Groups["sign"].Value == "-" ? "-" : "") + match.Groups["amount"].Value; TimeSpan ts = TimeSpan.Parse(offset); if (PlatformDetection.IsWindows && tzi.BaseUtcOffset != ts && (tzi.Id.Contains("Morocco") || tzi.Id.Contains("Volgograd"))) { // Windows data can report display name with UTC+01:00 offset which is not matching the actual BaseUtcOffset. // We special case this in the test to avoid the test failures like: // 01:00 != 00:00:00, dn:(UTC+01:00) Casablanca, sn:Morocco Standard Time // 04:00 != 03:00:00, dn:(UTC+04:00) Volgograd, sn:Volgograd Standard Time if (tzi.Id.Contains("Morocco")) { Assert.True(tzi.BaseUtcOffset == new TimeSpan(0, 0, 0), $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } else { // Volgograd, Russia Assert.True(tzi.BaseUtcOffset == new TimeSpan(3, 0, 0), $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } } else { Assert.True(tzi.BaseUtcOffset == ts || tzi.GetUtcOffset(DateTime.Now) == ts, $"{offset} != {tzi.BaseUtcOffset}, dn:{tzi.DisplayName}, sn:{tzi.StandardName}"); } } } } [Fact] public static void EnsureUtcObjectSingleton() { TimeZoneInfo utcObject = TimeZoneInfo.GetSystemTimeZones().Single(x => x.Id.Equals("UTC", StringComparison.OrdinalIgnoreCase)); Assert.True(ReferenceEquals(utcObject, TimeZoneInfo.Utc)); Assert.True(ReferenceEquals(TimeZoneInfo.FindSystemTimeZoneById("UTC"), TimeZoneInfo.Utc)); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))] [InlineData("Pacific Standard Time", "America/Los_Angeles")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney")] [InlineData("GMT Standard Time", "Europe/London")] [InlineData("Tonga Standard Time", "Pacific/Tongatapu")] [InlineData("W. Australia Standard Time", "Australia/Perth")] [InlineData("E. South America Standard Time", "America/Sao_Paulo")] [InlineData("E. Africa Standard Time", "Africa/Nairobi")] [InlineData("W. Europe Standard Time", "Europe/Berlin")] [InlineData("Russian Standard Time", "Europe/Moscow")] [InlineData("Libya Standard Time", "Africa/Tripoli")] [InlineData("South Africa Standard Time", "Africa/Johannesburg")] [InlineData("Morocco Standard Time", "Africa/Casablanca")] [InlineData("Argentina Standard Time", "America/Argentina/Catamarca")] [InlineData("Newfoundland Standard Time", "America/St_Johns")] [InlineData("Iran Standard Time", "Asia/Tehran")] public static void UsingAlternativeTimeZoneIdsTest(string windowsId, string ianaId) { if (PlatformDetection.ICUVersion.Major >= 52 && !PlatformDetection.IsiOS && !PlatformDetection.IstvOS) { TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById(ianaId); TimeZoneInfo tzi2 = TimeZoneInfo.FindSystemTimeZoneById(windowsId); Assert.Equal(tzi1.BaseUtcOffset, tzi2.BaseUtcOffset); Assert.NotEqual(tzi1.Id, tzi2.Id); } else { Assert.Throws<TimeZoneNotFoundException>(() => TimeZoneInfo.FindSystemTimeZoneById(s_isWindows ? ianaId : windowsId)); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(s_isWindows ? windowsId : ianaId); } } public static bool SupportIanaNamesConversion => PlatformDetection.IsNotMobile && PlatformDetection.ICUVersion.Major >= 52; public static bool SupportIanaNamesConversionAndRemoteExecution => SupportIanaNamesConversion && RemoteExecutor.IsSupported; public static bool DoesNotSupportIanaNamesConversion => !SupportIanaNamesConversion; // This test is executed using the remote execution because it needs to run before creating the time zone cache to ensure testing with that state. // There are already other tests that test after creating the cache. [ConditionalFact(nameof(SupportIanaNamesConversionAndRemoteExecution))] public static void IsIanaIdWithNotCacheTest() { RemoteExecutor.Invoke(() => { Assert.Equal(!s_isWindows || TimeZoneInfo.Local.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase), TimeZoneInfo.Local.HasIanaId); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"); Assert.False(tzi.HasIanaId); tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin"); Assert.True(tzi.HasIanaId); }).Dispose(); } [ConditionalFact(nameof(SupportIanaNamesConversion))] public static void IsIanaIdTest() { bool expected = !s_isWindows; Assert.Equal((expected || TimeZoneInfo.Local.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase)), TimeZoneInfo.Local.HasIanaId); foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones()) { Assert.True((expected || tzi.Id.Equals("Utc", StringComparison.OrdinalIgnoreCase)) == tzi.HasIanaId, $"`{tzi.Id}` has wrong IANA Id indicator"); } Assert.False(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time").HasIanaId, $" should not be IANA Id."); Assert.True(TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles").HasIanaId, $"'America/Los_Angeles' should be IANA Id"); } [ConditionalFact(nameof(DoesNotSupportIanaNamesConversion))] [PlatformSpecific(~TestPlatforms.Android)] public static void UnsupportedImplicitConversionTest() { string nonNativeTzName = s_isWindows ? "America/Los_Angeles" : "Pacific Standard Time"; Assert.Throws<TimeZoneNotFoundException>(() => TimeZoneInfo.FindSystemTimeZoneById(nonNativeTzName)); } [ConditionalTheory(nameof(SupportIanaNamesConversion))] [InlineData("Pacific Standard Time", "America/Los_Angeles")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney")] [InlineData("GMT Standard Time", "Europe/London")] [InlineData("Tonga Standard Time", "Pacific/Tongatapu")] [InlineData("W. Australia Standard Time", "Australia/Perth")] [InlineData("E. South America Standard Time", "America/Sao_Paulo")] [InlineData("E. Africa Standard Time", "Africa/Nairobi")] [InlineData("W. Europe Standard Time", "Europe/Berlin")] [InlineData("Russian Standard Time", "Europe/Moscow")] [InlineData("Libya Standard Time", "Africa/Tripoli")] [InlineData("South Africa Standard Time", "Africa/Johannesburg")] [InlineData("Morocco Standard Time", "Africa/Casablanca")] [InlineData("Argentina Standard Time", "America/Buenos_Aires")] [InlineData("Newfoundland Standard Time", "America/St_Johns")] [InlineData("Iran Standard Time", "Asia/Tehran")] public static void IdsConversionsTest(string windowsId, string ianaId) { Assert.True(TimeZoneInfo.TryConvertIanaIdToWindowsId(ianaId, out string winId)); Assert.Equal(windowsId, winId); Assert.True(TimeZoneInfo.TryConvertWindowsIdToIanaId(winId, out string ianaConvertedId)); Assert.Equal(ianaId, ianaConvertedId); } [ConditionalTheory(nameof(SupportIanaNamesConversion))] [InlineData("Pacific Standard Time", "America/Vancouver", "CA")] [InlineData("Pacific Standard Time", "America/Los_Angeles", "US")] [InlineData("Pacific Standard Time", "America/Los_Angeles", "\u0600NotValidRegion")] [InlineData("Central Europe Standard Time", "Europe/Budapest", "DJ")] [InlineData("Central Europe Standard Time", "Europe/Budapest", "\uFFFFNotValidRegion")] [InlineData("Central Europe Standard Time", "Europe/Prague", "CZ")] [InlineData("Central Europe Standard Time", "Europe/Ljubljana", "SI")] [InlineData("Central Europe Standard Time", "Europe/Bratislava", "SK")] [InlineData("Central Europe Standard Time", "Europe/Tirane", "AL")] [InlineData("Central Europe Standard Time", "Europe/Podgorica", "ME")] [InlineData("Central Europe Standard Time", "Europe/Belgrade", "RS")] // lowercased region name cases: [InlineData("Cen. Australia Standard Time", "Australia/Adelaide", "au")] [InlineData("AUS Central Standard Time", "Australia/Darwin", "au")] [InlineData("E. Australia Standard Time", "Australia/Brisbane", "au")] [InlineData("AUS Eastern Standard Time", "Australia/Sydney", "au")] [InlineData("Tasmania Standard Time", "Australia/Hobart", "au")] [InlineData("Romance Standard Time", "Europe/Madrid", "es")] [InlineData("Romance Standard Time", "Europe/Madrid", "Es")] [InlineData("Romance Standard Time", "Europe/Madrid", "eS")] [InlineData("GMT Standard Time", "Europe/London", "gb")] [InlineData("GMT Standard Time", "Europe/Dublin", "ie")] [InlineData("W. Europe Standard Time", "Europe/Rome", "it")] [InlineData("New Zealand Standard Time", "Pacific/Auckland", "nz")] public static void IdsConversionsWithRegionTest(string windowsId, string ianaId, string region) { Assert.True(TimeZoneInfo.TryConvertWindowsIdToIanaId(windowsId, region, out string ianaConvertedId)); Assert.Equal(ianaId, ianaConvertedId); } // We test the existence of a specific English time zone name to avoid failures on non-English platforms. [ConditionalFact(nameof(IsEnglishUILanguageAndRemoteExecutorSupported))] public static void TestNameWithInvariantCulture() { RemoteExecutor.Invoke(() => { // We call ICU to get the names. When passing invariant culture name to ICU, it fail and we'll use the abbreviated names at that time. // We fixed this issue by avoid sending the invariant culture name to ICU and this test is confirming we work fine at that time. CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; TimeZoneInfo.ClearCachedData(); TimeZoneInfo pacific = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); Assert.True(pacific.StandardName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.StandardName}' is not the expected standard name for Pacific time zone"); Assert.True(pacific.DaylightName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.DaylightName}' is not the expected daylight name for Pacific time zone"); Assert.True(pacific.DisplayName.IndexOf("Pacific", StringComparison.OrdinalIgnoreCase) >= 0, $"'{pacific.DisplayName}' is not the expected display name for Pacific time zone"); }).Dispose(); } private static readonly CultureInfo[] s_CulturesForWindowsNlsDisplayNamesTest = WindowsUILanguageHelper.GetInstalledWin32CulturesWithUniqueLanguages(); private static bool CanTestWindowsNlsDisplayNames => RemoteExecutor.IsSupported && s_CulturesForWindowsNlsDisplayNamesTest.Length > 1; [PlatformSpecific(TestPlatforms.Windows)] [ConditionalFact(nameof(CanTestWindowsNlsDisplayNames))] public static void TestWindowsNlsDisplayNames() { RemoteExecutor.Invoke(() => { CultureInfo[] cultures = s_CulturesForWindowsNlsDisplayNamesTest; CultureInfo.CurrentUICulture = cultures[0]; TimeZoneInfo.ClearCachedData(); TimeZoneInfo tz1 = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); CultureInfo.CurrentUICulture = cultures[1]; TimeZoneInfo.ClearCachedData(); TimeZoneInfo tz2 = TimeZoneInfo.FindSystemTimeZoneById(s_strPacific); Assert.True(tz1.DisplayName != tz2.DisplayName, $"The display name '{tz1.DisplayName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); Assert.True(tz1.StandardName != tz2.StandardName, $"The standard name '{tz1.StandardName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); Assert.True(tz1.DaylightName != tz2.DaylightName, $"The daylight name '{tz1.DaylightName}' should be different between {cultures[0].Name} and {cultures[1].Name}."); }).Dispose(); } [Theory] [PlatformSpecific(TestPlatforms.Browser)] [InlineData("America/Buenos_Aires", "America/Argentina/Buenos_Aires")] [InlineData("America/Catamarca", "America/Argentina/Catamarca")] [InlineData("America/Cordoba", "America/Argentina/Cordoba")] [InlineData("America/Jujuy", "America/Argentina/Jujuy")] [InlineData("America/Mendoza", "America/Argentina/Mendoza")] [InlineData("America/Indianapolis", "America/Indiana/Indianapolis")] public static void TestTimeZoneIdBackwardCompatibility(string oldId, string currentId) { TimeZoneInfo oldtz = TimeZoneInfo.FindSystemTimeZoneById(oldId); TimeZoneInfo currenttz = TimeZoneInfo.FindSystemTimeZoneById(currentId); Assert.Equal(oldtz.StandardName, currenttz.StandardName); Assert.Equal(oldtz.DaylightName, currenttz.DaylightName); // Note we cannot test the DisplayName, as it will contain the ID. } [Theory] [PlatformSpecific(TestPlatforms.Browser)] [InlineData("America/Buenos_Aires")] [InlineData("America/Catamarca")] [InlineData("America/Cordoba")] [InlineData("America/Jujuy")] [InlineData("America/Mendoza")] [InlineData("America/Indianapolis")] public static void ChangeLocalTimeZone(string id) { string originalTZ = Environment.GetEnvironmentVariable("TZ"); try { TimeZoneInfo.ClearCachedData(); Environment.SetEnvironmentVariable("TZ", id); TimeZoneInfo localtz = TimeZoneInfo.Local; TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(id); Assert.Equal(tz.StandardName, localtz.StandardName); Assert.Equal(tz.DisplayName, localtz.DisplayName); } finally { TimeZoneInfo.ClearCachedData(); Environment.SetEnvironmentVariable("TZ", originalTZ); } } [Fact] public static void FijiTimeZoneTest() { TimeZoneInfo fijiTZ = TimeZoneInfo.FindSystemTimeZoneById(s_strFiji); // "Fiji Standard Time" - "Pacific/Fiji" DateTime utcDT = new DateTime(2021, 1, 1, 14, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2021, 1, 31, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2022, 10, 1, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2022, 12, 31, 11, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2023, 1, 1, 10, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(13), fijiTZ.GetUtcOffset(utcDT)); Assert.True(fijiTZ.IsDaylightSavingTime(utcDT)); utcDT = new DateTime(2023, 2, 1, 0, 0, 0, DateTimeKind.Utc); Assert.Equal(TimeSpan.FromHours(12), fijiTZ.GetUtcOffset(utcDT)); Assert.False(fijiTZ.IsDaylightSavingTime(utcDT)); } [Fact] public static void AdjustmentRuleBaseUtcOffsetDeltaTest() { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 2, 0, 0), month: 3, day: 7); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFixedDateRule(timeOfDay: new DateTime(1, 1, 1, 1, 0, 0), month: 11, day: 7); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end, baseUtcOffsetDelta: new TimeSpan(1, 0, 0)); TimeZoneInfo customTimeZone = TimeZoneInfo.CreateCustomTimeZone( id: "Fake Time Zone", baseUtcOffset: new TimeSpan(0), displayName: "Fake Time Zone", standardDisplayName: "Standard Fake Time Zone", daylightDisplayName: "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule }); TimeZoneInfo.AdjustmentRule[] rules = customTimeZone.GetAdjustmentRules(); Assert.Equal(1, rules.Length); Assert.Equal(new TimeSpan(1, 0, 0), rules[0].BaseUtcOffsetDelta); // BaseUtcOffsetDelta should be counted to the returned offset during the standard time. Assert.Equal(new TimeSpan(1, 0, 0), customTimeZone.GetUtcOffset(new DateTime(2021, 1, 1, 2, 0, 0))); // BaseUtcOffsetDelta should be counted to the returned offset during the daylight time. Assert.Equal(new TimeSpan(2, 0, 0), customTimeZone.GetUtcOffset(new DateTime(2021, 3, 10, 2, 0, 0))); } [Fact] [ActiveIssue("https://github.com/dotnet/runtime/issues/64111", TestPlatforms.Linux)] public static void NoBackwardTimeZones() { ReadOnlyCollection<TimeZoneInfo> tzCollection = TimeZoneInfo.GetSystemTimeZones(); HashSet<String> tzDisplayNames = new HashSet<String>(); foreach (TimeZoneInfo timezone in tzCollection) { tzDisplayNames.Add(timezone.DisplayName); } Assert.Equal(tzCollection.Count, tzDisplayNames.Count); } private static bool IsEnglishUILanguage => CultureInfo.CurrentUICulture.Name.Length == 0 || CultureInfo.CurrentUICulture.TwoLetterISOLanguageName == "en"; private static bool IsEnglishUILanguageAndRemoteExecutorSupported => IsEnglishUILanguage && RemoteExecutor.IsSupported; private static void VerifyConvertException<TException>(DateTimeOffset inputTime, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvertException<TException>(DateTime inputTime, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvertException<TException>(DateTime inputTime, string sourceTimeZoneId, string destinationTimeZoneId) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId), TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId))); } private static void VerifyConvert(DateTimeOffset inputTime, string destinationTimeZoneId, DateTimeOffset expectedTime) { DateTimeOffset returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string destinationTimeZoneId, DateTime expectedTime) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); Assert.True(expectedTime.Kind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime.Kind, returnedTime.Kind, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string destinationTimeZoneId, DateTime expectedTime, DateTimeKind expectedKind) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime, returnedTime, inputTime, destinationTimeZoneId)); Assert.True(expectedKind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', TimeZone: {3}", expectedTime.Kind, returnedTime.Kind, inputTime, destinationTimeZoneId)); } private static void VerifyConvert(DateTime inputTime, string sourceTimeZoneId, string destinationTimeZoneId, DateTime expectedTime) { DateTime returnedTime = TimeZoneInfo.ConvertTime(inputTime, TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId), TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId)); Assert.True(returnedTime.Equals(expectedTime), string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', Source TimeZone: {3}, Dest. Time Zone: {4}", expectedTime, returnedTime, inputTime, sourceTimeZoneId, destinationTimeZoneId)); Assert.True(expectedTime.Kind == returnedTime.Kind, string.Format("Error: Expected value '{0}' but got '{1}', input value is '{2}', Source TimeZone: {3}, Dest. Time Zone: {4}", expectedTime.Kind, returnedTime.Kind, inputTime, sourceTimeZoneId, destinationTimeZoneId)); } private static void VerifyRoundTrip(DateTime dt1, string sourceTimeZoneId, string destinationTimeZoneId) { TimeZoneInfo sourceTzi = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId); TimeZoneInfo destTzi = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId); DateTime dt2 = TimeZoneInfo.ConvertTime(dt1, sourceTzi, destTzi); DateTime dt3 = TimeZoneInfo.ConvertTime(dt2, destTzi, sourceTzi); if (!destTzi.IsAmbiguousTime(dt2)) { // the ambiguous time can be mapped to 2 UTC times so it is not guaranteed to round trip Assert.True(dt1.Equals(dt3), string.Format("{0} failed to round trip using source '{1}' and '{2}' zones. wrong result {3}", dt1, sourceTimeZoneId, destinationTimeZoneId, dt3)); } if (sourceTimeZoneId == TimeZoneInfo.Utc.Id) { Assert.True(dt3.Kind == DateTimeKind.Utc, string.Format("failed to get the right DT Kind after round trip {0} using source TZ {1} and dest TZi {2}", dt1, sourceTimeZoneId, destinationTimeZoneId)); } } private static void VerifyAmbiguousOffsetsException<TException>(TimeZoneInfo tz, DateTime dt) where TException : Exception { Assert.Throws<TException>(() => tz.GetAmbiguousTimeOffsets(dt)); } private static void VerifyOffsets(TimeZoneInfo tz, DateTime dt, TimeSpan[] expectedOffsets) { TimeSpan[] ret = tz.GetAmbiguousTimeOffsets(dt); VerifyTimeSpanArray(ret, expectedOffsets, string.Format("Wrong offsets when used {0} with the zone {1}", dt, tz.Id)); } private static void VerifyTimeSpanArray(TimeSpan[] actual, TimeSpan[] expected, string errorMsg) { Assert.True(actual != null); Assert.True(expected != null); Assert.True(actual.Length == expected.Length); Array.Sort(expected); // TimeZoneInfo is expected to always return sorted TimeSpan arrays for (int i = 0; i < actual.Length; i++) { Assert.True(actual[i].Equals(expected[i]), errorMsg); } } private static void VerifyDST(TimeZoneInfo tz, DateTime dt, bool expectedDST) { bool ret = tz.IsDaylightSavingTime(dt); Assert.True(ret == expectedDST, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } private static void VerifyInv(TimeZoneInfo tz, DateTime dt, bool expectedInvalid) { bool ret = tz.IsInvalidTime(dt); Assert.True(expectedInvalid == ret, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } private static void VerifyAmbiguous(TimeZoneInfo tz, DateTime dt, bool expectedAmbiguous) { bool ret = tz.IsAmbiguousTime(dt); Assert.True(expectedAmbiguous == ret, string.Format("Test with the zone {0} and date {1} failed", tz.Id, dt)); } /// <summary> /// Gets the offset for the time zone for early times (close to DateTime.MinValue). /// </summary> /// <remarks> /// Windows uses the current daylight savings rules for early times. /// /// Other Unix distros use V2 tzfiles, which use local mean time (LMT), which is based on the solar time. /// The Pacific Standard Time LMT is UTC-07:53. For Sydney, LMT is UTC+10:04. /// </remarks> private static TimeSpan GetEarlyTimesOffset(string timeZoneId) { if (timeZoneId == s_strPacific) { if (s_isWindows) { return TimeSpan.FromHours(-8); } else { return new TimeSpan(7, 53, 0).Negate(); } } else if (timeZoneId == s_strSydney) { if (s_isWindows) { return TimeSpan.FromHours(11); } else { return new TimeSpan(10, 4, 0); } } else { throw new NotSupportedException(string.Format("The timeZoneId '{0}' is not supported by GetEarlyTimesOffset.", timeZoneId)); } } private static TimeZoneInfo TryGetSystemTimeZone(string id) { try { return TimeZoneInfo.FindSystemTimeZoneById(id); } catch (TimeZoneNotFoundException) { return null; } } private static TimeZoneInfo CreateCustomLondonTimeZone() { TimeZoneInfo.TransitionTime start = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 1, 0, 0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime end = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 2, 0, 0), 10, 5, DayOfWeek.Sunday); TimeZoneInfo.AdjustmentRule rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(DateTime.MinValue.Date, DateTime.MaxValue.Date, new TimeSpan(1, 0, 0), start, end); return TimeZoneInfo.CreateCustomTimeZone("Europe/London", new TimeSpan(0), "Europe/London", "British Standard Time", "British Summer Time", new TimeZoneInfo.AdjustmentRule[] { rule }); } private static void VerifyConvertToUtcException<TException>(DateTime dateTime, TimeZoneInfo sourceTimeZone) where TException : Exception { Assert.ThrowsAny<TException>(() => TimeZoneInfo.ConvertTimeToUtc(dateTime, sourceTimeZone)); } private static void VerifyCustomTimeZoneException<TException>(string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName = null, TimeZoneInfo.AdjustmentRule[] adjustmentRules = null) where TException : Exception { Assert.ThrowsAny<TException>(() => { if (daylightDisplayName == null && adjustmentRules == null) { TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName); } else { TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules); } }); } // This helper class is used to retrieve information about installed OS languages from Windows. // Its methods returns empty when run on non-Windows platforms. private static class WindowsUILanguageHelper { public static CultureInfo[] GetInstalledWin32CulturesWithUniqueLanguages() => GetInstalledWin32Cultures() .GroupBy(c => c.TwoLetterISOLanguageName) .Select(g => g.First()) .ToArray(); public static unsafe CultureInfo[] GetInstalledWin32Cultures() { if (!OperatingSystem.IsWindows()) { return new CultureInfo[0]; } var list = new List<CultureInfo>(); GCHandle handle = GCHandle.Alloc(list); try { EnumUILanguages( &EnumUiLanguagesCallback, MUI_ALL_INSTALLED_LANGUAGES | MUI_LANGUAGE_NAME, GCHandle.ToIntPtr(handle)); } finally { handle.Free(); } return list.ToArray(); } [UnmanagedCallersOnly] private static unsafe int EnumUiLanguagesCallback(char* lpUiLanguageString, IntPtr lParam) { // native string is null terminated var cultureName = new string(lpUiLanguageString); string tzResourceFilePath = Path.Join(Environment.SystemDirectory, cultureName, "tzres.dll.mui"); if (!File.Exists(tzResourceFilePath)) { // If Windows installed a UI language but did not include the time zone resources DLL for that language, // then skip this language as .NET will not be able to get the localized resources for that language. return 1; } try { var handle = GCHandle.FromIntPtr(lParam); var list = (List<CultureInfo>)handle.Target; list!.Add(CultureInfo.GetCultureInfo(cultureName)); return 1; } catch { return 0; } } private const uint MUI_LANGUAGE_NAME = 0x8; private const uint MUI_ALL_INSTALLED_LANGUAGES = 0x20; [DllImport("Kernel32.dll", CharSet = CharSet.Auto)] private static extern unsafe bool EnumUILanguages(delegate* unmanaged<char*, IntPtr, int> lpUILanguageEnumProc, uint dwFlags, IntPtr lParam); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Runtime/tests/System/Uri.CreateStringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Xunit; namespace System.Tests { public class UriCreateStringTests { private static readonly bool s_isWindowsSystem = PlatformDetection.IsWindows; public static readonly string s_longString = new string('a', 65520 + 1); public static IEnumerable<object[]> OriginalString_AbsoluteUri_ToString_TestData() { // Basic yield return new object[] { "http://host", "http://host/", "http://host/" }; yield return new object[] { @"http:/\host", "http://host/", "http://host/" }; yield return new object[] { @"http:\/host", "http://host/", "http://host/" }; yield return new object[] { @"http:\\host", "http://host/", "http://host/" }; yield return new object[] { @"http://host/path1\path2", "http://host/path1/path2", "http://host/path1/path2" }; yield return new object[] { "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment" }; yield return new object[] { "http://userinfo@host:80/path?query#fragment", "http://userinfo@host/path?query#fragment", "http://userinfo@host/path?query#fragment" }; yield return new object[] { "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment" }; // Escaped and non-ascii yield return new object[] { "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host", "http://userinfo%25%25%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%252g%252G@host/", "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host/" }; yield return new object[] { "http://\u1234\u2345/\u1234\u2345?\u1234\u2345#\u1234\u2345", "http://\u1234\u2345/%E1%88%B4%E2%8D%85?%E1%88%B4%E2%8D%85#%E1%88%B4%E2%8D%85", "http://\u1234\u2345/\u1234\u2345?\u1234\u2345#\u1234\u2345" }; // IP yield return new object[] { "http://192.168.0.1", "http://192.168.0.1/", "http://192.168.0.1/" }; yield return new object[] { "http://192.168.0.1/", "http://192.168.0.1/", "http://192.168.0.1/" }; yield return new object[] { "http://[::1]", "http://[::1]/", "http://[::1]/" }; yield return new object[] { "http://[::1]/", "http://[::1]/", "http://[::1]/" }; // Implicit UNC yield return new object[] { @"\\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"\/unchost", "file://unchost/", "file://unchost/" }; if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { @"/\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { "//unchost", "file://unchost/", "file://unchost/" }; } yield return new object[] { @"\\\/\/servername\sharename\path\filename", "file://servername/sharename/path/filename", "file://servername/sharename/path/filename" }; // Explicit UNC yield return new object[] { @"file://unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"file://\/unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"file:///\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { "file:////unchost", "file://unchost/", "file://unchost/" }; // Implicit windows drive yield return new object[] { "C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { "C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"C|\", "file:///C:/", "file:///C:/" }; // Explicit windows drive yield return new object[] { "file:///C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { "file://C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file:///C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file://C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { "file:///C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { "file://C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file:///C|\", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file://C|\", "file:///C:/", "file:///C:/" }; // Unix path if (!s_isWindowsSystem) { // Implicit File yield return new object[] { "/", "file:///", "file:///" }; yield return new object[] { "/path/filename", "file:///path/filename", "file:///path/filename" }; } // Compressed yield return new object[] { "http://host/path1/../path2", "http://host/path2", "http://host/path2" }; yield return new object[] { "http://host/../", "http://host/", "http://host/" }; } [Theory] [MemberData(nameof(OriginalString_AbsoluteUri_ToString_TestData))] public void OriginalString_AbsoluteUri_ToString(string uriString, string absoluteUri, string toString) { PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(uriString, uri.OriginalString); Assert.Equal(absoluteUri, uri.AbsoluteUri); Assert.Equal(toString, uri.ToString()); }); } public static IEnumerable<object[]> Scheme_Authority_TestData() { // HTTP (Generic Uri Syntax) yield return new object[] { " \t \r http://host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host:90", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://USERINFO@host", "http", "USERINFO", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host:90/", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90/", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host/", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90/", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host?query", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90?query", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90?query", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host:90?query", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host?query", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host#fragment", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90#fragment", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90#fragment", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host:90#fragment", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host#fragment", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://user:password@host", "http", "user:password", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://user:80@host:90", "http", "user:80", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host:0", "http", "", "host", UriHostNameType.Dns, 0, false, false }; yield return new object[] { "http://host:80", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:65535", "http", "", "host", UriHostNameType.Dns, 65535, false, false }; yield return new object[] { "http://part1-part2_part3-part4_part5/", "http", "", "part1-part2_part3-part4_part5", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "HTTP://USERINFO@HOST", "http", "USERINFO", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http.http2-http3+3http://host/", "http.http2-http3+3http", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"http:\\host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { @"http:/\host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { @"http:\/host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "https://host/", "https", "", "host", UriHostNameType.Dns, 443, true, false }; yield return new object[] { "http://_/", "http", "", "_", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://-/", "http", "", "-", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://_abc.efg1-hij2_345/path", "http", "", "_abc.efg1-hij2_345", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://_abc./path", "http", "", "_abc.", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://xn--abc", "http", "", "xn--abc", UriHostNameType.Dns, 80, true, false }; // IPv4 host - decimal yield return new object[] { "http://4294967295/", "http", "", "255.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://4294967296/", "http", "", "4294967296", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.1/", "http", "", "192.168.0.1", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://192.168.0.1.1/", "http", "", "192.168.0.1.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.256.0.1/", "http", "", "192.256.0.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.256.1/", "http", "", "192.168.256.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.256/", "http", "", "192.168.0.256", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://[email protected]:90/", "http", "userinfo", "192.168.0.1", UriHostNameType.IPv4, 90, false, false }; yield return new object[] { "http://192.16777216", "http", "", "192.16777216", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.65536", "http", "", "192.168.65536", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.256", "http", "", "192.168.0.256", UriHostNameType.Dns, 80, true, false }; // IPv4 host - hex yield return new object[] { "http://0x1a2B3c", "http", "", "0.26.43.60", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B3c", "http", "", "26.0.43.60", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B.0x3C4d", "http", "", "26.43.60.77", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B.0x3C.0x4d", "http", "", "26.43.60.77", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFFFFFFFF/", "http", "", "255.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFFFFFF/", "http", "", "0.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFF/", "http", "", "0.0.0.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0/", "http", "", "0.0.0.0", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x100000000/", "http", "", "0x100000000", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://0x/", "http", "", "0x", UriHostNameType.Dns, 80, true, false }; // IPv4 host - octet yield return new object[] { "http://192.0123.0.10", "http", "", "192.83.0.10", UriHostNameType.IPv4, 80, true, false }; // IPv4 host - implicit UNC if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"/\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; } yield return new object[] { @"\\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"\/192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv4 host - explicit UNC yield return new object[] { @"file://\\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "file:////192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"file:///\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; } yield return new object[] { @"file://\/192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv4 host - other yield return new object[] { "file://192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { "ftp://192.168.0.1", "ftp", "", "192.168.0.1", UriHostNameType.IPv4, 21, true, false }; yield return new object[] { "telnet://192.168.0.1", "telnet", "", "192.168.0.1", UriHostNameType.IPv4, 23, true, false }; yield return new object[] { "unknown://192.168.0.1", "unknown", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv6 host yield return new object[] { "http://[1111:1111:1111:1111:1111:1111:1111:1111]", "http", "", "[1111:1111:1111:1111:1111:1111:1111:1111]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[2001:0db8:0000:0000:0000:ff00:0042:8329]/", "http", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[2001:0db8:0000:0000:0000:ff00:0042:8329]:90/", "http", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 90, false, false }; yield return new object[] { "http://[1::]/", "http", "", "[1::]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[1::1]/", "http", "", "[1::1]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[::192.168.0.1]/", "http", "", "[::192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[::ffff:0:192.168.0.1]/", "http", "", "[::ffff:0:192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; // SIIT yield return new object[] { "http://[::ffff:1:192.168.0.1]/", "http", "", "[::ffff:1:c0a8:1]", UriHostNameType.IPv6, 80, true, false }; // SIIT (invalid) yield return new object[] { "http://[fe80::0000:5efe:192.168.0.1]/", "http", "", "[fe80::5efe:192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; // ISATAP yield return new object[] { "http://[1111:2222:3333::431/20]", "http", "", "[1111:2222:3333::431]", UriHostNameType.IPv6, 80, true, false }; // Prefix // IPv6 Host - implicit UNC if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"/\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; } yield return new object[] { @"\\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"\/[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file://\\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // IPv6 host - explicit UNC yield return new object[] { "file:////[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file:///\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file://\/[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // IPv6 Host - other yield return new object[] { "file://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { "ftp://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "ftp", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 21, true, false }; yield return new object[] { "telnet://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "telnet", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 23, true, false }; yield return new object[] { "unknown://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "unknown", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // File - empty path yield return new object[] { "file:///", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - host yield return new object[] { "file://path1/path2", "file", "", "path1", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:///path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - explicit with windows drive with empty path yield return new object[] { "file://C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - explicit with windows drive with path yield return new object[] { "file://C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - '/' + windows drive with empty path yield return new object[] { "file:///C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:///C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - '/' + windows drive with path yield return new object[] { "file:///C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:///C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - implicit with empty path yield return new object[] { "C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - implicit with path yield return new object[] { "C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - implicit with empty path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"/\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; } yield return new object[] { @"\\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\/unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - implicit with path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"/\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; } yield return new object[] { @"\\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\/unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\\\/\/servername\sharename\path\filename", "file", "", "servername", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with empty host and empty path yield return new object[] { @"file://\\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and non empty path yield return new object[] { @"file://\\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\//", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and query yield return new object[] { @"file://\\?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///?a", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///#a", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and fragment yield return new object[] { @"file://\\#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with non empty host and empty path yield return new object[] { @"file://\\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:////unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file:///\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file://\/unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with path yield return new object[] { @"file://\\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:////unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file:///\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file://\/unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with windows drive yield return new object[] { @"file://\\C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // Unix path if (!s_isWindowsSystem) { // Implicit with path yield return new object[] { "/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "/", "file", "", "", UriHostNameType.Basic, -1, true, true }; } // File - with host yield return new object[] { @"file://host/", "file", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.a./", "unknown", "", "h.a.", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.1./", "unknown", "", "h.1.", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.-/", "unknown", "", "h.-", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://h._", "unknown", "", "h._", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; // Mailto yield return new object[] { "mailto:", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; yield return new object[] { "mailto:[email protected]", "mailto", "someone", "example.com", UriHostNameType.Dns, 25, true, false }; yield return new object[] { "mailto://[email protected]", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; yield return new object[] { "mailto:/[email protected]", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; // FTP yield return new object[] { "ftp://host", "ftp", "", "host", UriHostNameType.Dns, 21, true, false }; yield return new object[] { "ftp://userinfo@host", "ftp", "userinfo", "host", UriHostNameType.Dns, 21, true, false }; yield return new object[] { "ftp://host?query#fragment", "ftp", "", "host", UriHostNameType.Dns, 21, true, false }; // Telnet yield return new object[] { "telnet://host/", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host:80", "telnet", "", "host", UriHostNameType.Dns, 80, false, false }; yield return new object[] { "telnet://userinfo@host/", "telnet", "userinfo", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://username:password@host/", "telnet", "username:password", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host?query#fragment", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host#fragment", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://localhost/", "telnet", "", "localhost", UriHostNameType.Dns, 23, true, true }; yield return new object[] { "telnet://loopback/", "telnet", "", "localhost", UriHostNameType.Dns, 23, true, true }; // Unknown yield return new object[] { "urn:namespace:segment1:segment2:segment3", "urn", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown:", "unknown", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown:path", "unknown", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown://host", "unknown", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://userinfo@host", "unknown", "userinfo", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://userinfo@host:80", "unknown", "userinfo", "host", UriHostNameType.Dns, 80, false, false }; yield return new object[] { "unknown://./", "unknown", "", ".", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://../", "unknown", "", "..", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://////", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "unknown:///C:/", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; // Loopback - HTTP yield return new object[] { "http://localhost/", "http", "", "localhost", UriHostNameType.Dns, 80, true, true }; yield return new object[] { "http://loopback/", "http", "", "localhost", UriHostNameType.Dns, 80, true, true }; // Loopback - implicit UNC with localhost if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"/\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; } yield return new object[] { @"\\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"\/localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - explicit UNC with localhost yield return new object[] { @"file://\\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file:///\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file://\/localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { "file:////localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - implicit UNC with loopback if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"/\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; } yield return new object[] { @"\\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"\/loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - explicit UNC with loopback yield return new object[] { @"file://\\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { "file:////loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file:///\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file://\/loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - IpV4 yield return new object[] { "http://127.0.0.1/", "http", "", "127.0.0.1", UriHostNameType.IPv4, 80, true, true }; // Loopback - IpV6 yield return new object[] { "http://[::1]/", "http", "", "[::1]", UriHostNameType.IPv6, 80, true, true }; yield return new object[] { "http://[::127.0.0.1]/", "http", "", "[::127.0.0.1]", UriHostNameType.IPv6, 80, true, true }; // Loopback - File yield return new object[] { "file://loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // RFC incompatability // We allow any non-unreserved, percent encoding or sub-delimeter in the userinfo yield return new object[] { "http://abc\u1234\u2345\u3456@host/", "http", "abc%E1%88%B4%E2%8D%85%E3%91%96", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234abc\u2345\u3456@host/", "http", "%E1%88%B4abc%E2%8D%85%E3%91%96", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234\u2345\u3456abc@host/", "http", "%E1%88%B4%E2%8D%85%E3%91%96abc", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo!~+-_*()[]:;&$=123PLACEHOLDER@host/", "http", "userinfo!~+-_*()[]:;&$=123PLACEHOLDER", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://%68%65%6C%6C%6F@host/", "http", "hello", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u00A3@host/", "http", "%C2%A3", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234@host/", "http", "%E1%88%B4", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host", "http", "userinfo%25%25%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%252g%252G", "host", UriHostNameType.Dns, 80, true, false }; } [Theory] [MemberData(nameof(Scheme_Authority_TestData))] public void Scheme_Authority_Basic(string uriString, string scheme, string userInfo, string host, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string idnHost = host; if (hostNameType == UriHostNameType.IPv6) { idnHost = host.Substring(1, host.Length - 2); } Scheme_Authority_IdnHost(uriString, scheme, userInfo, host, idnHost, idnHost, hostNameType, port, isDefaultPort, isLoopback); } public static IEnumerable<object[]> Scheme_Authority_IdnHost_TestData() { yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442", "xn--b1agh1afp", "\u043F\u0440\u0438\u0432\u0435\u0442", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442.ascii/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442.ascii", "xn--b1agh1afp.ascii", "\u043F\u0440\u0438\u0432\u0435\u0442.ascii", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://ascii.\u043F\u0440\u0438\u0432\u0435\u0442/", "http", "", "ascii.\u043F\u0440\u0438\u0432\u0435\u0442", "ascii.xn--b1agh1afp", "ascii.\u043F\u0440\u0438\u0432\u0435\u0442", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1", "xn--b1agh1afp.xn--ixaiab0ch2c", "\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://[1111:2222:3333::431%16]:50/", "http", "", "[1111:2222:3333::431]", "1111:2222:3333::431%16", "1111:2222:3333::431%16", UriHostNameType.IPv6, 50, false, false }; // Scope ID yield return new object[] { "http://[1111:2222:3333::431%16/20]", "http", "", "[1111:2222:3333::431]", "1111:2222:3333::431%16", "1111:2222:3333::431%16", UriHostNameType.IPv6, 80, true, false }; // Scope ID and prefix yield return new object[] { "http://\u1234\u2345\u3456/", "http", "", "\u1234\u2345\u3456", "xn--ryd258fr0m", "\u1234\u2345\u3456", UriHostNameType.Dns, 80, true, false }; } [Theory] [MemberData(nameof(Scheme_Authority_IdnHost_TestData))] public void Scheme_Authority_IdnHost(string uriString, string scheme, string userInfo, string host, string idnHost, string dnsSafeHost, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string authority = host; if (!isDefaultPort) { authority += ":" + port.ToString(); } PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(scheme, uri.Scheme); Assert.Equal(authority, uri.Authority); Assert.Equal(userInfo, uri.UserInfo); Assert.Equal(host, uri.Host); Assert.Equal(idnHost, uri.IdnHost); Assert.Equal(dnsSafeHost, uri.DnsSafeHost); Assert.Equal(hostNameType, uri.HostNameType); Assert.Equal(port, uri.Port); Assert.Equal(isDefaultPort, uri.IsDefaultPort); Assert.Equal(isLoopback, uri.IsLoopback); Assert.True(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); }); } public static IEnumerable<object[]> Path_Query_Fragment_TestData() { // Http yield return new object[] { "http://host", "/", "", "" }; yield return new object[] { "http://host?query", "/", "?query", "" }; yield return new object[] { "http://host#fragment", "/", "", "#fragment" }; yield return new object[] { "http://host?query#fragment", "/", "?query", "#fragment" }; yield return new object[] { "http://host/PATH?QUERY#FRAGMENT", "/PATH", "?QUERY", "#FRAGMENT" }; yield return new object[] { "http://host/", "/", "", "" }; yield return new object[] { "http://host/path1/path2", "/path1/path2", "", "" }; yield return new object[] { "http://host/path1/path2/", "/path1/path2/", "", "" }; yield return new object[] { "http://host/?query", "/", "?query", "" }; yield return new object[] { "http://host/path1/path2/?query", "/path1/path2/", "?query", "" }; yield return new object[] { "http://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "http://host/path1/path2/#fragment", "/path1/path2/", "", "#fragment" }; yield return new object[] { "http://host/?query#fragment", "/", "?query", "#fragment" }; yield return new object[] { "http://host/path1/path2/?query#fragment", "/path1/path2/", "?query", "#fragment" }; yield return new object[] { "http://host/?#fragment", "/", "?", "#fragment" }; yield return new object[] { "http://host/path1/path2/?#fragment", "/path1/path2/", "?", "#fragment" }; yield return new object[] { "http://host/?query#", "/", "?query", "#" }; yield return new object[] { "http://host/path1/path2/?query#", "/path1/path2/", "?query", "#" }; yield return new object[] { "http://host/?", "/", "?", "" }; yield return new object[] { "http://host/path1/path2/?", "/path1/path2/", "?", "" }; yield return new object[] { "http://host/#", "/", "", "#" }; yield return new object[] { "http://host/path1/path2/#", "/path1/path2/", "", "#" }; yield return new object[] { "http://host/?#", "/", "?", "#" }; yield return new object[] { "http://host/path1/path2/?#", "/path1/path2/", "?", "#" }; yield return new object[] { "http://host/?query1?query2#fragment1#fragment2?query3", "/", "?query1?query2", "#fragment1#fragment2?query3" }; yield return new object[] { "http://host/?query1=value&query2", "/", "?query1=value&query2", "" }; yield return new object[] { "http://host/?:@?/", "/", "?:@?/", "" }; yield return new object[] { @"http://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"http://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { "http://host/path \t \r \n \x0009 \x000A \x000D", "/path", "", "" }; yield return new object[] { "http://host/path?query \t \r \n \x0009 \x000A \x000D", "/path", "?query", "" }; yield return new object[] { "http://host/path#fragment \t \r \n \x0009 \x000A \x000D", "/path", "", "#fragment" }; yield return new object[] { "http://192.168.0.1:50/path1/page?query#fragment", "/path1/page", "?query", "#fragment" }; yield return new object[] { "http://192.168.0.1:80/\u1234\u2345/\u4567\u5678?query#fragment", "/%E1%88%B4%E2%8D%85/%E4%95%A7%E5%99%B8", "?query", "#fragment" }; yield return new object[] { "http://[1111:2222:3333::431]/path1/page?query#fragment", "/path1/page", "?query", "#fragment" }; yield return new object[] { "http://[1111:2222:3333::431]/\u1234\u2345/\u4567\u5678?query#fragment", "/%E1%88%B4%E2%8D%85/%E4%95%A7%E5%99%B8", "?query", "#fragment" }; // File with empty path yield return new object[] { "file:///", "/", "", "" }; yield return new object[] { @"file://\", "/", "", "" }; // File with windows drive yield return new object[] { "file://C:/", "C:/", "", "" }; yield return new object[] { "file://C|/", "C:/", "", "" }; yield return new object[] { @"file://C:\", "C:/", "", "" }; yield return new object[] { @"file://C|\", "C:/", "", "" }; // File with windows drive with path yield return new object[] { "file://C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "file://C|/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://C:\path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://C|\path1/path2", "C:/path1/path2", "", "" }; // File with windows drive with backlash in path yield return new object[] { @"file://C:/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C|/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C:\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C|\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; // File with windows drive ending with backslash yield return new object[] { @"file://C:/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C|/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C:\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C|\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; // File with host yield return new object[] { "file://path1/path2", "/path2", "", "" }; yield return new object[] { "file:///path1/path2", "/path1/path2", "", "" }; if (s_isWindowsSystem) { yield return new object[] { @"file:///path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:///path1\path2/path3%5Cpath4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://localhost/path1%5Cpath2", "/path1/path2", "", ""}; } else // Unix paths preserve backslash { yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", ""}; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file://localhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", ""}; } // Implicit file with empty path yield return new object[] { "C:/", "C:/", "", "" }; yield return new object[] { "C|/", "C:/", "", "" }; yield return new object[] { @"C:\", "C:/", "", "" }; yield return new object[] { @"C|\", "C:/", "", "" }; // Implicit file with path yield return new object[] { "C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "C|/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"C:\path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"C|\path1/path2", "C:/path1/path2", "", "" }; // Implicit file with backslash in path yield return new object[] { @"C:/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C|/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C:\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C|\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; // Implicit file ending with backlash yield return new object[] { @"C:/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C|/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C:\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C|\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; // Implicit UNC with empty path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { "//unchost", "/", "", "" }; yield return new object[] { @"/\unchost", "/", "", "" }; } yield return new object[] { @"\\unchost", "/", "", "" }; yield return new object[] { @"\/unchost", "/", "", "" }; // Implicit UNC with path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { "//unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"/\unchost/path1/path2", "/path1/path2", "", "" }; } yield return new object[] { @"\\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"\/unchost/path1/path2", "/path1/path2", "", "" }; // Implicit UNC with backslash in path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { @"//unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"/\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; } yield return new object[] { @"\\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"\/unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"\\\/\/servername\sharename\path\filename", "/sharename/path/filename", "", "" }; // Implicit UNC ending with backslash if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { @"//unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"/\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; } yield return new object[] { @"\\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"\/unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Explicit UNC with empty path yield return new object[] { @"file://\\unchost", "/", "", "" }; yield return new object[] { "file:////unchost", "/", "", "" }; yield return new object[] { @"file:///\unchost", "/", "", "" }; yield return new object[] { @"file://\/unchost", "/", "", "" }; // Explicit UNC with empty host and empty path yield return new object[] { @"file://\\", "//", "", "" }; yield return new object[] { "file:////", "//", "", "" }; yield return new object[] { @"file:///\", "//", "", "" }; yield return new object[] { @"file://\/", "//", "", "" }; // Explicit UNC with empty host and non-empty path yield return new object[] { @"file://\\/", "///", "", "" }; yield return new object[] { "file://///", "///", "", "" }; yield return new object[] { @"file:///\/", "///", "", "" }; yield return new object[] { @"file://\//", "///", "", "" }; // Explicit UNC with empty host and query yield return new object[] { @"file://\\?query", "//", "?query", "" }; yield return new object[] { "file:////?query", "//", "?query", "" }; yield return new object[] { @"file:///\?query", "//", "?query", "" }; yield return new object[] { @"file://\/?query", "//", "?query", "" }; yield return new object[] { "file://///?query", "///", "?query", "" }; // Explicit UNC with empty host and fragment yield return new object[] { @"file://\\#fragment", "//", "", "#fragment" }; yield return new object[] { "file:////#fragment", "//", "", "#fragment" }; yield return new object[] { @"file:///\#fragment", "//", "", "#fragment" }; yield return new object[] { @"file://\/#fragment", "//", "", "#fragment" }; yield return new object[] { "file://///#fragment", "///", "", "#fragment" }; // Explicit UNC with path yield return new object[] { @"file://\\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { "file:////unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"file:///\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"file://\/unchost/path1/path2", "/path1/path2", "", "" }; // Explicit UNC with path, query and fragment yield return new object[] { @"file://\\unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { "file:////unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { @"file:///\unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { @"file://\/unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; // Explicit UNC with a windows drive as host yield return new object[] { @"file://\\C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "file:////C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file:///\C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://\/C:/path1/path2", "C:/path1/path2", "", "" }; // Other yield return new object[] { "C|/path|path/path2", "C:/path%7Cpath/path2", "", "" }; yield return new object[] { "file://host/path?query#fragment", "/path", "?query", "#fragment" }; if (s_isWindowsSystem) { // Explicit UNC with backslash in path yield return new object[] { @"file://\\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; // Explicit UNC ending with backslash yield return new object[] { @"file://\\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; } else { // Implicit file with path yield return new object[] { "/", "/", "", "" }; yield return new object[] { "/path1/path2", "/path1/path2", "", "" }; // Implicit file with backslash in path yield return new object[] { @"/path1\path2/path3\path4", "/path1%5Cpath2/path3%5Cpath4", "", "" }; // Implicit file ending with backlash yield return new object[] { @"/path1\path2/path3\path4\", "/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; // Explicit UNC with backslash in path yield return new object[] { @"file://\\unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; // Explicit UNC ending with backslash yield return new object[] { @"file://\\unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; } // Mailto yield return new object[] { "mailto:[email protected]", "", "", "" }; yield return new object[] { "mailto:[email protected]?query#fragment", "", "?query", "#fragment" }; yield return new object[] { "mailto:/[email protected]", "/[email protected]", "", "" }; yield return new object[] { "mailto://[email protected]", "//[email protected]", "", "" }; yield return new object[] { "mailto://[email protected]?query#fragment", "//[email protected]", "?query", "#fragment" }; // Ftp yield return new object[] { "ftp://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "ftp://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "ftp://host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { "ftp://userinfo@host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { @"ftp://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"ftp://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Telnet yield return new object[] { "telnet://userinfo@host/", "/", "", "" }; yield return new object[] { "telnet://userinfo@host?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { "telnet://userinfo@host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { @"telnet://host/path1\path2/path3\path4", "/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"telnet://host/path1\path2/path3\path4\", "/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; // Unknown yield return new object[] { "urn:namespace:segment1:segment2:segment3", "namespace:segment1:segment2:segment3", "", "" }; yield return new object[] { "unknown:", "", "", "" }; yield return new object[] { "unknown:path", "path", "", "" }; yield return new object[] { "unknown:path1:path2", "path1:path2", "", "" }; yield return new object[] { "unknown:path?query#fragment", "path", "?query", "#fragment" }; yield return new object[] { "unknown:?query#fragment", "", "?query", "#fragment" }; yield return new object[] { "unknown://./", "/", "", "" }; yield return new object[] { "unknown://../", "/", "", "" }; yield return new object[] { "unknown://////", "////", "", "" }; yield return new object[] { "unknown:///C:/", "C:/", "", "" }; yield return new object[] { "unknown://host/path?query#fragment", "/path", "?query", "#fragment" }; yield return new object[] { @"unknown://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"unknown://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Does not need to be escaped yield return new object[] { "http://host/path!~+-_*()[]@:;&$=123PATH", "/path!~+-_*()[]@:;&$=123PATH", "", "" }; yield return new object[] { "http://host/?query!~+-_*()[]@:;&$=123QUERY", "/", "?query!~+-_*()[]@:;&$=123QUERY", "" }; yield return new object[] { "http://host/#fragment!~+-_*()[]@:;&$=123FRAGMENT", "/", "", "#fragment!~+-_*()[]@:;&$=123FRAGMENT" }; // Unescaped yield return new object[] { "http://host/\u1234\u2345\u3456", "/%E1%88%B4%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/abc\u1234\u2345\u3456", "/abc%E1%88%B4%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/\u1234abc\u2345\u3456", "/%E1%88%B4abc%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/\u1234\u2345\u3456abc", "/%E1%88%B4%E2%8D%85%E3%91%96abc", "", "" }; yield return new object[] { "http://host/?abc\u1234\u2345\u3456", "/", "?abc%E1%88%B4%E2%8D%85%E3%91%96", "" }; yield return new object[] { "http://host/?\u1234abc\u2345\u3456", "/", "?%E1%88%B4abc%E2%8D%85%E3%91%96", "" }; yield return new object[] { "http://host/?\u1234\u2345\u3456abc", "/", "?%E1%88%B4%E2%8D%85%E3%91%96abc", "" }; yield return new object[] { "http://host/#abc\u1234\u2345\u3456", "/", "", "#abc%E1%88%B4%E2%8D%85%E3%91%96" }; yield return new object[] { "http://host/#\u1234abc\u2345\u3456", "/", "", "#%E1%88%B4abc%E2%8D%85%E3%91%96" }; yield return new object[] { "http://host/#\u1234\u2345\u3456abc", "/", "", "#%E1%88%B4%E2%8D%85%E3%91%96abc" }; yield return new object[] { "http://host/\0?\0#\0", "/%00", "?%00", "#%00" }; // Unnecessarily escaped (upper case hex letters) yield return new object[] { "http://host/%68%65%6C%6C%6F", "/hello", "", "" }; yield return new object[] { "http://host/?%68%65%6C%6C%6F", "/", "?hello", "" }; yield return new object[] { "http://host/#%68%65%6C%6C%6F", "/", "", "#hello" }; // Unnecessarily escaped (lower case hex letters) yield return new object[] { "http://host/%68%65%6c%6c%6f", "/hello", "", "" }; yield return new object[] { "http://host/?%68%65%6c%6c%6f", "/", "?hello", "" }; yield return new object[] { "http://host/#%68%65%6c%6c%6f", "/", "", "#hello" }; // Encoded generic delimeters should not be expanded yield return new object[] { "http://host/%3A?%3A#%3A", "/%3A", "?%3A", "#%3A" }; yield return new object[] { "http://host/%2F?%2F#%2F", "/%2F", "?%2F", "#%2F" }; yield return new object[] { "http://host/%3F?%3F#%3F", "/%3F", "?%3F", "#%3F" }; yield return new object[] { "http://host/%23?%23#%23", "/%23", "?%23", "#%23" }; yield return new object[] { "http://host/%5B?%5B#%5B", "/%5B", "?%5B", "#%5B" }; yield return new object[] { "http://host/%5D?%5D#%5D", "/%5D", "?%5D", "#%5D" }; yield return new object[] { "http://host/%40?%40#%40", "/%40", "?%40", "#%40" }; // Encoded sub delimeters should not be expanded yield return new object[] { "http://host/%21?%21#%21", "/%21", "?%21", "#%21" }; yield return new object[] { "http://host/%24?%24#%24", "/%24", "?%24", "#%24" }; yield return new object[] { "http://host/%26?%26#%26", "/%26", "?%26", "#%26" }; yield return new object[] { "http://host/%5C?%5C#%5C", "/%5C", "?%5C", "#%5C" }; yield return new object[] { "http://host/%28?%28#%28", "/%28", "?%28", "#%28" }; yield return new object[] { "http://host/%29?%29#%29", "/%29", "?%29", "#%29" }; yield return new object[] { "http://host/%2A?%2A#%2A", "/%2A", "?%2A", "#%2A" }; yield return new object[] { "http://host/%2B?%2B#%2B", "/%2B", "?%2B", "#%2B" }; yield return new object[] { "http://host/%2C?%2C#%2C", "/%2C", "?%2C", "#%2C" }; yield return new object[] { "http://host/%3B?%3B#%3B", "/%3B", "?%3B", "#%3B" }; yield return new object[] { "http://host/%3D?%3D#%3D", "/%3D", "?%3D", "#%3D" }; // Invalid unicode yield return new object[] { "http://host/%?%#%", "/%25", "?%25", "#%25" }; yield return new object[] { "http://host/%3?%3#%3", "/%253", "?%253", "#%253" }; yield return new object[] { "http://host/%G?%G#%G", "/%25G", "?%25G", "#%25G" }; yield return new object[] { "http://host/%g?%g#%g", "/%25g", "?%25g", "#%25g" }; yield return new object[] { "http://host/%G3?%G3#%G3", "/%25G3", "?%25G3", "#%25G3" }; yield return new object[] { "http://host/%g3?%g3#%g3", "/%25g3", "?%25g3", "#%25g3" }; yield return new object[] { "http://host/%3G?%3G#%3G", "/%253G", "?%253G", "#%253G" }; yield return new object[] { "http://host/%3g?%3g#%3g", "/%253g", "?%253g", "#%253g" }; // Compressed yield return new object[] { "http://host/%2E%2E/%2E%2E", "/", "", "" }; yield return new object[] { "http://host/path1/../path2", "/path2", "", "" }; yield return new object[] { "http://host/../", "/", "", "" }; yield return new object[] { "http://host/path1/./path2", "/path1/path2", "", "" }; yield return new object[] { "http://host/./", "/", "", "" }; yield return new object[] { "http://host/..", "/", "", "" }; yield return new object[] { "http://host/.../", "/.../", "", "" }; yield return new object[] { "http://host/x../", "/x../", "", "" }; yield return new object[] { "http://host/..x/", "/..x/", "", "" }; yield return new object[] { "http://host/path//", "/path//", "", "" }; yield return new object[] { "file://C:/abc/def/../ghi", "C:/abc/ghi", "", "" }; } [Theory] [MemberData(nameof(Path_Query_Fragment_TestData))] public void Path_Query_Fragment(string uriString, string path, string query, string fragment) { IEnumerable<string> segments = null; string localPath = null; string segmentsPath = null; PerformAction(uriString, UriKind.Absolute, uri => { if (segments == null) { localPath = Uri.UnescapeDataString(path); segmentsPath = path; if (uri.IsUnc) { localPath = @"\\" + uri.Host + path; localPath = localPath.Replace('/', '\\'); // Unescape '\\' localPath = localPath.Replace("%5C", "\\"); if (path == "/") { localPath = localPath.Substring(0, localPath.Length - 1); } } else if (path.Length > 2 && path[1] == ':' && path[2] == '/') { segmentsPath = '/' + segmentsPath; localPath = localPath.Replace('/', '\\'); } segments = Regex.Split(segmentsPath, @"(?<=/)").TakeWhile(s => s.Length != 0); } Assert.Equal(path, uri.AbsolutePath); Assert.Equal(localPath, uri.LocalPath); Assert.Equal(path + query, uri.PathAndQuery); Assert.Equal(segments, uri.Segments); Assert.Equal(query, uri.Query); Assert.Equal(fragment, uri.Fragment); Assert.True(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); }); } public static IEnumerable<object[]> IsFile_IsUnc_TestData() { // Explicit file with windows drive with path yield return new object[] { "file://C:/path", true, false }; yield return new object[] { "file://C|/path", true, false }; yield return new object[] { @"file://C:\path", true, false }; yield return new object[] { @"file://C|\path", true, false }; yield return new object[] { "file:///C:/path", true, false }; yield return new object[] { "file:///C|/path", true, false }; yield return new object[] { @"file:///C:\path", true, false }; yield return new object[] { @"file:///C|\path", true, false }; // File with empty path yield return new object[] { "file:///", true, false }; yield return new object[] { @"file://\", true, false }; // File with host yield return new object[] { "file://host/path2", true, true }; // Implicit file with windows drive with empty path yield return new object[] { "C:/", true, false }; yield return new object[] { "C|/", true, false }; yield return new object[] { @"C:\", true, false }; yield return new object[] { @"C|/", true, false }; // Implicit file with windows drive with path yield return new object[] { "C:/path", true, false }; yield return new object[] { "C|/path", true, false }; yield return new object[] { @"C:\path", true, false }; yield return new object[] { @"C|\path", true, false }; yield return new object[] { @"\\unchost", true, true }; // Implicit UNC with empty path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost", true, true }; yield return new object[] { @"/\unchost", true, true }; } yield return new object[] { @"\\unchost", true, true }; yield return new object[] { @"\/unchost", true, true }; // Implicit UNC with path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost/path1/path2", true, true }; yield return new object[] { @"/\unchost/path1/path2", true, true }; } yield return new object[] { @"\\unchost/path1/path2", true, true }; yield return new object[] { @"\/unchost/path1/path2", true, true }; // Explicit UNC with empty path yield return new object[] { @"file://\\unchost", true, true }; yield return new object[] { "file:////unchost", true, true }; yield return new object[] { @"file:///\unchost", true, true }; yield return new object[] { @"file://\/unchost", true, true }; // Explicit UNC with empty host and empty path yield return new object[] { @"file://\\", true, false }; yield return new object[] { "file:////", true, false }; yield return new object[] { @"file:///\", true, false }; yield return new object[] { @"file://\/", true, false }; // Explicit UNC with empty host and non empty path yield return new object[] { @"file://\\/", true, false }; yield return new object[] { "file://///", true, false }; yield return new object[] { @"file:///\/", true, false }; yield return new object[] { @"file://\//", true, false }; // Explicit UNC with query yield return new object[] { @"file://\\?query", true, false }; yield return new object[] { "file:////?query", true, false }; yield return new object[] { @"file:///\?query", true, false }; yield return new object[] { @"file://\/?query", true, false }; // Explicit UNC with fragment yield return new object[] { @"file://\\#fragment", true, false }; yield return new object[] { "file:////#fragment", true, false }; yield return new object[] { @"file:///\#fragment", true, false }; yield return new object[] { @"file://\/#fragment", true, false }; // Explicit UNC with path yield return new object[] { @"file://\\unchost/path1/path2", true, true }; yield return new object[] { "file:////unchost/path1/path2", true, true }; yield return new object[] { @"file:///\unchost/path1/path2", true, true }; yield return new object[] { @"file://\/unchost/path1/path2", true, true }; // Explicit UNC with windows drive yield return new object[] { @"file://\\C:/", true, false }; yield return new object[] { "file:////C:/", true, false }; yield return new object[] { @"file:///\C:/", true, false }; yield return new object[] { @"file://\/C:/", true, false }; yield return new object[] { @"file://\\C|/", true, false }; yield return new object[] { "file:////C|/", true, false }; yield return new object[] { @"file:///\C|/", true, false }; yield return new object[] { @"file://\/C|/", true, false }; yield return new object[] { @"file://\\C:\", true, false }; yield return new object[] { @"file:////C:\", true, false }; yield return new object[] { @"file:///\C:\", true, false }; yield return new object[] { @"file://\/C:\", true, false }; yield return new object[] { @"file://\\C|\", true, false }; yield return new object[] { @"file:////C|\", true, false }; yield return new object[] { @"file:///\C|\", true, false }; yield return new object[] { @"file://\/C|\", true, false }; // Not a file yield return new object[] { "http://host/", false, false }; yield return new object[] { "https://host/", false, false }; yield return new object[] { "mailto:[email protected]", false, false }; yield return new object[] { "ftp://host/", false, false }; yield return new object[] { "telnet://host/", false, false }; yield return new object[] { "unknown:", false, false }; yield return new object[] { "unknown:path", false, false }; yield return new object[] { "unknown://host/", false, false }; } [Theory] [MemberData(nameof(IsFile_IsUnc_TestData))] public void IsFile_IsUnc(string uriString, bool isFile, bool isUnc) { PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(isFile, uri.IsFile); Assert.Equal(isUnc, uri.IsUnc); }); } public static IEnumerable<object[]> Relative_TestData() { yield return new object[] { "path1/page.htm?query1=value#fragment", true }; yield return new object[] { "/", true }; yield return new object[] { "?query", true }; yield return new object[] { "#fragment", true }; yield return new object[] { @"C:\abc", false }; yield return new object[] { @"C|\abc", false }; yield return new object[] { @"\\servername\sharename\path\filename", false }; } [Theory] [MemberData(nameof(Relative_TestData))] public void Relative(string uriString, bool relativeOrAbsolute) { PerformAction(uriString, UriKind.Relative, uri => { VerifyRelativeUri(uri, uriString, uriString); }); PerformAction(uriString, UriKind.RelativeOrAbsolute, uri => { if (relativeOrAbsolute) { VerifyRelativeUri(uri, uriString, uriString); } else { Assert.True(uri.IsAbsoluteUri); } }); } [Fact] public void Create_String_Null_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("uriString", () => new Uri(null)); AssertExtensions.Throws<ArgumentNullException>("uriString", () => new Uri(null, UriKind.Absolute)); Uri uri; Assert.False(Uri.TryCreate(null, UriKind.Absolute, out uri)); Assert.Null(uri); } [Fact] public void Create_String_InvalidUriKind_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new Uri("http://host", UriKind.RelativeOrAbsolute - 1)); AssertExtensions.Throws<ArgumentException>(null, () => new Uri("http://host", UriKind.Relative + 1)); Uri uri = null; AssertExtensions.Throws<ArgumentException>(null, () => Uri.TryCreate("http://host", UriKind.RelativeOrAbsolute - 1, out uri)); Assert.Null(uri); AssertExtensions.Throws<ArgumentException>(null, () => Uri.TryCreate("http://host", UriKind.Relative + 1, out uri)); Assert.Null(uri); } public static IEnumerable<object[]> Create_String_Invalid_TestData() { yield return new object[] { s_longString, UriKind.Absolute }; // UriString is longer than 66520 characters // Invalid scheme yield return new object[] { "", UriKind.Absolute }; yield return new object[] { " \t \r \n \x0009 \x000A \x000D ", UriKind.Absolute }; yield return new object[] { "http", UriKind.Absolute }; yield return new object[] { ":", UriKind.Absolute }; yield return new object[] { "1http://host/", UriKind.Absolute }; yield return new object[] { "http/://host/", UriKind.Absolute }; yield return new object[] { "\u1234http://host/", UriKind.Absolute }; yield return new object[] { "ht\u1234tp://host/", UriKind.Absolute }; yield return new object[] { "ht%45tp://host/", UriKind.Absolute }; yield return new object[] { "\x00a0 \x000B \x000C \x0085http", UriKind.Absolute }; yield return new object[] { "~", UriKind.Absolute }; yield return new object[] { "http://", UriKind.Absolute }; yield return new object[] { "http:/", UriKind.Absolute }; yield return new object[] { "domain.com", UriKind.Absolute }; yield return new object[] { "\u1234http://domain.com", UriKind.Absolute }; yield return new object[] { "http\u1234://domain.com", UriKind.Absolute }; yield return new object[] { "http~://domain.com", UriKind.Absolute }; yield return new object[] { "http#://domain.com", UriKind.Absolute }; yield return new object[] { new string('a', 1025) + "://domain.com", UriKind.Absolute }; // Scheme is longer than 1024 characters // Invalid userinfo yield return new object[] { @"http://use\rinfo@host", UriKind.Absolute }; // Invalid characters in host yield return new object[] { "http://ho!st/", UriKind.Absolute }; yield return new object[] { "http://ho&st/", UriKind.Absolute }; yield return new object[] { "http://ho$st/", UriKind.Absolute }; yield return new object[] { "http://ho(st/", UriKind.Absolute }; yield return new object[] { "http://ho)st/", UriKind.Absolute }; yield return new object[] { "http://ho*st", UriKind.Absolute }; yield return new object[] { "http://ho+st", UriKind.Absolute }; yield return new object[] { "http://ho,st", UriKind.Absolute }; yield return new object[] { "http://ho;st/", UriKind.Absolute }; yield return new object[] { "http://ho=st", UriKind.Absolute }; yield return new object[] { "http://ho~st/", UriKind.Absolute }; // Empty host yield return new object[] { "http://", UriKind.Absolute }; yield return new object[] { "http:/", UriKind.Absolute }; yield return new object[] { "http:/abc", UriKind.Absolute }; yield return new object[] { "http://@", UriKind.Absolute }; yield return new object[] { "http://userinfo@", UriKind.Absolute }; yield return new object[] { "http://:", UriKind.Absolute }; yield return new object[] { "http://:80", UriKind.Absolute }; yield return new object[] { "http://@:", UriKind.Absolute }; yield return new object[] { "http://@:80", UriKind.Absolute }; yield return new object[] { "http://userinfo@:80", UriKind.Absolute }; yield return new object[] { "http:///", UriKind.Absolute }; yield return new object[] { "http://@/", UriKind.Absolute }; yield return new object[] { "http://userinfo@/", UriKind.Absolute }; yield return new object[] { "http://:/", UriKind.Absolute }; yield return new object[] { "http://:80/", UriKind.Absolute }; yield return new object[] { "http://@:/", UriKind.Absolute }; yield return new object[] { "http://@:80/", UriKind.Absolute }; yield return new object[] { "http://userinfo@:80/", UriKind.Absolute }; yield return new object[] { "http://?query", UriKind.Absolute }; yield return new object[] { "http://:?query", UriKind.Absolute }; yield return new object[] { "http://@:?query", UriKind.Absolute }; yield return new object[] { "http://userinfo@:?query", UriKind.Absolute }; yield return new object[] { "http://#fragment", UriKind.Absolute }; yield return new object[] { "http://:#fragment", UriKind.Absolute }; yield return new object[] { "http://@:#fragment", UriKind.Absolute }; yield return new object[] { "http://userinfo@:#fragment", UriKind.Absolute }; yield return new object[] { @"http://host\", UriKind.Absolute }; yield return new object[] { @"http://userinfo@host@host/", UriKind.Absolute }; yield return new object[] { @"http://userinfo\@host/", UriKind.Absolute }; yield return new object[] { "http://ho\0st/", UriKind.Absolute }; yield return new object[] { "http://ho[st/", UriKind.Absolute }; yield return new object[] { "http://ho]st/", UriKind.Absolute }; yield return new object[] { @"http://ho\st/", UriKind.Absolute }; yield return new object[] { "http://ho{st/", UriKind.Absolute }; yield return new object[] { "http://ho}st/", UriKind.Absolute }; // Invalid host yield return new object[] { @"http://domain\", UriKind.Absolute }; yield return new object[] { @"unknownscheme://domain\", UriKind.Absolute }; yield return new object[] { "unknown://h..9", UriKind.Absolute }; yield return new object[] { "unknown://h..-", UriKind.Absolute }; yield return new object[] { "unknown://h..", UriKind.Absolute }; yield return new object[] { "unknown://h.a;./", UriKind.Absolute }; // Invalid file yield return new object[] { "file:/a", UriKind.Absolute }; yield return new object[] { "C:adomain.com", UriKind.Absolute }; yield return new object[] { "C|adomain.com", UriKind.Absolute }; yield return new object[] { "!://domain.com", UriKind.Absolute }; yield return new object[] { "!|//domain.com", UriKind.Absolute }; yield return new object[] { "\u1234://domain.com", UriKind.Absolute }; yield return new object[] { "\u1234|//domain.com", UriKind.Absolute }; yield return new object[] { ".://domain.com", UriKind.Absolute }; // File is not rooted yield return new object[] { "file://a:a", UriKind.Absolute }; yield return new object[] { "file://a:", UriKind.Absolute }; // Implicit UNC has an empty host yield return new object[] { @"\\", UriKind.Absolute }; yield return new object[] { @"\\?query", UriKind.Absolute }; yield return new object[] { @"\\#fragment", UriKind.Absolute }; yield return new object[] { "\\\\?query\u1234", UriKind.Absolute }; yield return new object[] { "\\\\#fragment\u1234", UriKind.Absolute }; // Implicit UNC has port yield return new object[] { @"\\unchost:90", UriKind.Absolute }; yield return new object[] { @"\\unchost:90/path1/path2", UriKind.Absolute }; // Explicit UNC has port yield return new object[] { @"file://\\unchost:90", UriKind.Absolute }; yield return new object[] { @"file://\\unchost:90/path1/path2", UriKind.Absolute }; // File with host has port yield return new object[] { @"file://host:90", UriKind.Absolute }; yield return new object[] { @"file://host:90/path1/path2", UriKind.Absolute }; // Implicit UNC has userinfo yield return new object[] { @"\\userinfo@host", UriKind.Absolute }; yield return new object[] { @"\\userinfo@host/path1/path2", UriKind.Absolute }; // Explicit UNC has userinfo yield return new object[] { @"file://\\userinfo@host", UriKind.Absolute }; yield return new object[] { @"file://\\userinfo@host/path1/path2", UriKind.Absolute }; // File with host has userinfo yield return new object[] { @"file://userinfo@host", UriKind.Absolute }; yield return new object[] { @"file://userinfo@host/path1/path2", UriKind.Absolute }; // Implicit UNC with windows drive yield return new object[] { @"\\C:/", UriKind.Absolute }; yield return new object[] { @"\\C|/", UriKind.Absolute }; if (s_isWindowsSystem) // Valid Unix path { yield return new object[] { "//C:/", UriKind.Absolute }; yield return new object[] { "//C|/", UriKind.Absolute }; } yield return new object[] { @"\/C:/", UriKind.Absolute }; yield return new object[] { @"\/C|/", UriKind.Absolute }; if (s_isWindowsSystem) // Valid Unix path { yield return new object[] { @"/\C:/", UriKind.Absolute }; yield return new object[] { @"/\C|/", UriKind.Absolute }; } // Explicit UNC with invalid windows drive yield return new object[] { @"file://\\1:/", UriKind.Absolute }; yield return new object[] { @"file://\\ab:/", UriKind.Absolute }; // Unc host is invalid yield return new object[] { @"\\.", UriKind.Absolute }; yield return new object[] { @"\\server..", UriKind.Absolute }; // Domain name host is invalid yield return new object[] { "http://./", UriKind.Absolute }; yield return new object[] { "http://_a..a/", UriKind.Absolute }; yield return new object[] { "http://a..a/", UriKind.Absolute }; yield return new object[] { "unknownscheme://..a/", UriKind.Absolute }; yield return new object[] { "http://host" + (char)0, UriKind.Absolute }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442" + (char)0, UriKind.Absolute }; yield return new object[] { "http://%", UriKind.Absolute }; yield return new object[] { "http://@", UriKind.Absolute }; // Invalid IPv4 address yield return new object[] { "http://192..0.1", UriKind.Absolute }; yield return new object[] { "http://192.0.0.1;", UriKind.Absolute }; // Invalid IPv6 address yield return new object[] { "http://[", UriKind.Absolute }; yield return new object[] { "http://[?", UriKind.Absolute }; yield return new object[] { "http://[#", UriKind.Absolute }; yield return new object[] { "http://[/", UriKind.Absolute }; yield return new object[] { @"http://[\", UriKind.Absolute }; yield return new object[] { "http://[]", UriKind.Absolute }; yield return new object[] { "http://[a]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431%", UriKind.Absolute }; yield return new object[] { "http://[::1::1]", UriKind.Absolute }; yield return new object[] { "http://[11111:2222:3333::431]", UriKind.Absolute }; yield return new object[] { "http://[/12]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431/12/12]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431%16/]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431/123]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0.9/192.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0.9%192.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[001.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[a92.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0]", UriKind.Absolute }; yield return new object[] { "http://[256.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[01.168.0.9]", UriKind.Absolute }; // Invalid port yield return new object[] { "http://domain:a", UriKind.Absolute }; yield return new object[] { "http://domain:-1", UriKind.Absolute }; yield return new object[] { "http://domain:65536", UriKind.Absolute }; yield return new object[] { "http://host:2147483648", UriKind.Absolute }; yield return new object[] { "http://host:80:80", UriKind.Absolute }; yield return new object[] { "uri://domain:a", UriKind.Absolute }; yield return new object[] { "uri://domain:65536", UriKind.Absolute }; yield return new object[] { "uri://a:a", UriKind.Absolute }; yield return new object[] { "uri://a:65536", UriKind.Absolute }; yield return new object[] { "uri://a:2147483648", UriKind.Absolute }; yield return new object[] { "uri://a:80:80", UriKind.Absolute }; if (PlatformDetection.IsNotInvariantGlobalization) { // Invalid unicode yield return new object[] { "http://\uD800", UriKind.Absolute }; yield return new object[] { "http://\uDC00", UriKind.Absolute }; } } [Theory] [MemberData(nameof(Create_String_Invalid_TestData))] public void Create_String_Invalid(string uriString, UriKind uriKind) { if (uriKind == UriKind.Absolute) { Assert.Throws<UriFormatException>(() => new Uri(uriString)); } Assert.Throws<UriFormatException>(() => new Uri(uriString, uriKind)); Uri uri; Assert.False(Uri.TryCreate(uriString, uriKind, out uri)); Assert.Null(uri); } private static void PerformAction(string uriString, UriKind uriKind, Action<Uri> action) { if (uriKind == UriKind.Absolute) { Uri uri = new Uri(uriString); action(uri); } Uri uri1 = new Uri(uriString, uriKind); action(uri1); Uri result = null; Assert.True(Uri.TryCreate(uriString, uriKind, out result)); action(result); } internal static void VerifyRelativeUri(Uri uri, string originalString, string toString) { Assert.Equal(originalString, uri.OriginalString); Assert.Equal(toString, uri.ToString()); Assert.False(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); Assert.Throws<InvalidOperationException>(() => uri.AbsoluteUri); Assert.Throws<InvalidOperationException>(() => uri.Scheme); Assert.Throws<InvalidOperationException>(() => uri.HostNameType); Assert.Throws<InvalidOperationException>(() => uri.Authority); Assert.Throws<InvalidOperationException>(() => uri.Host); Assert.Throws<InvalidOperationException>(() => uri.IdnHost); Assert.Throws<InvalidOperationException>(() => uri.DnsSafeHost); Assert.Throws<InvalidOperationException>(() => uri.Port); Assert.Throws<InvalidOperationException>(() => uri.AbsolutePath); Assert.Throws<InvalidOperationException>(() => uri.LocalPath); Assert.Throws<InvalidOperationException>(() => uri.PathAndQuery); Assert.Throws<InvalidOperationException>(() => uri.Segments); Assert.Throws<InvalidOperationException>(() => uri.Fragment); Assert.Throws<InvalidOperationException>(() => uri.Query); Assert.Throws<InvalidOperationException>(() => uri.UserInfo); Assert.Throws<InvalidOperationException>(() => uri.IsDefaultPort); Assert.Throws<InvalidOperationException>(() => uri.IsFile); Assert.Throws<InvalidOperationException>(() => uri.IsLoopback); Assert.Throws<InvalidOperationException>(() => uri.IsUnc); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Xunit; namespace System.Tests { public class UriCreateStringTests { private static readonly bool s_isWindowsSystem = PlatformDetection.IsWindows; public static readonly string s_longString = new string('a', 65520 + 1); public static IEnumerable<object[]> OriginalString_AbsoluteUri_ToString_TestData() { // Basic yield return new object[] { "http://host", "http://host/", "http://host/" }; yield return new object[] { @"http:/\host", "http://host/", "http://host/" }; yield return new object[] { @"http:\/host", "http://host/", "http://host/" }; yield return new object[] { @"http:\\host", "http://host/", "http://host/" }; yield return new object[] { @"http://host/path1\path2", "http://host/path1/path2", "http://host/path1/path2" }; yield return new object[] { "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment" }; yield return new object[] { "http://userinfo@host:80/path?query#fragment", "http://userinfo@host/path?query#fragment", "http://userinfo@host/path?query#fragment" }; yield return new object[] { "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment", "http://userinfo@host:90/path?query#fragment" }; // Escaped and non-ascii yield return new object[] { "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host", "http://userinfo%25%25%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%252g%252G@host/", "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host/" }; yield return new object[] { "http://\u1234\u2345/\u1234\u2345?\u1234\u2345#\u1234\u2345", "http://\u1234\u2345/%E1%88%B4%E2%8D%85?%E1%88%B4%E2%8D%85#%E1%88%B4%E2%8D%85", "http://\u1234\u2345/\u1234\u2345?\u1234\u2345#\u1234\u2345" }; // IP yield return new object[] { "http://192.168.0.1", "http://192.168.0.1/", "http://192.168.0.1/" }; yield return new object[] { "http://192.168.0.1/", "http://192.168.0.1/", "http://192.168.0.1/" }; yield return new object[] { "http://[::1]", "http://[::1]/", "http://[::1]/" }; yield return new object[] { "http://[::1]/", "http://[::1]/", "http://[::1]/" }; // Implicit UNC yield return new object[] { @"\\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"\/unchost", "file://unchost/", "file://unchost/" }; if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { @"/\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { "//unchost", "file://unchost/", "file://unchost/" }; } yield return new object[] { @"\\\/\/servername\sharename\path\filename", "file://servername/sharename/path/filename", "file://servername/sharename/path/filename" }; // Explicit UNC yield return new object[] { @"file://unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"file://\/unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { @"file:///\unchost", "file://unchost/", "file://unchost/" }; yield return new object[] { "file:////unchost", "file://unchost/", "file://unchost/" }; // Implicit windows drive yield return new object[] { "C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { "C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"C|\", "file:///C:/", "file:///C:/" }; // Explicit windows drive yield return new object[] { "file:///C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { "file://C:/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file:///C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file://C:\", "file:///C:/", "file:///C:/" }; yield return new object[] { "file:///C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { "file://C|/", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file:///C|\", "file:///C:/", "file:///C:/" }; yield return new object[] { @"file://C|\", "file:///C:/", "file:///C:/" }; // Unix path if (!s_isWindowsSystem) { // Implicit File yield return new object[] { "/", "file:///", "file:///" }; yield return new object[] { "/path/filename", "file:///path/filename", "file:///path/filename" }; } // Compressed yield return new object[] { "http://host/path1/../path2", "http://host/path2", "http://host/path2" }; yield return new object[] { "http://host/../", "http://host/", "http://host/" }; } [Theory] [MemberData(nameof(OriginalString_AbsoluteUri_ToString_TestData))] public void OriginalString_AbsoluteUri_ToString(string uriString, string absoluteUri, string toString) { PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(uriString, uri.OriginalString); Assert.Equal(absoluteUri, uri.AbsoluteUri); Assert.Equal(toString, uri.ToString()); }); } public static IEnumerable<object[]> Scheme_Authority_TestData() { // HTTP (Generic Uri Syntax) yield return new object[] { " \t \r http://host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host:90", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://USERINFO@host", "http", "USERINFO", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host:90/", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90/", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo@host/", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90/", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host/", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host?query", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90?query", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90?query", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host:90?query", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host?query", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host#fragment", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:90#fragment", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://@host:90#fragment", "http", "", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host:90#fragment", "http", "userinfo", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://userinfo@host#fragment", "http", "userinfo", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://user:password@host", "http", "user:password", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://user:80@host:90", "http", "user:80", "host", UriHostNameType.Dns, 90, false, false }; yield return new object[] { "http://host:0", "http", "", "host", UriHostNameType.Dns, 0, false, false }; yield return new object[] { "http://host:80", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://host:65535", "http", "", "host", UriHostNameType.Dns, 65535, false, false }; yield return new object[] { "http://part1-part2_part3-part4_part5/", "http", "", "part1-part2_part3-part4_part5", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "HTTP://USERINFO@HOST", "http", "USERINFO", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http.http2-http3+3http://host/", "http.http2-http3+3http", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"http:\\host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { @"http:/\host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { @"http:\/host", "http", "", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "https://host/", "https", "", "host", UriHostNameType.Dns, 443, true, false }; yield return new object[] { "http://_/", "http", "", "_", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://-/", "http", "", "-", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://_abc.efg1-hij2_345/path", "http", "", "_abc.efg1-hij2_345", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://_abc./path", "http", "", "_abc.", UriHostNameType.Basic, 80, true, false }; yield return new object[] { "http://xn--abc", "http", "", "xn--abc", UriHostNameType.Dns, 80, true, false }; // IPv4 host - decimal yield return new object[] { "http://4294967295/", "http", "", "255.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://4294967296/", "http", "", "4294967296", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.1/", "http", "", "192.168.0.1", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://192.168.0.1.1/", "http", "", "192.168.0.1.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.256.0.1/", "http", "", "192.256.0.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.256.1/", "http", "", "192.168.256.1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.256/", "http", "", "192.168.0.256", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://[email protected]:90/", "http", "userinfo", "192.168.0.1", UriHostNameType.IPv4, 90, false, false }; yield return new object[] { "http://192.16777216", "http", "", "192.16777216", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.65536", "http", "", "192.168.65536", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://192.168.0.256", "http", "", "192.168.0.256", UriHostNameType.Dns, 80, true, false }; // IPv4 host - hex yield return new object[] { "http://0x1a2B3c", "http", "", "0.26.43.60", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B3c", "http", "", "26.0.43.60", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B.0x3C4d", "http", "", "26.43.60.77", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x1a.0x2B.0x3C.0x4d", "http", "", "26.43.60.77", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFFFFFFFF/", "http", "", "255.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFFFFFF/", "http", "", "0.255.255.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0xFF/", "http", "", "0.0.0.255", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0/", "http", "", "0.0.0.0", UriHostNameType.IPv4, 80, true, false }; yield return new object[] { "http://0x100000000/", "http", "", "0x100000000", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://0x/", "http", "", "0x", UriHostNameType.Dns, 80, true, false }; // IPv4 host - octet yield return new object[] { "http://192.0123.0.10", "http", "", "192.83.0.10", UriHostNameType.IPv4, 80, true, false }; // IPv4 host - implicit UNC if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"/\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; } yield return new object[] { @"\\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"\/192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv4 host - explicit UNC yield return new object[] { @"file://\\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "file:////192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { @"file:///\192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; } yield return new object[] { @"file://\/192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv4 host - other yield return new object[] { "file://192.168.0.1", "file", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; yield return new object[] { "ftp://192.168.0.1", "ftp", "", "192.168.0.1", UriHostNameType.IPv4, 21, true, false }; yield return new object[] { "telnet://192.168.0.1", "telnet", "", "192.168.0.1", UriHostNameType.IPv4, 23, true, false }; yield return new object[] { "unknown://192.168.0.1", "unknown", "", "192.168.0.1", UriHostNameType.IPv4, -1, true, false }; // IPv6 host yield return new object[] { "http://[1111:1111:1111:1111:1111:1111:1111:1111]", "http", "", "[1111:1111:1111:1111:1111:1111:1111:1111]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[2001:0db8:0000:0000:0000:ff00:0042:8329]/", "http", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[2001:0db8:0000:0000:0000:ff00:0042:8329]:90/", "http", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 90, false, false }; yield return new object[] { "http://[1::]/", "http", "", "[1::]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[1::1]/", "http", "", "[1::1]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[::192.168.0.1]/", "http", "", "[::192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; yield return new object[] { "http://[::ffff:0:192.168.0.1]/", "http", "", "[::ffff:0:192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; // SIIT yield return new object[] { "http://[::ffff:1:192.168.0.1]/", "http", "", "[::ffff:1:c0a8:1]", UriHostNameType.IPv6, 80, true, false }; // SIIT (invalid) yield return new object[] { "http://[fe80::0000:5efe:192.168.0.1]/", "http", "", "[fe80::5efe:192.168.0.1]", UriHostNameType.IPv6, 80, true, false }; // ISATAP yield return new object[] { "http://[1111:2222:3333::431/20]", "http", "", "[1111:2222:3333::431]", UriHostNameType.IPv6, 80, true, false }; // Prefix // IPv6 Host - implicit UNC if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"/\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; } yield return new object[] { @"\\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"\/[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file://\\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // IPv6 host - explicit UNC yield return new object[] { "file:////[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file:///\[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { @"file://\/[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // IPv6 Host - other yield return new object[] { "file://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "file", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; yield return new object[] { "ftp://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "ftp", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 21, true, false }; yield return new object[] { "telnet://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "telnet", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, 23, true, false }; yield return new object[] { "unknown://[2001:0db8:0000:0000:0000:ff00:0042:8329]", "unknown", "", "[2001:db8::ff00:42:8329]", UriHostNameType.IPv6, -1, true, false }; // File - empty path yield return new object[] { "file:///", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - host yield return new object[] { "file://path1/path2", "file", "", "path1", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:///path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - explicit with windows drive with empty path yield return new object[] { "file://C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - explicit with windows drive with path yield return new object[] { "file://C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - '/' + windows drive with empty path yield return new object[] { "file:///C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:///C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - '/' + windows drive with path yield return new object[] { "file:///C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:///C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - implicit with empty path yield return new object[] { "C:/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "C|/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C:\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C|\", "file", "", "", UriHostNameType.Basic, -1, true, true }; // File - implicit with path yield return new object[] { "C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "C|/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C:\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"C|\path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - implicit with empty path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"/\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; } yield return new object[] { @"\\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\/unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - implicit with path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"/\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; } yield return new object[] { @"\\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\/unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"\\\/\/servername\sharename\path\filename", "file", "", "servername", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with empty host and empty path yield return new object[] { @"file://\\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and non empty path yield return new object[] { @"file://\\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\/", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\//", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and query yield return new object[] { @"file://\\?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/?query", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///?a", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file://///#a", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with empty host and fragment yield return new object[] { @"file://\\#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/#fragment", "file", "", "", UriHostNameType.Basic, -1, true, true }; // UNC - explicit with non empty host and empty path yield return new object[] { @"file://\\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:////unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file:///\unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file://\/unchost", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with path yield return new object[] { @"file://\\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "file:////unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file:///\unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; yield return new object[] { @"file://\/unchost/path1/path2", "file", "", "unchost", UriHostNameType.Dns, -1, true, false }; // UNC - explicit with windows drive yield return new object[] { @"file://\\C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "file:////C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file:///\C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { @"file://\/C:/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; // Unix path if (!s_isWindowsSystem) { // Implicit with path yield return new object[] { "/path1/path2", "file", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "/", "file", "", "", UriHostNameType.Basic, -1, true, true }; } // File - with host yield return new object[] { @"file://host/", "file", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.a./", "unknown", "", "h.a.", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.1./", "unknown", "", "h.1.", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://h.-/", "unknown", "", "h.-", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://h._", "unknown", "", "h._", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; // Mailto yield return new object[] { "mailto:", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; yield return new object[] { "mailto:[email protected]", "mailto", "someone", "example.com", UriHostNameType.Dns, 25, true, false }; yield return new object[] { "mailto://[email protected]", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; yield return new object[] { "mailto:/[email protected]", "mailto", "", "", UriHostNameType.Basic, 25, true, true }; // FTP yield return new object[] { "ftp://host", "ftp", "", "host", UriHostNameType.Dns, 21, true, false }; yield return new object[] { "ftp://userinfo@host", "ftp", "userinfo", "host", UriHostNameType.Dns, 21, true, false }; yield return new object[] { "ftp://host?query#fragment", "ftp", "", "host", UriHostNameType.Dns, 21, true, false }; // Telnet yield return new object[] { "telnet://host/", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host:80", "telnet", "", "host", UriHostNameType.Dns, 80, false, false }; yield return new object[] { "telnet://userinfo@host/", "telnet", "userinfo", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://username:password@host/", "telnet", "username:password", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host?query#fragment", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://host#fragment", "telnet", "", "host", UriHostNameType.Dns, 23, true, false }; yield return new object[] { "telnet://localhost/", "telnet", "", "localhost", UriHostNameType.Dns, 23, true, true }; yield return new object[] { "telnet://loopback/", "telnet", "", "localhost", UriHostNameType.Dns, 23, true, true }; // Unknown yield return new object[] { "urn:namespace:segment1:segment2:segment3", "urn", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown:", "unknown", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown:path", "unknown", "", "", UriHostNameType.Unknown, -1, true, false }; yield return new object[] { "unknown://host", "unknown", "", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://userinfo@host", "unknown", "userinfo", "host", UriHostNameType.Dns, -1, true, false }; yield return new object[] { "unknown://userinfo@host:80", "unknown", "userinfo", "host", UriHostNameType.Dns, 80, false, false }; yield return new object[] { "unknown://./", "unknown", "", ".", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://../", "unknown", "", "..", UriHostNameType.Basic, -1, true, false }; yield return new object[] { "unknown://////", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; yield return new object[] { "unknown:///C:/", "unknown", "", "", UriHostNameType.Basic, -1, true, true }; // Loopback - HTTP yield return new object[] { "http://localhost/", "http", "", "localhost", UriHostNameType.Dns, 80, true, true }; yield return new object[] { "http://loopback/", "http", "", "localhost", UriHostNameType.Dns, 80, true, true }; // Loopback - implicit UNC with localhost if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"/\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; } yield return new object[] { @"\\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"\/localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - explicit UNC with localhost yield return new object[] { @"file://\\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file:///\localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file://\/localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { "file:////localhost", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - implicit UNC with loopback if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"/\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; } yield return new object[] { @"\\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"\/loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - explicit UNC with loopback yield return new object[] { @"file://\\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { "file:////loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file:///\loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; yield return new object[] { @"file://\/loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // Loopback - IpV4 yield return new object[] { "http://127.0.0.1/", "http", "", "127.0.0.1", UriHostNameType.IPv4, 80, true, true }; // Loopback - IpV6 yield return new object[] { "http://[::1]/", "http", "", "[::1]", UriHostNameType.IPv6, 80, true, true }; yield return new object[] { "http://[::127.0.0.1]/", "http", "", "[::127.0.0.1]", UriHostNameType.IPv6, 80, true, true }; // Loopback - File yield return new object[] { "file://loopback", "file", "", "localhost", UriHostNameType.Dns, -1, true, true }; // RFC incompatability // We allow any non-unreserved, percent encoding or sub-delimeter in the userinfo yield return new object[] { "http://abc\u1234\u2345\u3456@host/", "http", "abc%E1%88%B4%E2%8D%85%E3%91%96", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234abc\u2345\u3456@host/", "http", "%E1%88%B4abc%E2%8D%85%E3%91%96", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234\u2345\u3456abc@host/", "http", "%E1%88%B4%E2%8D%85%E3%91%96abc", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo!~+-_*()[]:;&$=123PLACEHOLDER@host/", "http", "userinfo!~+-_*()[]:;&$=123PLACEHOLDER", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://%68%65%6C%6C%6F@host/", "http", "hello", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u00A3@host/", "http", "%C2%A3", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u1234@host/", "http", "%E1%88%B4", "host", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://userinfo%%%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%2g%2G@host", "http", "userinfo%25%25%2F%3F%23%5B%5D%40%3B%26%2B%2C%5C%252g%252G", "host", UriHostNameType.Dns, 80, true, false }; } [Theory] [MemberData(nameof(Scheme_Authority_TestData))] public void Scheme_Authority_Basic(string uriString, string scheme, string userInfo, string host, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string idnHost = host; if (hostNameType == UriHostNameType.IPv6) { idnHost = host.Substring(1, host.Length - 2); } Scheme_Authority_IdnHost(uriString, scheme, userInfo, host, idnHost, idnHost, hostNameType, port, isDefaultPort, isLoopback); } public static IEnumerable<object[]> Scheme_Authority_IdnHost_TestData() { yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442", "xn--b1agh1afp", "\u043F\u0440\u0438\u0432\u0435\u0442", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442.ascii/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442.ascii", "xn--b1agh1afp.ascii", "\u043F\u0440\u0438\u0432\u0435\u0442.ascii", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://ascii.\u043F\u0440\u0438\u0432\u0435\u0442/", "http", "", "ascii.\u043F\u0440\u0438\u0432\u0435\u0442", "ascii.xn--b1agh1afp", "ascii.\u043F\u0440\u0438\u0432\u0435\u0442", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1/", "http", "", "\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1", "xn--b1agh1afp.xn--ixaiab0ch2c", "\u043F\u0440\u0438\u0432\u0435\u0442.\u03B2\u03AD\u03BB\u03B1\u03C3\u03BC\u03B1", UriHostNameType.Dns, 80, true, false }; yield return new object[] { "http://[1111:2222:3333::431%16]:50/", "http", "", "[1111:2222:3333::431]", "1111:2222:3333::431%16", "1111:2222:3333::431%16", UriHostNameType.IPv6, 50, false, false }; // Scope ID yield return new object[] { "http://[1111:2222:3333::431%16/20]", "http", "", "[1111:2222:3333::431]", "1111:2222:3333::431%16", "1111:2222:3333::431%16", UriHostNameType.IPv6, 80, true, false }; // Scope ID and prefix yield return new object[] { "http://\u1234\u2345\u3456/", "http", "", "\u1234\u2345\u3456", "xn--ryd258fr0m", "\u1234\u2345\u3456", UriHostNameType.Dns, 80, true, false }; } [Theory] [MemberData(nameof(Scheme_Authority_IdnHost_TestData))] public void Scheme_Authority_IdnHost(string uriString, string scheme, string userInfo, string host, string idnHost, string dnsSafeHost, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string authority = host; if (!isDefaultPort) { authority += ":" + port.ToString(); } PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(scheme, uri.Scheme); Assert.Equal(authority, uri.Authority); Assert.Equal(userInfo, uri.UserInfo); Assert.Equal(host, uri.Host); Assert.Equal(idnHost, uri.IdnHost); Assert.Equal(dnsSafeHost, uri.DnsSafeHost); Assert.Equal(hostNameType, uri.HostNameType); Assert.Equal(port, uri.Port); Assert.Equal(isDefaultPort, uri.IsDefaultPort); Assert.Equal(isLoopback, uri.IsLoopback); Assert.True(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); }); } public static IEnumerable<object[]> Path_Query_Fragment_TestData() { // Http yield return new object[] { "http://host", "/", "", "" }; yield return new object[] { "http://host?query", "/", "?query", "" }; yield return new object[] { "http://host#fragment", "/", "", "#fragment" }; yield return new object[] { "http://host?query#fragment", "/", "?query", "#fragment" }; yield return new object[] { "http://host/PATH?QUERY#FRAGMENT", "/PATH", "?QUERY", "#FRAGMENT" }; yield return new object[] { "http://host/", "/", "", "" }; yield return new object[] { "http://host/path1/path2", "/path1/path2", "", "" }; yield return new object[] { "http://host/path1/path2/", "/path1/path2/", "", "" }; yield return new object[] { "http://host/?query", "/", "?query", "" }; yield return new object[] { "http://host/path1/path2/?query", "/path1/path2/", "?query", "" }; yield return new object[] { "http://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "http://host/path1/path2/#fragment", "/path1/path2/", "", "#fragment" }; yield return new object[] { "http://host/?query#fragment", "/", "?query", "#fragment" }; yield return new object[] { "http://host/path1/path2/?query#fragment", "/path1/path2/", "?query", "#fragment" }; yield return new object[] { "http://host/?#fragment", "/", "?", "#fragment" }; yield return new object[] { "http://host/path1/path2/?#fragment", "/path1/path2/", "?", "#fragment" }; yield return new object[] { "http://host/?query#", "/", "?query", "#" }; yield return new object[] { "http://host/path1/path2/?query#", "/path1/path2/", "?query", "#" }; yield return new object[] { "http://host/?", "/", "?", "" }; yield return new object[] { "http://host/path1/path2/?", "/path1/path2/", "?", "" }; yield return new object[] { "http://host/#", "/", "", "#" }; yield return new object[] { "http://host/path1/path2/#", "/path1/path2/", "", "#" }; yield return new object[] { "http://host/?#", "/", "?", "#" }; yield return new object[] { "http://host/path1/path2/?#", "/path1/path2/", "?", "#" }; yield return new object[] { "http://host/?query1?query2#fragment1#fragment2?query3", "/", "?query1?query2", "#fragment1#fragment2?query3" }; yield return new object[] { "http://host/?query1=value&query2", "/", "?query1=value&query2", "" }; yield return new object[] { "http://host/?:@?/", "/", "?:@?/", "" }; yield return new object[] { @"http://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"http://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { "http://host/path \t \r \n \x0009 \x000A \x000D", "/path", "", "" }; yield return new object[] { "http://host/path?query \t \r \n \x0009 \x000A \x000D", "/path", "?query", "" }; yield return new object[] { "http://host/path#fragment \t \r \n \x0009 \x000A \x000D", "/path", "", "#fragment" }; yield return new object[] { "http://192.168.0.1:50/path1/page?query#fragment", "/path1/page", "?query", "#fragment" }; yield return new object[] { "http://192.168.0.1:80/\u1234\u2345/\u4567\u5678?query#fragment", "/%E1%88%B4%E2%8D%85/%E4%95%A7%E5%99%B8", "?query", "#fragment" }; yield return new object[] { "http://[1111:2222:3333::431]/path1/page?query#fragment", "/path1/page", "?query", "#fragment" }; yield return new object[] { "http://[1111:2222:3333::431]/\u1234\u2345/\u4567\u5678?query#fragment", "/%E1%88%B4%E2%8D%85/%E4%95%A7%E5%99%B8", "?query", "#fragment" }; // File with empty path yield return new object[] { "file:///", "/", "", "" }; yield return new object[] { @"file://\", "/", "", "" }; // File with windows drive yield return new object[] { "file://C:/", "C:/", "", "" }; yield return new object[] { "file://C|/", "C:/", "", "" }; yield return new object[] { @"file://C:\", "C:/", "", "" }; yield return new object[] { @"file://C|\", "C:/", "", "" }; // File with windows drive with path yield return new object[] { "file://C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "file://C|/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://C:\path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://C|\path1/path2", "C:/path1/path2", "", "" }; // File with windows drive with backlash in path yield return new object[] { @"file://C:/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C|/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C:\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://C|\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; // File with windows drive ending with backslash yield return new object[] { @"file://C:/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C|/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C:\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://C|\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; // File with host yield return new object[] { "file://path1/path2", "/path2", "", "" }; yield return new object[] { "file:///path1/path2", "/path1/path2", "", "" }; if (s_isWindowsSystem) { yield return new object[] { @"file:///path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:///path1\path2/path3%5Cpath4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://localhost/path1%5Cpath2", "/path1/path2", "", "" }; } else // Unix paths preserve backslash { yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", "" }; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file://localhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", "" }; } // Implicit file with empty path yield return new object[] { "C:/", "C:/", "", "" }; yield return new object[] { "C|/", "C:/", "", "" }; yield return new object[] { @"C:\", "C:/", "", "" }; yield return new object[] { @"C|\", "C:/", "", "" }; // Implicit file with path yield return new object[] { "C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "C|/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"C:\path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"C|\path1/path2", "C:/path1/path2", "", "" }; // Implicit file with backslash in path yield return new object[] { @"C:/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C|/path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C:\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; yield return new object[] { @"C|\path1\path2/path3\path4", "C:/path1/path2/path3/path4", "", "" }; // Implicit file ending with backlash yield return new object[] { @"C:/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C|/path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C:\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"C|\path1\path2/path3\path4\", "C:/path1/path2/path3/path4/", "", "" }; // Implicit UNC with empty path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { "//unchost", "/", "", "" }; yield return new object[] { @"/\unchost", "/", "", "" }; } yield return new object[] { @"\\unchost", "/", "", "" }; yield return new object[] { @"\/unchost", "/", "", "" }; // Implicit UNC with path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { "//unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"/\unchost/path1/path2", "/path1/path2", "", "" }; } yield return new object[] { @"\\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"\/unchost/path1/path2", "/path1/path2", "", "" }; // Implicit UNC with backslash in path if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { @"//unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"/\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; } yield return new object[] { @"\\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"\/unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"\\\/\/servername\sharename\path\filename", "/sharename/path/filename", "", "" }; // Implicit UNC ending with backslash if (s_isWindowsSystem) // Unix UNC paths must start with '\' { yield return new object[] { @"//unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"/\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; } yield return new object[] { @"\\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"\/unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Explicit UNC with empty path yield return new object[] { @"file://\\unchost", "/", "", "" }; yield return new object[] { "file:////unchost", "/", "", "" }; yield return new object[] { @"file:///\unchost", "/", "", "" }; yield return new object[] { @"file://\/unchost", "/", "", "" }; // Explicit UNC with empty host and empty path yield return new object[] { @"file://\\", "//", "", "" }; yield return new object[] { "file:////", "//", "", "" }; yield return new object[] { @"file:///\", "//", "", "" }; yield return new object[] { @"file://\/", "//", "", "" }; // Explicit UNC with empty host and non-empty path yield return new object[] { @"file://\\/", "///", "", "" }; yield return new object[] { "file://///", "///", "", "" }; yield return new object[] { @"file:///\/", "///", "", "" }; yield return new object[] { @"file://\//", "///", "", "" }; // Explicit UNC with empty host and query yield return new object[] { @"file://\\?query", "//", "?query", "" }; yield return new object[] { "file:////?query", "//", "?query", "" }; yield return new object[] { @"file:///\?query", "//", "?query", "" }; yield return new object[] { @"file://\/?query", "//", "?query", "" }; yield return new object[] { "file://///?query", "///", "?query", "" }; // Explicit UNC with empty host and fragment yield return new object[] { @"file://\\#fragment", "//", "", "#fragment" }; yield return new object[] { "file:////#fragment", "//", "", "#fragment" }; yield return new object[] { @"file:///\#fragment", "//", "", "#fragment" }; yield return new object[] { @"file://\/#fragment", "//", "", "#fragment" }; yield return new object[] { "file://///#fragment", "///", "", "#fragment" }; // Explicit UNC with path yield return new object[] { @"file://\\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { "file:////unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"file:///\unchost/path1/path2", "/path1/path2", "", "" }; yield return new object[] { @"file://\/unchost/path1/path2", "/path1/path2", "", "" }; // Explicit UNC with path, query and fragment yield return new object[] { @"file://\\unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { "file:////unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { @"file:///\unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; yield return new object[] { @"file://\/unchost/path1/path2?query#fragment", "/path1/path2", "?query", "#fragment" }; // Explicit UNC with a windows drive as host yield return new object[] { @"file://\\C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { "file:////C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file:///\C:/path1/path2", "C:/path1/path2", "", "" }; yield return new object[] { @"file://\/C:/path1/path2", "C:/path1/path2", "", "" }; // Other yield return new object[] { "C|/path|path/path2", "C:/path%7Cpath/path2", "", "" }; yield return new object[] { "file://host/path?query#fragment", "/path", "?query", "#fragment" }; if (s_isWindowsSystem) { // Explicit UNC with backslash in path yield return new object[] { @"file://\\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; // Explicit UNC ending with backslash yield return new object[] { @"file://\\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; } else { // Implicit file with path yield return new object[] { "/", "/", "", "" }; yield return new object[] { "/path1/path2", "/path1/path2", "", "" }; // Implicit file with backslash in path yield return new object[] { @"/path1\path2/path3\path4", "/path1%5Cpath2/path3%5Cpath4", "", "" }; // Implicit file ending with backlash yield return new object[] { @"/path1\path2/path3\path4\", "/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; // Explicit UNC with backslash in path yield return new object[] { @"file://\\unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; // Explicit UNC ending with backslash yield return new object[] { @"file://\\unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file:////unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file:///\unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; yield return new object[] { @"file://\/unchost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; } // Mailto yield return new object[] { "mailto:[email protected]", "", "", "" }; yield return new object[] { "mailto:[email protected]?query#fragment", "", "?query", "#fragment" }; yield return new object[] { "mailto:/[email protected]", "/[email protected]", "", "" }; yield return new object[] { "mailto://[email protected]", "//[email protected]", "", "" }; yield return new object[] { "mailto://[email protected]?query#fragment", "//[email protected]", "?query", "#fragment" }; // Ftp yield return new object[] { "ftp://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "ftp://host/#fragment", "/", "", "#fragment" }; yield return new object[] { "ftp://host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { "ftp://userinfo@host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { @"ftp://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"ftp://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Telnet yield return new object[] { "telnet://userinfo@host/", "/", "", "" }; yield return new object[] { "telnet://userinfo@host?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { "telnet://userinfo@host/?query#fragment", "/%3Fquery", "", "#fragment" }; yield return new object[] { @"telnet://host/path1\path2/path3\path4", "/path1%5Cpath2/path3%5Cpath4", "", "" }; yield return new object[] { @"telnet://host/path1\path2/path3\path4\", "/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; // Unknown yield return new object[] { "urn:namespace:segment1:segment2:segment3", "namespace:segment1:segment2:segment3", "", "" }; yield return new object[] { "unknown:", "", "", "" }; yield return new object[] { "unknown:path", "path", "", "" }; yield return new object[] { "unknown:path1:path2", "path1:path2", "", "" }; yield return new object[] { "unknown:path?query#fragment", "path", "?query", "#fragment" }; yield return new object[] { "unknown:?query#fragment", "", "?query", "#fragment" }; yield return new object[] { "unknown://./", "/", "", "" }; yield return new object[] { "unknown://../", "/", "", "" }; yield return new object[] { "unknown://////", "////", "", "" }; yield return new object[] { "unknown:///C:/", "C:/", "", "" }; yield return new object[] { "unknown://host/path?query#fragment", "/path", "?query", "#fragment" }; yield return new object[] { @"unknown://host/path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"unknown://host/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; // Does not need to be escaped yield return new object[] { "http://host/path!~+-_*()[]@:;&$=123PATH", "/path!~+-_*()[]@:;&$=123PATH", "", "" }; yield return new object[] { "http://host/?query!~+-_*()[]@:;&$=123QUERY", "/", "?query!~+-_*()[]@:;&$=123QUERY", "" }; yield return new object[] { "http://host/#fragment!~+-_*()[]@:;&$=123FRAGMENT", "/", "", "#fragment!~+-_*()[]@:;&$=123FRAGMENT" }; // Unescaped yield return new object[] { "http://host/\u1234\u2345\u3456", "/%E1%88%B4%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/abc\u1234\u2345\u3456", "/abc%E1%88%B4%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/\u1234abc\u2345\u3456", "/%E1%88%B4abc%E2%8D%85%E3%91%96", "", "" }; yield return new object[] { "http://host/\u1234\u2345\u3456abc", "/%E1%88%B4%E2%8D%85%E3%91%96abc", "", "" }; yield return new object[] { "http://host/?abc\u1234\u2345\u3456", "/", "?abc%E1%88%B4%E2%8D%85%E3%91%96", "" }; yield return new object[] { "http://host/?\u1234abc\u2345\u3456", "/", "?%E1%88%B4abc%E2%8D%85%E3%91%96", "" }; yield return new object[] { "http://host/?\u1234\u2345\u3456abc", "/", "?%E1%88%B4%E2%8D%85%E3%91%96abc", "" }; yield return new object[] { "http://host/#abc\u1234\u2345\u3456", "/", "", "#abc%E1%88%B4%E2%8D%85%E3%91%96" }; yield return new object[] { "http://host/#\u1234abc\u2345\u3456", "/", "", "#%E1%88%B4abc%E2%8D%85%E3%91%96" }; yield return new object[] { "http://host/#\u1234\u2345\u3456abc", "/", "", "#%E1%88%B4%E2%8D%85%E3%91%96abc" }; yield return new object[] { "http://host/\0?\0#\0", "/%00", "?%00", "#%00" }; // Unnecessarily escaped (upper case hex letters) yield return new object[] { "http://host/%68%65%6C%6C%6F", "/hello", "", "" }; yield return new object[] { "http://host/?%68%65%6C%6C%6F", "/", "?hello", "" }; yield return new object[] { "http://host/#%68%65%6C%6C%6F", "/", "", "#hello" }; // Unnecessarily escaped (lower case hex letters) yield return new object[] { "http://host/%68%65%6c%6c%6f", "/hello", "", "" }; yield return new object[] { "http://host/?%68%65%6c%6c%6f", "/", "?hello", "" }; yield return new object[] { "http://host/#%68%65%6c%6c%6f", "/", "", "#hello" }; // Encoded generic delimeters should not be expanded yield return new object[] { "http://host/%3A?%3A#%3A", "/%3A", "?%3A", "#%3A" }; yield return new object[] { "http://host/%2F?%2F#%2F", "/%2F", "?%2F", "#%2F" }; yield return new object[] { "http://host/%3F?%3F#%3F", "/%3F", "?%3F", "#%3F" }; yield return new object[] { "http://host/%23?%23#%23", "/%23", "?%23", "#%23" }; yield return new object[] { "http://host/%5B?%5B#%5B", "/%5B", "?%5B", "#%5B" }; yield return new object[] { "http://host/%5D?%5D#%5D", "/%5D", "?%5D", "#%5D" }; yield return new object[] { "http://host/%40?%40#%40", "/%40", "?%40", "#%40" }; // Encoded sub delimeters should not be expanded yield return new object[] { "http://host/%21?%21#%21", "/%21", "?%21", "#%21" }; yield return new object[] { "http://host/%24?%24#%24", "/%24", "?%24", "#%24" }; yield return new object[] { "http://host/%26?%26#%26", "/%26", "?%26", "#%26" }; yield return new object[] { "http://host/%5C?%5C#%5C", "/%5C", "?%5C", "#%5C" }; yield return new object[] { "http://host/%28?%28#%28", "/%28", "?%28", "#%28" }; yield return new object[] { "http://host/%29?%29#%29", "/%29", "?%29", "#%29" }; yield return new object[] { "http://host/%2A?%2A#%2A", "/%2A", "?%2A", "#%2A" }; yield return new object[] { "http://host/%2B?%2B#%2B", "/%2B", "?%2B", "#%2B" }; yield return new object[] { "http://host/%2C?%2C#%2C", "/%2C", "?%2C", "#%2C" }; yield return new object[] { "http://host/%3B?%3B#%3B", "/%3B", "?%3B", "#%3B" }; yield return new object[] { "http://host/%3D?%3D#%3D", "/%3D", "?%3D", "#%3D" }; // Invalid unicode yield return new object[] { "http://host/%?%#%", "/%25", "?%25", "#%25" }; yield return new object[] { "http://host/%3?%3#%3", "/%253", "?%253", "#%253" }; yield return new object[] { "http://host/%G?%G#%G", "/%25G", "?%25G", "#%25G" }; yield return new object[] { "http://host/%g?%g#%g", "/%25g", "?%25g", "#%25g" }; yield return new object[] { "http://host/%G3?%G3#%G3", "/%25G3", "?%25G3", "#%25G3" }; yield return new object[] { "http://host/%g3?%g3#%g3", "/%25g3", "?%25g3", "#%25g3" }; yield return new object[] { "http://host/%3G?%3G#%3G", "/%253G", "?%253G", "#%253G" }; yield return new object[] { "http://host/%3g?%3g#%3g", "/%253g", "?%253g", "#%253g" }; // Compressed yield return new object[] { "http://host/%2E%2E/%2E%2E", "/", "", "" }; yield return new object[] { "http://host/path1/../path2", "/path2", "", "" }; yield return new object[] { "http://host/../", "/", "", "" }; yield return new object[] { "http://host/path1/./path2", "/path1/path2", "", "" }; yield return new object[] { "http://host/./", "/", "", "" }; yield return new object[] { "http://host/..", "/", "", "" }; yield return new object[] { "http://host/.../", "/.../", "", "" }; yield return new object[] { "http://host/x../", "/x../", "", "" }; yield return new object[] { "http://host/..x/", "/..x/", "", "" }; yield return new object[] { "http://host/path//", "/path//", "", "" }; yield return new object[] { "file://C:/abc/def/../ghi", "C:/abc/ghi", "", "" }; } [Theory] [MemberData(nameof(Path_Query_Fragment_TestData))] public void Path_Query_Fragment(string uriString, string path, string query, string fragment) { IEnumerable<string> segments = null; string localPath = null; string segmentsPath = null; PerformAction(uriString, UriKind.Absolute, uri => { if (segments == null) { localPath = Uri.UnescapeDataString(path); segmentsPath = path; if (uri.IsUnc) { localPath = @"\\" + uri.Host + path; localPath = localPath.Replace('/', '\\'); // Unescape '\\' localPath = localPath.Replace("%5C", "\\"); if (path == "/") { localPath = localPath.Substring(0, localPath.Length - 1); } } else if (path.Length > 2 && path[1] == ':' && path[2] == '/') { segmentsPath = '/' + segmentsPath; localPath = localPath.Replace('/', '\\'); } segments = Regex.Split(segmentsPath, @"(?<=/)").TakeWhile(s => s.Length != 0); } Assert.Equal(path, uri.AbsolutePath); Assert.Equal(localPath, uri.LocalPath); Assert.Equal(path + query, uri.PathAndQuery); Assert.Equal(segments, uri.Segments); Assert.Equal(query, uri.Query); Assert.Equal(fragment, uri.Fragment); Assert.True(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); }); } public static IEnumerable<object[]> IsFile_IsUnc_TestData() { // Explicit file with windows drive with path yield return new object[] { "file://C:/path", true, false }; yield return new object[] { "file://C|/path", true, false }; yield return new object[] { @"file://C:\path", true, false }; yield return new object[] { @"file://C|\path", true, false }; yield return new object[] { "file:///C:/path", true, false }; yield return new object[] { "file:///C|/path", true, false }; yield return new object[] { @"file:///C:\path", true, false }; yield return new object[] { @"file:///C|\path", true, false }; // File with empty path yield return new object[] { "file:///", true, false }; yield return new object[] { @"file://\", true, false }; // File with host yield return new object[] { "file://host/path2", true, true }; // Implicit file with windows drive with empty path yield return new object[] { "C:/", true, false }; yield return new object[] { "C|/", true, false }; yield return new object[] { @"C:\", true, false }; yield return new object[] { @"C|/", true, false }; // Implicit file with windows drive with path yield return new object[] { "C:/path", true, false }; yield return new object[] { "C|/path", true, false }; yield return new object[] { @"C:\path", true, false }; yield return new object[] { @"C|\path", true, false }; yield return new object[] { @"\\unchost", true, true }; // Implicit UNC with empty path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost", true, true }; yield return new object[] { @"/\unchost", true, true }; } yield return new object[] { @"\\unchost", true, true }; yield return new object[] { @"\/unchost", true, true }; // Implicit UNC with path if (s_isWindowsSystem) // Unc can only start with '/' on Windows { yield return new object[] { "//unchost/path1/path2", true, true }; yield return new object[] { @"/\unchost/path1/path2", true, true }; } yield return new object[] { @"\\unchost/path1/path2", true, true }; yield return new object[] { @"\/unchost/path1/path2", true, true }; // Explicit UNC with empty path yield return new object[] { @"file://\\unchost", true, true }; yield return new object[] { "file:////unchost", true, true }; yield return new object[] { @"file:///\unchost", true, true }; yield return new object[] { @"file://\/unchost", true, true }; // Explicit UNC with empty host and empty path yield return new object[] { @"file://\\", true, false }; yield return new object[] { "file:////", true, false }; yield return new object[] { @"file:///\", true, false }; yield return new object[] { @"file://\/", true, false }; // Explicit UNC with empty host and non empty path yield return new object[] { @"file://\\/", true, false }; yield return new object[] { "file://///", true, false }; yield return new object[] { @"file:///\/", true, false }; yield return new object[] { @"file://\//", true, false }; // Explicit UNC with query yield return new object[] { @"file://\\?query", true, false }; yield return new object[] { "file:////?query", true, false }; yield return new object[] { @"file:///\?query", true, false }; yield return new object[] { @"file://\/?query", true, false }; // Explicit UNC with fragment yield return new object[] { @"file://\\#fragment", true, false }; yield return new object[] { "file:////#fragment", true, false }; yield return new object[] { @"file:///\#fragment", true, false }; yield return new object[] { @"file://\/#fragment", true, false }; // Explicit UNC with path yield return new object[] { @"file://\\unchost/path1/path2", true, true }; yield return new object[] { "file:////unchost/path1/path2", true, true }; yield return new object[] { @"file:///\unchost/path1/path2", true, true }; yield return new object[] { @"file://\/unchost/path1/path2", true, true }; // Explicit UNC with windows drive yield return new object[] { @"file://\\C:/", true, false }; yield return new object[] { "file:////C:/", true, false }; yield return new object[] { @"file:///\C:/", true, false }; yield return new object[] { @"file://\/C:/", true, false }; yield return new object[] { @"file://\\C|/", true, false }; yield return new object[] { "file:////C|/", true, false }; yield return new object[] { @"file:///\C|/", true, false }; yield return new object[] { @"file://\/C|/", true, false }; yield return new object[] { @"file://\\C:\", true, false }; yield return new object[] { @"file:////C:\", true, false }; yield return new object[] { @"file:///\C:\", true, false }; yield return new object[] { @"file://\/C:\", true, false }; yield return new object[] { @"file://\\C|\", true, false }; yield return new object[] { @"file:////C|\", true, false }; yield return new object[] { @"file:///\C|\", true, false }; yield return new object[] { @"file://\/C|\", true, false }; // Not a file yield return new object[] { "http://host/", false, false }; yield return new object[] { "https://host/", false, false }; yield return new object[] { "mailto:[email protected]", false, false }; yield return new object[] { "ftp://host/", false, false }; yield return new object[] { "telnet://host/", false, false }; yield return new object[] { "unknown:", false, false }; yield return new object[] { "unknown:path", false, false }; yield return new object[] { "unknown://host/", false, false }; } [Theory] [MemberData(nameof(IsFile_IsUnc_TestData))] public void IsFile_IsUnc(string uriString, bool isFile, bool isUnc) { PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(isFile, uri.IsFile); Assert.Equal(isUnc, uri.IsUnc); }); } public static IEnumerable<object[]> Relative_TestData() { yield return new object[] { "path1/page.htm?query1=value#fragment", true }; yield return new object[] { "/", true }; yield return new object[] { "?query", true }; yield return new object[] { "#fragment", true }; yield return new object[] { @"C:\abc", false }; yield return new object[] { @"C|\abc", false }; yield return new object[] { @"\\servername\sharename\path\filename", false }; } [Theory] [MemberData(nameof(Relative_TestData))] public void Relative(string uriString, bool relativeOrAbsolute) { PerformAction(uriString, UriKind.Relative, uri => { VerifyRelativeUri(uri, uriString, uriString); }); PerformAction(uriString, UriKind.RelativeOrAbsolute, uri => { if (relativeOrAbsolute) { VerifyRelativeUri(uri, uriString, uriString); } else { Assert.True(uri.IsAbsoluteUri); } }); } [Fact] public void Create_String_Null_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("uriString", () => new Uri(null)); AssertExtensions.Throws<ArgumentNullException>("uriString", () => new Uri(null, UriKind.Absolute)); Uri uri; Assert.False(Uri.TryCreate(null, UriKind.Absolute, out uri)); Assert.Null(uri); } [Fact] public void Create_String_InvalidUriKind_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new Uri("http://host", UriKind.RelativeOrAbsolute - 1)); AssertExtensions.Throws<ArgumentException>(null, () => new Uri("http://host", UriKind.Relative + 1)); Uri uri = null; AssertExtensions.Throws<ArgumentException>(null, () => Uri.TryCreate("http://host", UriKind.RelativeOrAbsolute - 1, out uri)); Assert.Null(uri); AssertExtensions.Throws<ArgumentException>(null, () => Uri.TryCreate("http://host", UriKind.Relative + 1, out uri)); Assert.Null(uri); } public static IEnumerable<object[]> Create_String_Invalid_TestData() { yield return new object[] { s_longString, UriKind.Absolute }; // UriString is longer than 66520 characters // Invalid scheme yield return new object[] { "", UriKind.Absolute }; yield return new object[] { " \t \r \n \x0009 \x000A \x000D ", UriKind.Absolute }; yield return new object[] { "http", UriKind.Absolute }; yield return new object[] { ":", UriKind.Absolute }; yield return new object[] { "1http://host/", UriKind.Absolute }; yield return new object[] { "http/://host/", UriKind.Absolute }; yield return new object[] { "\u1234http://host/", UriKind.Absolute }; yield return new object[] { "ht\u1234tp://host/", UriKind.Absolute }; yield return new object[] { "ht%45tp://host/", UriKind.Absolute }; yield return new object[] { "\x00a0 \x000B \x000C \x0085http", UriKind.Absolute }; yield return new object[] { "~", UriKind.Absolute }; yield return new object[] { "http://", UriKind.Absolute }; yield return new object[] { "http:/", UriKind.Absolute }; yield return new object[] { "domain.com", UriKind.Absolute }; yield return new object[] { "\u1234http://domain.com", UriKind.Absolute }; yield return new object[] { "http\u1234://domain.com", UriKind.Absolute }; yield return new object[] { "http~://domain.com", UriKind.Absolute }; yield return new object[] { "http#://domain.com", UriKind.Absolute }; yield return new object[] { new string('a', 1025) + "://domain.com", UriKind.Absolute }; // Scheme is longer than 1024 characters // Invalid userinfo yield return new object[] { @"http://use\rinfo@host", UriKind.Absolute }; // Invalid characters in host yield return new object[] { "http://ho!st/", UriKind.Absolute }; yield return new object[] { "http://ho&st/", UriKind.Absolute }; yield return new object[] { "http://ho$st/", UriKind.Absolute }; yield return new object[] { "http://ho(st/", UriKind.Absolute }; yield return new object[] { "http://ho)st/", UriKind.Absolute }; yield return new object[] { "http://ho*st", UriKind.Absolute }; yield return new object[] { "http://ho+st", UriKind.Absolute }; yield return new object[] { "http://ho,st", UriKind.Absolute }; yield return new object[] { "http://ho;st/", UriKind.Absolute }; yield return new object[] { "http://ho=st", UriKind.Absolute }; yield return new object[] { "http://ho~st/", UriKind.Absolute }; // Empty host yield return new object[] { "http://", UriKind.Absolute }; yield return new object[] { "http:/", UriKind.Absolute }; yield return new object[] { "http:/abc", UriKind.Absolute }; yield return new object[] { "http://@", UriKind.Absolute }; yield return new object[] { "http://userinfo@", UriKind.Absolute }; yield return new object[] { "http://:", UriKind.Absolute }; yield return new object[] { "http://:80", UriKind.Absolute }; yield return new object[] { "http://@:", UriKind.Absolute }; yield return new object[] { "http://@:80", UriKind.Absolute }; yield return new object[] { "http://userinfo@:80", UriKind.Absolute }; yield return new object[] { "http:///", UriKind.Absolute }; yield return new object[] { "http://@/", UriKind.Absolute }; yield return new object[] { "http://userinfo@/", UriKind.Absolute }; yield return new object[] { "http://:/", UriKind.Absolute }; yield return new object[] { "http://:80/", UriKind.Absolute }; yield return new object[] { "http://@:/", UriKind.Absolute }; yield return new object[] { "http://@:80/", UriKind.Absolute }; yield return new object[] { "http://userinfo@:80/", UriKind.Absolute }; yield return new object[] { "http://?query", UriKind.Absolute }; yield return new object[] { "http://:?query", UriKind.Absolute }; yield return new object[] { "http://@:?query", UriKind.Absolute }; yield return new object[] { "http://userinfo@:?query", UriKind.Absolute }; yield return new object[] { "http://#fragment", UriKind.Absolute }; yield return new object[] { "http://:#fragment", UriKind.Absolute }; yield return new object[] { "http://@:#fragment", UriKind.Absolute }; yield return new object[] { "http://userinfo@:#fragment", UriKind.Absolute }; yield return new object[] { @"http://host\", UriKind.Absolute }; yield return new object[] { @"http://userinfo@host@host/", UriKind.Absolute }; yield return new object[] { @"http://userinfo\@host/", UriKind.Absolute }; yield return new object[] { "http://ho\0st/", UriKind.Absolute }; yield return new object[] { "http://ho[st/", UriKind.Absolute }; yield return new object[] { "http://ho]st/", UriKind.Absolute }; yield return new object[] { @"http://ho\st/", UriKind.Absolute }; yield return new object[] { "http://ho{st/", UriKind.Absolute }; yield return new object[] { "http://ho}st/", UriKind.Absolute }; // Invalid host yield return new object[] { @"http://domain\", UriKind.Absolute }; yield return new object[] { @"unknownscheme://domain\", UriKind.Absolute }; yield return new object[] { "unknown://h..9", UriKind.Absolute }; yield return new object[] { "unknown://h..-", UriKind.Absolute }; yield return new object[] { "unknown://h..", UriKind.Absolute }; yield return new object[] { "unknown://h.a;./", UriKind.Absolute }; // Invalid file yield return new object[] { "file:/a", UriKind.Absolute }; yield return new object[] { "C:adomain.com", UriKind.Absolute }; yield return new object[] { "C|adomain.com", UriKind.Absolute }; yield return new object[] { "!://domain.com", UriKind.Absolute }; yield return new object[] { "!|//domain.com", UriKind.Absolute }; yield return new object[] { "\u1234://domain.com", UriKind.Absolute }; yield return new object[] { "\u1234|//domain.com", UriKind.Absolute }; yield return new object[] { ".://domain.com", UriKind.Absolute }; // File is not rooted yield return new object[] { "file://a:a", UriKind.Absolute }; yield return new object[] { "file://a:", UriKind.Absolute }; // Implicit UNC has an empty host yield return new object[] { @"\\", UriKind.Absolute }; yield return new object[] { @"\\?query", UriKind.Absolute }; yield return new object[] { @"\\#fragment", UriKind.Absolute }; yield return new object[] { "\\\\?query\u1234", UriKind.Absolute }; yield return new object[] { "\\\\#fragment\u1234", UriKind.Absolute }; // Implicit UNC has port yield return new object[] { @"\\unchost:90", UriKind.Absolute }; yield return new object[] { @"\\unchost:90/path1/path2", UriKind.Absolute }; // Explicit UNC has port yield return new object[] { @"file://\\unchost:90", UriKind.Absolute }; yield return new object[] { @"file://\\unchost:90/path1/path2", UriKind.Absolute }; // File with host has port yield return new object[] { @"file://host:90", UriKind.Absolute }; yield return new object[] { @"file://host:90/path1/path2", UriKind.Absolute }; // Implicit UNC has userinfo yield return new object[] { @"\\userinfo@host", UriKind.Absolute }; yield return new object[] { @"\\userinfo@host/path1/path2", UriKind.Absolute }; // Explicit UNC has userinfo yield return new object[] { @"file://\\userinfo@host", UriKind.Absolute }; yield return new object[] { @"file://\\userinfo@host/path1/path2", UriKind.Absolute }; // File with host has userinfo yield return new object[] { @"file://userinfo@host", UriKind.Absolute }; yield return new object[] { @"file://userinfo@host/path1/path2", UriKind.Absolute }; // Implicit UNC with windows drive yield return new object[] { @"\\C:/", UriKind.Absolute }; yield return new object[] { @"\\C|/", UriKind.Absolute }; if (s_isWindowsSystem) // Valid Unix path { yield return new object[] { "//C:/", UriKind.Absolute }; yield return new object[] { "//C|/", UriKind.Absolute }; } yield return new object[] { @"\/C:/", UriKind.Absolute }; yield return new object[] { @"\/C|/", UriKind.Absolute }; if (s_isWindowsSystem) // Valid Unix path { yield return new object[] { @"/\C:/", UriKind.Absolute }; yield return new object[] { @"/\C|/", UriKind.Absolute }; } // Explicit UNC with invalid windows drive yield return new object[] { @"file://\\1:/", UriKind.Absolute }; yield return new object[] { @"file://\\ab:/", UriKind.Absolute }; // Unc host is invalid yield return new object[] { @"\\.", UriKind.Absolute }; yield return new object[] { @"\\server..", UriKind.Absolute }; // Domain name host is invalid yield return new object[] { "http://./", UriKind.Absolute }; yield return new object[] { "http://_a..a/", UriKind.Absolute }; yield return new object[] { "http://a..a/", UriKind.Absolute }; yield return new object[] { "unknownscheme://..a/", UriKind.Absolute }; yield return new object[] { "http://host" + (char)0, UriKind.Absolute }; yield return new object[] { "http://\u043F\u0440\u0438\u0432\u0435\u0442" + (char)0, UriKind.Absolute }; yield return new object[] { "http://%", UriKind.Absolute }; yield return new object[] { "http://@", UriKind.Absolute }; // Invalid IPv4 address yield return new object[] { "http://192..0.1", UriKind.Absolute }; yield return new object[] { "http://192.0.0.1;", UriKind.Absolute }; // Invalid IPv6 address yield return new object[] { "http://[", UriKind.Absolute }; yield return new object[] { "http://[?", UriKind.Absolute }; yield return new object[] { "http://[#", UriKind.Absolute }; yield return new object[] { "http://[/", UriKind.Absolute }; yield return new object[] { @"http://[\", UriKind.Absolute }; yield return new object[] { "http://[]", UriKind.Absolute }; yield return new object[] { "http://[a]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431%", UriKind.Absolute }; yield return new object[] { "http://[::1::1]", UriKind.Absolute }; yield return new object[] { "http://[11111:2222:3333::431]", UriKind.Absolute }; yield return new object[] { "http://[/12]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431/12/12]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431%16/]", UriKind.Absolute }; yield return new object[] { "http://[1111:2222:3333::431/123]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0.9/192.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0.9%192.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[001.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[a92.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[192.168.0]", UriKind.Absolute }; yield return new object[] { "http://[256.168.0.9]", UriKind.Absolute }; yield return new object[] { "http://[01.168.0.9]", UriKind.Absolute }; // Invalid port yield return new object[] { "http://domain:a", UriKind.Absolute }; yield return new object[] { "http://domain:-1", UriKind.Absolute }; yield return new object[] { "http://domain:65536", UriKind.Absolute }; yield return new object[] { "http://host:2147483648", UriKind.Absolute }; yield return new object[] { "http://host:80:80", UriKind.Absolute }; yield return new object[] { "uri://domain:a", UriKind.Absolute }; yield return new object[] { "uri://domain:65536", UriKind.Absolute }; yield return new object[] { "uri://a:a", UriKind.Absolute }; yield return new object[] { "uri://a:65536", UriKind.Absolute }; yield return new object[] { "uri://a:2147483648", UriKind.Absolute }; yield return new object[] { "uri://a:80:80", UriKind.Absolute }; if (PlatformDetection.IsNotInvariantGlobalization) { // Invalid unicode yield return new object[] { "http://\uD800", UriKind.Absolute }; yield return new object[] { "http://\uDC00", UriKind.Absolute }; } } [Theory] [MemberData(nameof(Create_String_Invalid_TestData))] public void Create_String_Invalid(string uriString, UriKind uriKind) { if (uriKind == UriKind.Absolute) { Assert.Throws<UriFormatException>(() => new Uri(uriString)); } Assert.Throws<UriFormatException>(() => new Uri(uriString, uriKind)); Uri uri; Assert.False(Uri.TryCreate(uriString, uriKind, out uri)); Assert.Null(uri); } private static void PerformAction(string uriString, UriKind uriKind, Action<Uri> action) { if (uriKind == UriKind.Absolute) { Uri uri = new Uri(uriString); action(uri); } Uri uri1 = new Uri(uriString, uriKind); action(uri1); Uri result = null; Assert.True(Uri.TryCreate(uriString, uriKind, out result)); action(result); } internal static void VerifyRelativeUri(Uri uri, string originalString, string toString) { Assert.Equal(originalString, uri.OriginalString); Assert.Equal(toString, uri.ToString()); Assert.False(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); Assert.Throws<InvalidOperationException>(() => uri.AbsoluteUri); Assert.Throws<InvalidOperationException>(() => uri.Scheme); Assert.Throws<InvalidOperationException>(() => uri.HostNameType); Assert.Throws<InvalidOperationException>(() => uri.Authority); Assert.Throws<InvalidOperationException>(() => uri.Host); Assert.Throws<InvalidOperationException>(() => uri.IdnHost); Assert.Throws<InvalidOperationException>(() => uri.DnsSafeHost); Assert.Throws<InvalidOperationException>(() => uri.Port); Assert.Throws<InvalidOperationException>(() => uri.AbsolutePath); Assert.Throws<InvalidOperationException>(() => uri.LocalPath); Assert.Throws<InvalidOperationException>(() => uri.PathAndQuery); Assert.Throws<InvalidOperationException>(() => uri.Segments); Assert.Throws<InvalidOperationException>(() => uri.Fragment); Assert.Throws<InvalidOperationException>(() => uri.Query); Assert.Throws<InvalidOperationException>(() => uri.UserInfo); Assert.Throws<InvalidOperationException>(() => uri.IsDefaultPort); Assert.Throws<InvalidOperationException>(() => uri.IsFile); Assert.Throws<InvalidOperationException>(() => uri.IsLoopback); Assert.Throws<InvalidOperationException>(() => uri.IsUnc); } } }
1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyBySelectedScalarWideningLowerAndSubtract.Vector64.UInt16.Vector64.UInt16.3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt16> _fld2; public Vector64<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt16> _clsVar2; private static Vector64<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt16> _fld2; private Vector64<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( _clsVar1, _clsVar2, _clsVar3, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector64<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)), AdvSimd.LoadVector64((UInt16*)(pClsVar3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) fixed (Vector64<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)), AdvSimd.LoadVector64((UInt16*)(&test._fld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt16> op2, Vector64<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningAndSubtract(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract)}<UInt32>(Vector128<UInt32>, Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt16[] inArray2, UInt16[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt16, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt16> _fld2; public Vector64<UInt16> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 testClass) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 3; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static UInt16[] _data3 = new UInt16[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt16> _clsVar2; private static Vector64<UInt16> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt16> _fld2; private Vector64<UInt16> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld3), ref Unsafe.As<UInt16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt16>), typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( _clsVar1, _clsVar2, _clsVar3, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt16>* pClsVar2 = &_clsVar2) fixed (Vector64<UInt16>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), AdvSimd.LoadVector64((UInt16*)(pClsVar2)), AdvSimd.LoadVector64((UInt16*)(pClsVar3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(op1, op2, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyBySelectedScalarWideningLowerAndSubtract_Vector64_UInt16_Vector64_UInt16_3(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt16>* pFld2 = &test._fld2) fixed (Vector64<UInt16>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(_fld1, _fld2, _fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt16>* pFld2 = &_fld2) fixed (Vector64<UInt16>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(pFld1)), AdvSimd.LoadVector64((UInt16*)(pFld2)), AdvSimd.LoadVector64((UInt16*)(pFld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract(test._fld1, test._fld2, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), AdvSimd.LoadVector64((UInt16*)(&test._fld2)), AdvSimd.LoadVector64((UInt16*)(&test._fld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt16> op2, Vector64<UInt16> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] inArray3 = new UInt16[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt16[] secondOp, UInt16[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyWideningAndSubtract(firstOp[i], secondOp[i], thirdOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyBySelectedScalarWideningLowerAndSubtract)}<UInt32>(Vector128<UInt32>, Vector64<UInt16>, Vector64<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Ceiling.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void CeilingSingle() { var test = new VectorUnaryOpTest__CeilingSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__CeilingSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__CeilingSingle testClass) { var result = Vector256.Ceiling(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar1; private Vector256<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__CeilingSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorUnaryOpTest__CeilingSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Ceiling( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), new Type[] { typeof(Vector256<Single>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Ceiling( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var result = Vector256.Ceiling(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__CeilingSingle(); var result = Vector256.Ceiling(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Ceiling(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Ceiling(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != MathF.Ceiling(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != MathF.Ceiling(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Ceiling)}<Single>(Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void CeilingSingle() { var test = new VectorUnaryOpTest__CeilingSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorUnaryOpTest__CeilingSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__CeilingSingle testClass) { var result = Vector256.Ceiling(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar1; private Vector256<Single> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__CeilingSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorUnaryOpTest__CeilingSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Ceiling( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), new Type[] { typeof(Vector256<Single>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Ceiling), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Ceiling( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var result = Vector256.Ceiling(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorUnaryOpTest__CeilingSingle(); var result = Vector256.Ceiling(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Ceiling(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Ceiling(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != MathF.Ceiling(firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != MathF.Ceiling(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Ceiling)}<Single>(Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/Methodical/casts/coverage/castclass_ldloc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace JitTest { internal class BaseClass { } internal class TestClass : BaseClass { private static bool Test_LDLOC(object _obj, bool flag) { object obj = _obj; try { TestClass inst; if (flag) { inst = (TestClass)obj; return inst != null; } else { inst = (TestClass)obj; return obj == null; } } catch (Exception X) { return !flag && X is InvalidCastException; } } private static int Main() { if (!Test_LDLOC(new TestClass(), true)) { Console.WriteLine("Failed => 101"); return 101; } if (!Test_LDLOC(new DerivedClass(), true)) { Console.WriteLine("Failed => 102"); return 102; } if (!Test_LDLOC(new BaseClass(), false)) { Console.WriteLine("Failed => 103"); return 103; } if (!Test_LDLOC(new OtherClass(), false)) { Console.WriteLine("Failed => 104"); return 104; } if (!Test_LDLOC(null, false)) { Console.WriteLine("Failed => 105"); return 105; } Console.WriteLine("Passed => 100"); return 100; } } internal class DerivedClass : TestClass { } internal class OtherClass { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace JitTest { internal class BaseClass { } internal class TestClass : BaseClass { private static bool Test_LDLOC(object _obj, bool flag) { object obj = _obj; try { TestClass inst; if (flag) { inst = (TestClass)obj; return inst != null; } else { inst = (TestClass)obj; return obj == null; } } catch (Exception X) { return !flag && X is InvalidCastException; } } private static int Main() { if (!Test_LDLOC(new TestClass(), true)) { Console.WriteLine("Failed => 101"); return 101; } if (!Test_LDLOC(new DerivedClass(), true)) { Console.WriteLine("Failed => 102"); return 102; } if (!Test_LDLOC(new BaseClass(), false)) { Console.WriteLine("Failed => 103"); return 103; } if (!Test_LDLOC(new OtherClass(), false)) { Console.WriteLine("Failed => 104"); return 104; } if (!Test_LDLOC(null, false)) { Console.WriteLine("Failed => 105"); return 105; } Console.WriteLine("Passed => 100"); return 100; } } internal class DerivedClass : TestClass { } internal class OtherClass { } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/baseservices/TieredCompilation/BasicTest_DefaultMode.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="BasicTest.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="BasicTest.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CoreTestAssembly/GenericTypes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; namespace GenericTypes { /// <summary> /// Generic class to be used for testing. /// </summary> /// <typeparam name="T"></typeparam> public abstract class GenericClass<T> { /// <summary> /// Purpose is to manipulate a method involving a generic parameter in its return type. /// </summary> public abstract T Foo(); /// <summary> /// Purpose is to manipulate a method involving a generic parameter in its parameter list. /// </summary> public void Bar(T a) { } ~GenericClass() { } } public class DerivedGenericClass<T> : GenericClass<T> { public override sealed T Foo() { return default(T); } } /// <summary> /// Generic class with multiple parameters to be used for testing. /// </summary> public class TwoParamGenericClass<T,U> { /// <summary> /// Purpose is to allow testing of the properties of non-generic methods on generic types /// </summary> public void NonGenericFunction() { } /// <summary> /// Purpose is to allow testing of the properties of generic methods on generic types /// </summary> public void GenericFunction<K, V>() { } } /// <summary> /// Non-generic type which has a generic method in it /// </summary> public class NonGenericClass { /// <summary> /// Purpose is to allow testing the properties of generic methods on nongeneric types /// </summary> /// <typeparam name="K"></typeparam> /// <typeparam name="V"></typeparam> public void GenericFunction<K, V>() { } } /// <summary> /// Generic structure with 3 fields all defined by type parameters /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GenStruct<A,B,C> { A _a; B _b; C _c; } public class GenClass<A> { #pragma warning disable 169 A _a; #pragma warning restore 169 } public class GenDerivedClass<A,B> : GenClass<A> { #pragma warning disable 169 B _b; #pragma warning restore 169 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; namespace GenericTypes { /// <summary> /// Generic class to be used for testing. /// </summary> /// <typeparam name="T"></typeparam> public abstract class GenericClass<T> { /// <summary> /// Purpose is to manipulate a method involving a generic parameter in its return type. /// </summary> public abstract T Foo(); /// <summary> /// Purpose is to manipulate a method involving a generic parameter in its parameter list. /// </summary> public void Bar(T a) { } ~GenericClass() { } } public class DerivedGenericClass<T> : GenericClass<T> { public override sealed T Foo() { return default(T); } } /// <summary> /// Generic class with multiple parameters to be used for testing. /// </summary> public class TwoParamGenericClass<T,U> { /// <summary> /// Purpose is to allow testing of the properties of non-generic methods on generic types /// </summary> public void NonGenericFunction() { } /// <summary> /// Purpose is to allow testing of the properties of generic methods on generic types /// </summary> public void GenericFunction<K, V>() { } } /// <summary> /// Non-generic type which has a generic method in it /// </summary> public class NonGenericClass { /// <summary> /// Purpose is to allow testing the properties of generic methods on nongeneric types /// </summary> /// <typeparam name="K"></typeparam> /// <typeparam name="V"></typeparam> public void GenericFunction<K, V>() { } } /// <summary> /// Generic structure with 3 fields all defined by type parameters /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GenStruct<A,B,C> { A _a; B _b; C _c; } public class GenClass<A> { #pragma warning disable 169 A _a; #pragma warning restore 169 } public class GenDerivedClass<A,B> : GenClass<A> { #pragma warning disable 169 B _b; #pragma warning restore 169 } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the HashSet class. /// </summary> public abstract class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T> { #region ISet<T> Helper Methods protected override bool ResetImplemented => true; protected override ModifyOperation ModifyEnumeratorThrows => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorThrows : (base.ModifyEnumeratorAllowed & ~(ModifyOperation.Remove | ModifyOperation.Clear)); protected override ModifyOperation ModifyEnumeratorAllowed => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorAllowed : ModifyOperation.Overwrite | ModifyOperation.Remove | ModifyOperation.Clear; protected override ISet<T> GenericISetFactory() { return new HashSet<T>(); } #endregion #region Constructors private static IEnumerable<int> NonSquares(int limit) { for (int i = 0; i != limit; ++i) { int root = (int)Math.Sqrt(i); if (i != root * root) yield return i; } } [Fact] public void HashSet_Generic_Constructor() { HashSet<T> set = new HashSet<T>(); Assert.Empty(set); } [Fact] public void HashSet_Generic_Constructor_IEqualityComparer() { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(comparer); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Fact] public void HashSet_Generic_Constructor_NullIEqualityComparer() { IEqualityComparer<T> comparer = null; HashSet<T> set = new HashSet<T>(comparer); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Theory] [MemberData(nameof(EnumerableTestData))] public void HashSet_Generic_Constructor_IEnumerable(EnumerableType enumerableType, int setLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { _ = setLength; _ = numberOfMatchingElements; IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, numberOfDuplicateElements); HashSet<T> set = new HashSet<T>(enumerable); Assert.True(set.SetEquals(enumerable)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_IEnumerable_WithManyDuplicates(int count) { IEnumerable<T> items = CreateEnumerable(EnumerableType.List, null, count, 0, 0); HashSet<T> hashSetFromDuplicates = new HashSet<T>(Enumerable.Range(0, 40).SelectMany(i => items).ToArray()); HashSet<T> hashSetFromNoDuplicates = new HashSet<T>(items); Assert.True(hashSetFromNoDuplicates.SetEquals(hashSetFromDuplicates)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_HashSet_SparselyFilled(int count) { HashSet<T> source = (HashSet<T>)CreateEnumerable(EnumerableType.HashSet, null, count, 0, 0); List<T> sourceElements = source.ToList(); foreach (int i in NonSquares(count)) source.Remove(sourceElements[i]);// Unevenly spaced survivors increases chance of catching any spacing-related bugs. HashSet<T> set = new HashSet<T>(source, GetIEqualityComparer()); Assert.True(set.SetEquals(source)); } [Fact] public void HashSet_Generic_Constructor_IEnumerable_Null() { Assert.Throws<ArgumentNullException>(() => new HashSet<T>((IEnumerable<T>)null)); Assert.Throws<ArgumentNullException>(() => new HashSet<T>((IEnumerable<T>)null, EqualityComparer<T>.Default)); } [Theory] [MemberData(nameof(EnumerableTestData))] public void HashSet_Generic_Constructor_IEnumerable_IEqualityComparer(EnumerableType enumerableType, int setLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { _ = setLength; _ = numberOfMatchingElements; _ = numberOfDuplicateElements; IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, 0); HashSet<T> set = new HashSet<T>(enumerable, GetIEqualityComparer()); Assert.True(set.SetEquals(enumerable)); } #endregion #region RemoveWhere [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_AllElements(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int removedCount = set.RemoveWhere((value) => { return true; }); Assert.Equal(setLength, removedCount); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_NoElements(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int removedCount = set.RemoveWhere((value) => { return false; }); Assert.Equal(0, removedCount); Assert.Equal(setLength, set.Count); } [Fact] public void HashSet_Generic_RemoveWhere_NewObject() // Regression Dev10_624201 { object[] array = new object[2]; object obj = new object(); HashSet<object> set = new HashSet<object>(); set.Add(obj); set.Remove(obj); foreach (object o in set) { } set.CopyTo(array, 0, 2); set.RemoveWhere((element) => { return false; }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_NullMatchPredicate(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); Assert.Throws<ArgumentNullException>(() => set.RemoveWhere(null)); } #endregion #region TrimExcess [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_OnValidSetThatHasntBeenRemovedFrom(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_Repeatedly(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); List<T> expected = set.ToList(); set.TrimExcess(); set.TrimExcess(); set.TrimExcess(); Assert.True(set.SetEquals(expected)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterRemovingOneElement(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); List<T> expected = set.ToList(); T elementToRemove = set.ElementAt(0); set.TrimExcess(); Assert.True(set.Remove(elementToRemove)); expected.Remove(elementToRemove); set.TrimExcess(); Assert.True(set.SetEquals(expected)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterClearingAndAddingSomeElementsBack(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); set.Clear(); set.TrimExcess(); Assert.Equal(0, set.Count); AddToCollection(set, setLength / 10); set.TrimExcess(); Assert.Equal(setLength / 10, set.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); set.Clear(); set.TrimExcess(); Assert.Equal(0, set.Count); AddToCollection(set, setLength); set.TrimExcess(); Assert.Equal(setLength, set.Count); } } #endregion #region CopyTo [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_CopyTo_NegativeCount_ThrowsArgumentOutOfRangeException(int count) { HashSet<T> set = (HashSet<T>)GenericISetFactory(count); T[] arr = new T[count]; Assert.Throws<ArgumentOutOfRangeException>(() => set.CopyTo(arr, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => set.CopyTo(arr, 0, int.MinValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_CopyTo_NoIndexDefaultsToZero(int count) { HashSet<T> set = (HashSet<T>)GenericISetFactory(count); T[] arr1 = new T[count]; T[] arr2 = new T[count]; set.CopyTo(arr1); set.CopyTo(arr2, 0); Assert.True(arr1.SequenceEqual(arr2)); } #endregion #region CreateSetComparer [Fact] public void SetComparer_SetEqualsTests() { List<T> objects = new List<T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet1 = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet2 = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[3], objects[4], objects[5] }, new HashSet<T> { objects[0], objects[1], objects[2] } }; Assert.False(noComparerSet.SetEquals(set)); Assert.True(comparerSet1.SetEquals(set)); Assert.True(comparerSet2.SetEquals(set)); } [Fact] public void SetComparer_SequenceEqualTests() { List<T> objects = new List<T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; Assert.False(noComparerSet.SequenceEqual(set)); Assert.True(noComparerSet.SequenceEqual(set, HashSet<T>.CreateSetComparer())); Assert.False(comparerSet.SequenceEqual(set)); } #endregion [Fact] public void CanBeCastedToISet() { HashSet<T> set = new HashSet<T>(); ISet<T> iset = (set as ISet<T>); Assert.NotNull(iset); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int(int capacity) { HashSet<T> set = new HashSet<T>(capacity); Assert.Equal(0, set.Count); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity) { HashSet<T> set = new HashSet<T>(capacity); AddToCollection(set, capacity); Assert.Equal(capacity, set.Count); AddToCollection(set, capacity + 1); Assert.Equal(capacity + 1, set.Count); } [Fact] public void HashSet_Generic_Constructor_Capacity_ToNextPrimeNumber() { // Highest pre-computed number + 1. const int Capacity = 7199370; var set = new HashSet<T>(Capacity); // Assert that the HashTable's capacity is set to the descendant prime number of the given one. const int NextPrime = 7199371; Assert.Equal(NextPrime, set.EnsureCapacity(0)); } [Fact] public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity) { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(capacity, comparer); Assert.Equal(0, set.Count); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity) { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(capacity, comparer); AddToCollection(set, capacity); Assert.Equal(capacity, set.Count); AddToCollection(set, capacity + 1); Assert.Equal(capacity + 1, set.Count); } [Fact] public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException() { IEqualityComparer<T> comparer = GetIEqualityComparer(); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer)); } #region TryGetValue [Fact] public void HashSet_Generic_TryGetValue_Contains() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(1); T actualValue; Assert.True(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(value, actualValue); if (!typeof(T).IsValueType) { Assert.Same((object)value, (object)actualValue); } } [Fact] public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(1); T actualValue = CreateT(2); Assert.True(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(value, actualValue); if (!typeof(T).IsValueType) { Assert.Same((object)value, (object)actualValue); } } [Fact] public void HashSet_Generic_TryGetValue_NotContains() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(2); T actualValue; Assert.False(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(default(T), actualValue); } [Fact] public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(2); T actualValue = equalValue; Assert.False(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(default(T), actualValue); } #endregion #region EnsureCapacity [Theory] [MemberData(nameof(ValidCollectionSizes))] public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength) { HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength)); var capacity = set.EnsureCapacity(0); IEnumerator valuesEnum = set.GetEnumerator(); IEnumerator valuesListEnum = new List<T>(set).GetEnumerator(); set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration while (valuesEnum.MoveNext()) { valuesListEnum.MoveNext(); Assert.Equal(valuesListEnum.Current, valuesEnum.Current); } } [Fact] public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws() { var set = new HashSet<T>(); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1)); } [Fact] public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero() { var set = new HashSet<T>(); Assert.Equal(0, set.EnsureCapacity(0)); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity) { var set = new HashSet<T>(); Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue); } [Theory] [InlineData(3)] [InlineData(7)] public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity) { HashSet<T> set; // assert capacity remains the same when ensuring a capacity smaller or equal than existing for (int i = 0; i <= currentCapacity; i++) { set = new HashSet<T>(currentCapacity); Assert.Equal(currentCapacity, set.EnsureCapacity(i)); } } [Theory] [InlineData(7)] [InlineData(89)] public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity) { var set = new HashSet<T>(capacity); Assert.Equal(capacity, set.EnsureCapacity(capacity)); set = (HashSet<T>)GenericISetFactory(capacity); Assert.Equal(capacity, set.EnsureCapacity(capacity)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int capacity = set.EnsureCapacity(0); Assert.Equal(capacity, set.EnsureCapacity(0)); set = (HashSet<T>)GenericISetFactory(setLength); capacity = set.EnsureCapacity(setLength); Assert.Equal(capacity, set.EnsureCapacity(setLength)); set = (HashSet<T>)GenericISetFactory(setLength); capacity = set.EnsureCapacity(setLength + 1); Assert.Equal(capacity, set.EnsureCapacity(setLength + 1)); } [Theory] [InlineData(1)] [InlineData(5)] [InlineData(7)] [InlineData(8)] public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue); } [Theory] [InlineData(7)] [InlineData(20)] public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); // get current capacity int currentCapacity = set.EnsureCapacity(0); // assert we can update to a larger capacity int newCapacity = set.EnsureCapacity(currentCapacity * 2); Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue); } [Fact] public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested() { var set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(17)); set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(15)); set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(13)); } [Theory] [InlineData(2)] [InlineData(10)] public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); // Remove the first element to ensure we have a free list. Assert.True(set.Remove(set.ElementAt(0))); int currentCapacity = set.EnsureCapacity(0); Assert.True(currentCapacity > 0); int newCapacity = set.EnsureCapacity(currentCapacity + 1); Assert.True(newCapacity > currentCapacity); } #endregion #region Remove [Theory] [MemberData(nameof(ValidPositiveCollectionSizes))] public void Remove_NonDefaultComparer_ComparerUsed(int capacity) { var c = new TrackingEqualityComparer<T>(); var set = new HashSet<T>(capacity, c); AddToCollection(set, capacity); T first = set.First(); c.EqualsCalls = 0; c.GetHashCodeCalls = 0; Assert.Equal(capacity, set.Count); set.Remove(first); Assert.Equal(capacity - 1, set.Count); Assert.InRange(c.EqualsCalls, 1, int.MaxValue); Assert.InRange(c.GetHashCodeCalls, 1, int.MaxValue); } #endregion #region Serialization [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] public void ComparerSerialization() { // Strings switch between randomized and non-randomized comparers, // however this should never be observable externally. TestComparerSerialization(EqualityComparer<string>.Default); // OrdinalCaseSensitiveComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.Ordinal, "System.OrdinalComparer"); // OrdinalIgnoreCaseComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.OrdinalIgnoreCase, "System.OrdinalComparer"); TestComparerSerialization(StringComparer.CurrentCulture); TestComparerSerialization(StringComparer.CurrentCultureIgnoreCase); TestComparerSerialization(StringComparer.InvariantCulture); TestComparerSerialization(StringComparer.InvariantCultureIgnoreCase); // Check other types while here, IEquatable valuetype, nullable valuetype, and non IEquatable object TestComparerSerialization(EqualityComparer<int>.Default); TestComparerSerialization(EqualityComparer<int?>.Default); TestComparerSerialization(EqualityComparer<object>.Default); static void TestComparerSerialization<TCompared>(IEqualityComparer<TCompared> equalityComparer, string internalTypeName = null) { var bf = new BinaryFormatter(); var s = new MemoryStream(); var dict = new HashSet<TCompared>(equalityComparer); Assert.Same(equalityComparer, dict.Comparer); bf.Serialize(s, dict); s.Position = 0; dict = (HashSet<TCompared>)bf.Deserialize(s); if (internalTypeName == null) { Assert.IsType(equalityComparer.GetType(), dict.Comparer); } else { Assert.Equal(internalTypeName, dict.Comparer.GetType().ToString()); } Assert.True(equalityComparer.Equals(dict.Comparer)); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the HashSet class. /// </summary> public abstract class HashSet_Generic_Tests<T> : ISet_Generic_Tests<T> { #region ISet<T> Helper Methods protected override bool ResetImplemented => true; protected override ModifyOperation ModifyEnumeratorThrows => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorThrows : (base.ModifyEnumeratorAllowed & ~(ModifyOperation.Remove | ModifyOperation.Clear)); protected override ModifyOperation ModifyEnumeratorAllowed => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorAllowed : ModifyOperation.Overwrite | ModifyOperation.Remove | ModifyOperation.Clear; protected override ISet<T> GenericISetFactory() { return new HashSet<T>(); } #endregion #region Constructors private static IEnumerable<int> NonSquares(int limit) { for (int i = 0; i != limit; ++i) { int root = (int)Math.Sqrt(i); if (i != root * root) yield return i; } } [Fact] public void HashSet_Generic_Constructor() { HashSet<T> set = new HashSet<T>(); Assert.Empty(set); } [Fact] public void HashSet_Generic_Constructor_IEqualityComparer() { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(comparer); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Fact] public void HashSet_Generic_Constructor_NullIEqualityComparer() { IEqualityComparer<T> comparer = null; HashSet<T> set = new HashSet<T>(comparer); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Theory] [MemberData(nameof(EnumerableTestData))] public void HashSet_Generic_Constructor_IEnumerable(EnumerableType enumerableType, int setLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { _ = setLength; _ = numberOfMatchingElements; IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, numberOfDuplicateElements); HashSet<T> set = new HashSet<T>(enumerable); Assert.True(set.SetEquals(enumerable)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_IEnumerable_WithManyDuplicates(int count) { IEnumerable<T> items = CreateEnumerable(EnumerableType.List, null, count, 0, 0); HashSet<T> hashSetFromDuplicates = new HashSet<T>(Enumerable.Range(0, 40).SelectMany(i => items).ToArray()); HashSet<T> hashSetFromNoDuplicates = new HashSet<T>(items); Assert.True(hashSetFromNoDuplicates.SetEquals(hashSetFromDuplicates)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_HashSet_SparselyFilled(int count) { HashSet<T> source = (HashSet<T>)CreateEnumerable(EnumerableType.HashSet, null, count, 0, 0); List<T> sourceElements = source.ToList(); foreach (int i in NonSquares(count)) source.Remove(sourceElements[i]);// Unevenly spaced survivors increases chance of catching any spacing-related bugs. HashSet<T> set = new HashSet<T>(source, GetIEqualityComparer()); Assert.True(set.SetEquals(source)); } [Fact] public void HashSet_Generic_Constructor_IEnumerable_Null() { Assert.Throws<ArgumentNullException>(() => new HashSet<T>((IEnumerable<T>)null)); Assert.Throws<ArgumentNullException>(() => new HashSet<T>((IEnumerable<T>)null, EqualityComparer<T>.Default)); } [Theory] [MemberData(nameof(EnumerableTestData))] public void HashSet_Generic_Constructor_IEnumerable_IEqualityComparer(EnumerableType enumerableType, int setLength, int enumerableLength, int numberOfMatchingElements, int numberOfDuplicateElements) { _ = setLength; _ = numberOfMatchingElements; _ = numberOfDuplicateElements; IEnumerable<T> enumerable = CreateEnumerable(enumerableType, null, enumerableLength, 0, 0); HashSet<T> set = new HashSet<T>(enumerable, GetIEqualityComparer()); Assert.True(set.SetEquals(enumerable)); } #endregion #region RemoveWhere [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_AllElements(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int removedCount = set.RemoveWhere((value) => { return true; }); Assert.Equal(setLength, removedCount); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_NoElements(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int removedCount = set.RemoveWhere((value) => { return false; }); Assert.Equal(0, removedCount); Assert.Equal(setLength, set.Count); } [Fact] public void HashSet_Generic_RemoveWhere_NewObject() // Regression Dev10_624201 { object[] array = new object[2]; object obj = new object(); HashSet<object> set = new HashSet<object>(); set.Add(obj); set.Remove(obj); foreach (object o in set) { } set.CopyTo(array, 0, 2); set.RemoveWhere((element) => { return false; }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_RemoveWhere_NullMatchPredicate(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); Assert.Throws<ArgumentNullException>(() => set.RemoveWhere(null)); } #endregion #region TrimExcess [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_OnValidSetThatHasntBeenRemovedFrom(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_Repeatedly(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); List<T> expected = set.ToList(); set.TrimExcess(); set.TrimExcess(); set.TrimExcess(); Assert.True(set.SetEquals(expected)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterRemovingOneElement(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); List<T> expected = set.ToList(); T elementToRemove = set.ElementAt(0); set.TrimExcess(); Assert.True(set.Remove(elementToRemove)); expected.Remove(elementToRemove); set.TrimExcess(); Assert.True(set.SetEquals(expected)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterClearingAndAddingSomeElementsBack(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); set.Clear(); set.TrimExcess(); Assert.Equal(0, set.Count); AddToCollection(set, setLength / 10); set.TrimExcess(); Assert.Equal(setLength / 10, set.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_TrimExcess_AfterClearingAndAddingAllElementsBack(int setLength) { if (setLength > 0) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); set.TrimExcess(); set.Clear(); set.TrimExcess(); Assert.Equal(0, set.Count); AddToCollection(set, setLength); set.TrimExcess(); Assert.Equal(setLength, set.Count); } } #endregion #region CopyTo [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_CopyTo_NegativeCount_ThrowsArgumentOutOfRangeException(int count) { HashSet<T> set = (HashSet<T>)GenericISetFactory(count); T[] arr = new T[count]; Assert.Throws<ArgumentOutOfRangeException>(() => set.CopyTo(arr, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => set.CopyTo(arr, 0, int.MinValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_CopyTo_NoIndexDefaultsToZero(int count) { HashSet<T> set = (HashSet<T>)GenericISetFactory(count); T[] arr1 = new T[count]; T[] arr2 = new T[count]; set.CopyTo(arr1); set.CopyTo(arr2, 0); Assert.True(arr1.SequenceEqual(arr2)); } #endregion #region CreateSetComparer [Fact] public void SetComparer_SetEqualsTests() { List<T> objects = new List<T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet1 = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet2 = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[3], objects[4], objects[5] }, new HashSet<T> { objects[0], objects[1], objects[2] } }; Assert.False(noComparerSet.SetEquals(set)); Assert.True(comparerSet1.SetEquals(set)); Assert.True(comparerSet2.SetEquals(set)); } [Fact] public void SetComparer_SequenceEqualTests() { List<T> objects = new List<T>() { CreateT(1), CreateT(2), CreateT(3), CreateT(4), CreateT(5), CreateT(6) }; var set = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var noComparerSet = new HashSet<HashSet<T>>() { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; var comparerSet = new HashSet<HashSet<T>>(HashSet<T>.CreateSetComparer()) { new HashSet<T> { objects[0], objects[1], objects[2] }, new HashSet<T> { objects[3], objects[4], objects[5] } }; Assert.False(noComparerSet.SequenceEqual(set)); Assert.True(noComparerSet.SequenceEqual(set, HashSet<T>.CreateSetComparer())); Assert.False(comparerSet.SequenceEqual(set)); } #endregion [Fact] public void CanBeCastedToISet() { HashSet<T> set = new HashSet<T>(); ISet<T> iset = (set as ISet<T>); Assert.NotNull(iset); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int(int capacity) { HashSet<T> set = new HashSet<T>(capacity); Assert.Equal(0, set.Count); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_AddUpToAndBeyondCapacity(int capacity) { HashSet<T> set = new HashSet<T>(capacity); AddToCollection(set, capacity); Assert.Equal(capacity, set.Count); AddToCollection(set, capacity + 1); Assert.Equal(capacity + 1, set.Count); } [Fact] public void HashSet_Generic_Constructor_Capacity_ToNextPrimeNumber() { // Highest pre-computed number + 1. const int Capacity = 7199370; var set = new HashSet<T>(Capacity); // Assert that the HashTable's capacity is set to the descendant prime number of the given one. const int NextPrime = 7199371; Assert.Equal(NextPrime, set.EnsureCapacity(0)); } [Fact] public void HashSet_Generic_Constructor_int_Negative_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_IEqualityComparer(int capacity) { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(capacity, comparer); Assert.Equal(0, set.Count); if (comparer == null) Assert.Equal(EqualityComparer<T>.Default, set.Comparer); else Assert.Equal(comparer, set.Comparer); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void HashSet_Generic_Constructor_int_IEqualityComparer_AddUpToAndBeyondCapacity(int capacity) { IEqualityComparer<T> comparer = GetIEqualityComparer(); HashSet<T> set = new HashSet<T>(capacity, comparer); AddToCollection(set, capacity); Assert.Equal(capacity, set.Count); AddToCollection(set, capacity + 1); Assert.Equal(capacity + 1, set.Count); } [Fact] public void HashSet_Generic_Constructor_int_IEqualityComparer_Negative_ThrowsArgumentOutOfRangeException() { IEqualityComparer<T> comparer = GetIEqualityComparer(); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(-1, comparer)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new HashSet<T>(int.MinValue, comparer)); } #region TryGetValue [Fact] public void HashSet_Generic_TryGetValue_Contains() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(1); T actualValue; Assert.True(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(value, actualValue); if (!typeof(T).IsValueType) { Assert.Same((object)value, (object)actualValue); } } [Fact] public void HashSet_Generic_TryGetValue_Contains_OverwriteOutputParam() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(1); T actualValue = CreateT(2); Assert.True(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(value, actualValue); if (!typeof(T).IsValueType) { Assert.Same((object)value, (object)actualValue); } } [Fact] public void HashSet_Generic_TryGetValue_NotContains() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(2); T actualValue; Assert.False(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(default(T), actualValue); } [Fact] public void HashSet_Generic_TryGetValue_NotContains_OverwriteOutputParam() { T value = CreateT(1); HashSet<T> set = new HashSet<T> { value }; T equalValue = CreateT(2); T actualValue = equalValue; Assert.False(set.TryGetValue(equalValue, out actualValue)); Assert.Equal(default(T), actualValue); } #endregion #region EnsureCapacity [Theory] [MemberData(nameof(ValidCollectionSizes))] public void EnsureCapacity_Generic_RequestingLargerCapacity_DoesNotInvalidateEnumeration(int setLength) { HashSet<T> set = (HashSet<T>)(GenericISetFactory(setLength)); var capacity = set.EnsureCapacity(0); IEnumerator valuesEnum = set.GetEnumerator(); IEnumerator valuesListEnum = new List<T>(set).GetEnumerator(); set.EnsureCapacity(capacity + 1); // Verify EnsureCapacity does not invalidate enumeration while (valuesEnum.MoveNext()) { valuesListEnum.MoveNext(); Assert.Equal(valuesListEnum.Current, valuesEnum.Current); } } [Fact] public void EnsureCapacity_Generic_NegativeCapacityRequested_Throws() { var set = new HashSet<T>(); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => set.EnsureCapacity(-1)); } [Fact] public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedZero_ReturnsZero() { var set = new HashSet<T>(); Assert.Equal(0, set.EnsureCapacity(0)); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void EnsureCapacity_Generic_HashsetNotInitialized_RequestedNonZero_CapacityIsSetToAtLeastTheRequested(int requestedCapacity) { var set = new HashSet<T>(); Assert.InRange(set.EnsureCapacity(requestedCapacity), requestedCapacity, int.MaxValue); } [Theory] [InlineData(3)] [InlineData(7)] public void EnsureCapacity_Generic_RequestedCapacitySmallerThanCurrent_CapacityUnchanged(int currentCapacity) { HashSet<T> set; // assert capacity remains the same when ensuring a capacity smaller or equal than existing for (int i = 0; i <= currentCapacity; i++) { set = new HashSet<T>(currentCapacity); Assert.Equal(currentCapacity, set.EnsureCapacity(i)); } } [Theory] [InlineData(7)] [InlineData(89)] public void EnsureCapacity_Generic_ExistingCapacityRequested_SameValueReturned(int capacity) { var set = new HashSet<T>(capacity); Assert.Equal(capacity, set.EnsureCapacity(capacity)); set = (HashSet<T>)GenericISetFactory(capacity); Assert.Equal(capacity, set.EnsureCapacity(capacity)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] public void EnsureCapacity_Generic_EnsureCapacityCalledTwice_ReturnsSameValue(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); int capacity = set.EnsureCapacity(0); Assert.Equal(capacity, set.EnsureCapacity(0)); set = (HashSet<T>)GenericISetFactory(setLength); capacity = set.EnsureCapacity(setLength); Assert.Equal(capacity, set.EnsureCapacity(setLength)); set = (HashSet<T>)GenericISetFactory(setLength); capacity = set.EnsureCapacity(setLength + 1); Assert.Equal(capacity, set.EnsureCapacity(setLength + 1)); } [Theory] [InlineData(1)] [InlineData(5)] [InlineData(7)] [InlineData(8)] public void EnsureCapacity_Generic_HashsetNotEmpty_RequestedSmallerThanCount_ReturnsAtLeastSizeOfCount(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); Assert.InRange(set.EnsureCapacity(setLength - 1), setLength, int.MaxValue); } [Theory] [InlineData(7)] [InlineData(20)] public void EnsureCapacity_Generic_HashsetNotEmpty_SetsToAtLeastTheRequested(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); // get current capacity int currentCapacity = set.EnsureCapacity(0); // assert we can update to a larger capacity int newCapacity = set.EnsureCapacity(currentCapacity * 2); Assert.InRange(newCapacity, currentCapacity * 2, int.MaxValue); } [Fact] public void EnsureCapacity_Generic_CapacityIsSetToPrimeNumberLargerOrEqualToRequested() { var set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(17)); set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(15)); set = new HashSet<T>(); Assert.Equal(17, set.EnsureCapacity(13)); } [Theory] [InlineData(2)] [InlineData(10)] public void EnsureCapacity_Generic_GrowCapacityWithFreeList(int setLength) { HashSet<T> set = (HashSet<T>)GenericISetFactory(setLength); // Remove the first element to ensure we have a free list. Assert.True(set.Remove(set.ElementAt(0))); int currentCapacity = set.EnsureCapacity(0); Assert.True(currentCapacity > 0); int newCapacity = set.EnsureCapacity(currentCapacity + 1); Assert.True(newCapacity > currentCapacity); } #endregion #region Remove [Theory] [MemberData(nameof(ValidPositiveCollectionSizes))] public void Remove_NonDefaultComparer_ComparerUsed(int capacity) { var c = new TrackingEqualityComparer<T>(); var set = new HashSet<T>(capacity, c); AddToCollection(set, capacity); T first = set.First(); c.EqualsCalls = 0; c.GetHashCodeCalls = 0; Assert.Equal(capacity, set.Count); set.Remove(first); Assert.Equal(capacity - 1, set.Count); Assert.InRange(c.EqualsCalls, 1, int.MaxValue); Assert.InRange(c.GetHashCodeCalls, 1, int.MaxValue); } #endregion #region Serialization [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))] public void ComparerSerialization() { // Strings switch between randomized and non-randomized comparers, // however this should never be observable externally. TestComparerSerialization(EqualityComparer<string>.Default); // OrdinalCaseSensitiveComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.Ordinal, "System.OrdinalComparer"); // OrdinalIgnoreCaseComparer is internal and (de)serializes as OrdinalComparer TestComparerSerialization(StringComparer.OrdinalIgnoreCase, "System.OrdinalComparer"); TestComparerSerialization(StringComparer.CurrentCulture); TestComparerSerialization(StringComparer.CurrentCultureIgnoreCase); TestComparerSerialization(StringComparer.InvariantCulture); TestComparerSerialization(StringComparer.InvariantCultureIgnoreCase); // Check other types while here, IEquatable valuetype, nullable valuetype, and non IEquatable object TestComparerSerialization(EqualityComparer<int>.Default); TestComparerSerialization(EqualityComparer<int?>.Default); TestComparerSerialization(EqualityComparer<object>.Default); static void TestComparerSerialization<TCompared>(IEqualityComparer<TCompared> equalityComparer, string internalTypeName = null) { var bf = new BinaryFormatter(); var s = new MemoryStream(); var dict = new HashSet<TCompared>(equalityComparer); Assert.Same(equalityComparer, dict.Comparer); bf.Serialize(s, dict); s.Position = 0; dict = (HashSet<TCompared>)bf.Deserialize(s); if (internalTypeName == null) { Assert.IsType(equalityComparer.GetType(), dict.Comparer); } else { Assert.Equal(internalTypeName, dict.Comparer.GetType().ToString()); } Assert.True(equalityComparer.Equals(dict.Comparer)); } } #endregion } }
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/tests/JIT/CodeGenBringUpTests/StaticCalls_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="StaticCalls.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="StaticCalls.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,179
Use RegexGenerator in applicable tests
Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
Clockwork-Muse
2022-03-04T03:46:20Z
2022-03-07T21:04:10Z
f5ebdf8d128a3b5eb5b9e2fc5a2d81b3cfeb8931
8d12bc107bc3a71630861f6a51631a2cfcd1504c
Use RegexGenerator in applicable tests. Use RegexGenerator where possible in tests. Also added to `System.Private.DataContractSerialization`
./src/mono/System.Private.CoreLib/src/Mono/RuntimeHandles.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Runtime.CompilerServices; namespace Mono { internal unsafe struct RuntimeClassHandle : IEquatable<RuntimeClassHandle> { private readonly RuntimeStructs.MonoClass* value; internal RuntimeClassHandle(RuntimeStructs.MonoClass* value) { this.value = value; } internal RuntimeClassHandle(IntPtr ptr) { this.value = (RuntimeStructs.MonoClass*)ptr; } internal RuntimeStructs.MonoClass* Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimeClassHandle)obj).Value; } public override int GetHashCode() => ((IntPtr)value).GetHashCode(); public bool Equals(RuntimeClassHandle handle) { return value == handle.Value; } public static bool operator ==(RuntimeClassHandle left, object? right) { return right != null && right is RuntimeClassHandle rch && left.Equals(rch); } public static bool operator !=(RuntimeClassHandle left, object? right) { return !(left == right); } public static bool operator ==(object? left, RuntimeClassHandle right) { return left != null && left is RuntimeClassHandle rch && rch.Equals(right); } public static bool operator !=(object? left, RuntimeClassHandle right) { return !(left == right); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetTypeFromClass(RuntimeStructs.MonoClass* klass); internal RuntimeTypeHandle GetTypeHandle() => new RuntimeTypeHandle(GetTypeFromClass(value)); } internal unsafe struct RuntimeRemoteClassHandle { private readonly RuntimeStructs.RemoteClass* value; internal RuntimeRemoteClassHandle(RuntimeStructs.RemoteClass* value) { this.value = value; } internal RuntimeClassHandle ProxyClass { get { return new RuntimeClassHandle(value->proxy_class); } } } internal unsafe struct RuntimeGenericParamInfoHandle { private readonly RuntimeStructs.GenericParamInfo* value; internal RuntimeGenericParamInfoHandle(RuntimeStructs.GenericParamInfo* value) { this.value = value; } internal RuntimeGenericParamInfoHandle(IntPtr ptr) { this.value = (RuntimeStructs.GenericParamInfo*)ptr; } internal Type[] Constraints => GetConstraints(); internal GenericParameterAttributes Attributes => (GenericParameterAttributes)value->flags; private Type[] GetConstraints() { int n = GetConstraintsCount(); var a = new Type[n]; for (int i = 0; i < n; i++) { RuntimeClassHandle c = new RuntimeClassHandle(value->constraints[i]); a[i] = Type.GetTypeFromHandle(c.GetTypeHandle())!; } return a; } private int GetConstraintsCount() { int i = 0; RuntimeStructs.MonoClass** p = value->constraints; while (p != null && *p != null) { p++; i++; } return i; } } internal struct RuntimeEventHandle : IEquatable<RuntimeEventHandle> { private readonly IntPtr value; internal RuntimeEventHandle(IntPtr v) { value = v; } public IntPtr Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimeEventHandle)obj).Value; } public bool Equals(RuntimeEventHandle handle) { return value == handle.Value; } public override int GetHashCode() { return value.GetHashCode(); } public static bool operator ==(RuntimeEventHandle left, RuntimeEventHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeEventHandle left, RuntimeEventHandle right) { return !left.Equals(right); } } internal struct RuntimePropertyHandle : IEquatable<RuntimePropertyHandle> { private readonly IntPtr value; internal RuntimePropertyHandle(IntPtr v) { value = v; } public IntPtr Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimePropertyHandle)obj).Value; } public bool Equals(RuntimePropertyHandle handle) { return value == handle.Value; } public override int GetHashCode() { return value.GetHashCode(); } public static bool operator ==(RuntimePropertyHandle left, RuntimePropertyHandle right) { return left.Equals(right); } public static bool operator !=(RuntimePropertyHandle left, RuntimePropertyHandle right) { return !left.Equals(right); } } internal unsafe struct RuntimeGPtrArrayHandle { private RuntimeStructs.GPtrArray* value; internal RuntimeGPtrArrayHandle(RuntimeStructs.GPtrArray* value) { this.value = value; } internal RuntimeGPtrArrayHandle(IntPtr ptr) { this.value = (RuntimeStructs.GPtrArray*)ptr; } internal int Length => value->len; internal IntPtr this[int i] => Lookup(i); internal IntPtr Lookup(int i) { if (i >= 0 && i < Length) { return value->data[i]; } else throw new IndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GPtrArrayFree(RuntimeStructs.GPtrArray* value); internal static void DestroyAndFree(ref RuntimeGPtrArrayHandle h) { GPtrArrayFree(h.value); h.value = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; using System.Runtime.CompilerServices; namespace Mono { internal unsafe struct RuntimeClassHandle : IEquatable<RuntimeClassHandle> { private readonly RuntimeStructs.MonoClass* value; internal RuntimeClassHandle(RuntimeStructs.MonoClass* value) { this.value = value; } internal RuntimeClassHandle(IntPtr ptr) { this.value = (RuntimeStructs.MonoClass*)ptr; } internal RuntimeStructs.MonoClass* Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimeClassHandle)obj).Value; } public override int GetHashCode() => ((IntPtr)value).GetHashCode(); public bool Equals(RuntimeClassHandle handle) { return value == handle.Value; } public static bool operator ==(RuntimeClassHandle left, object? right) { return right != null && right is RuntimeClassHandle rch && left.Equals(rch); } public static bool operator !=(RuntimeClassHandle left, object? right) { return !(left == right); } public static bool operator ==(object? left, RuntimeClassHandle right) { return left != null && left is RuntimeClassHandle rch && rch.Equals(right); } public static bool operator !=(object? left, RuntimeClassHandle right) { return !(left == right); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern unsafe IntPtr GetTypeFromClass(RuntimeStructs.MonoClass* klass); internal RuntimeTypeHandle GetTypeHandle() => new RuntimeTypeHandle(GetTypeFromClass(value)); } internal unsafe struct RuntimeRemoteClassHandle { private readonly RuntimeStructs.RemoteClass* value; internal RuntimeRemoteClassHandle(RuntimeStructs.RemoteClass* value) { this.value = value; } internal RuntimeClassHandle ProxyClass { get { return new RuntimeClassHandle(value->proxy_class); } } } internal unsafe struct RuntimeGenericParamInfoHandle { private readonly RuntimeStructs.GenericParamInfo* value; internal RuntimeGenericParamInfoHandle(RuntimeStructs.GenericParamInfo* value) { this.value = value; } internal RuntimeGenericParamInfoHandle(IntPtr ptr) { this.value = (RuntimeStructs.GenericParamInfo*)ptr; } internal Type[] Constraints => GetConstraints(); internal GenericParameterAttributes Attributes => (GenericParameterAttributes)value->flags; private Type[] GetConstraints() { int n = GetConstraintsCount(); var a = new Type[n]; for (int i = 0; i < n; i++) { RuntimeClassHandle c = new RuntimeClassHandle(value->constraints[i]); a[i] = Type.GetTypeFromHandle(c.GetTypeHandle())!; } return a; } private int GetConstraintsCount() { int i = 0; RuntimeStructs.MonoClass** p = value->constraints; while (p != null && *p != null) { p++; i++; } return i; } } internal struct RuntimeEventHandle : IEquatable<RuntimeEventHandle> { private readonly IntPtr value; internal RuntimeEventHandle(IntPtr v) { value = v; } public IntPtr Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimeEventHandle)obj).Value; } public bool Equals(RuntimeEventHandle handle) { return value == handle.Value; } public override int GetHashCode() { return value.GetHashCode(); } public static bool operator ==(RuntimeEventHandle left, RuntimeEventHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeEventHandle left, RuntimeEventHandle right) { return !left.Equals(right); } } internal struct RuntimePropertyHandle : IEquatable<RuntimePropertyHandle> { private readonly IntPtr value; internal RuntimePropertyHandle(IntPtr v) { value = v; } public IntPtr Value => value; public override bool Equals(object? obj) { if (obj == null || GetType() != obj.GetType()) return false; return value == ((RuntimePropertyHandle)obj).Value; } public bool Equals(RuntimePropertyHandle handle) { return value == handle.Value; } public override int GetHashCode() { return value.GetHashCode(); } public static bool operator ==(RuntimePropertyHandle left, RuntimePropertyHandle right) { return left.Equals(right); } public static bool operator !=(RuntimePropertyHandle left, RuntimePropertyHandle right) { return !left.Equals(right); } } internal unsafe struct RuntimeGPtrArrayHandle { private RuntimeStructs.GPtrArray* value; internal RuntimeGPtrArrayHandle(RuntimeStructs.GPtrArray* value) { this.value = value; } internal RuntimeGPtrArrayHandle(IntPtr ptr) { this.value = (RuntimeStructs.GPtrArray*)ptr; } internal int Length => value->len; internal IntPtr this[int i] => Lookup(i); internal IntPtr Lookup(int i) { if (i >= 0 && i < Length) { return value->data[i]; } else throw new IndexOutOfRangeException(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GPtrArrayFree(RuntimeStructs.GPtrArray* value); internal static void DestroyAndFree(ref RuntimeGPtrArrayHandle h) { GPtrArrayFree(h.value); h.value = null; } } }
-1